// Team Leader dashboard — takes a live `team` object from /api/team.

function TeamDashboard({ team, onOpenAgent, onLogout, onRefresh, loading }) {
  const kpis = KPI_DEFS;
  const ink = REM.linen;
  const muted = 'rgba(240,238,234,.55)';
  const hair = 'rgba(240,238,234,.14)';

  const agents = team.agents || [];
  const teamTotals = team.teamTotals || zeroValues();
  const teamTargets = team.teamTargets || zeroValues();
  const loggedToday = agents.filter(a => a.loggedToday).length;

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%', background: REM.obsidian, color: ink }}>
      <PhoneChrome
        dark={true}
        left={<Press onClick={onRefresh} haptic={false} style={{ padding: 6 }}>
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
            <path d="M3 10a7 7 0 1 1 2 4.95M3 16v-4h4" stroke={ink} strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </Press>}
        right={<Press onClick={onLogout} haptic={false} style={{ padding: 6 }}>
          <Eyebrow color={ink} size={10}>Sign out</Eyebrow>
        </Press>}
      />

      <div style={{ flex:1, overflow:'auto' }}>
        <div style={{ padding: '22px 20px 20px', borderBottom: `1px solid ${hair}` }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 12 }}>
            <Eyebrow color={muted}>Team · Remnant R.E.</Eyebrow>
            <Eyebrow color={muted}>{loggedToday} of {agents.length} logged</Eyebrow>
          </div>
          <div style={{
            fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 44, lineHeight: .98,
            letterSpacing: '-0.025em', color: ink,
          }}>
            The <span style={{ color: REM.sage, fontStyle:'italic', fontWeight: 400 }}>scorecard.</span>
          </div>
          <div style={{ marginTop: 14 }}>
            <Eyebrow color={muted} size={9}>Week of {fmtDate(team.monday)} · through {fmtDate(team.today)}</Eyebrow>
          </div>
        </div>

        {/* Team weekly totals */}
        <div style={{ padding: '22px 20px 4px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 16 }}>
            <Eyebrow color={muted}>Week-to-date · team</Eyebrow>
            <Eyebrow color={muted}>Targets</Eyebrow>
          </div>
          {kpis.map(k => {
            const have = teamTotals[k.id] || 0;
            const target = teamTargets[k.id] || 0;
            const pct = target > 0 ? Math.round((have/target)*100) : 0;
            return (
              <div key={k.id} style={{ padding: '14px 0', borderTop: `1px solid ${hair}` }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 10 }}>
                  <div style={{ display:'flex', alignItems:'baseline', gap: 10 }}>
                    <div style={{ fontFamily: REM.fontBody, fontSize: 14, color: ink }}>{k.label}</div>
                    <StatusDot pct={pct}/>
                  </div>
                  <div style={{ fontFamily: REM.fontBody, fontSize: 13, color: muted, fontVariantNumeric:'tabular-nums' }}>
                    <span style={{ color: ink, fontFamily: REM.fontDisplay, fontSize: 18, letterSpacing:'-0.01em', marginRight: 6 }}>{have}</span>
                    / {target} · <span style={{ color: statusColor(pct) }}>{pct}%</span>
                  </div>
                </div>
                <ProgressBar pct={pct} dark accent={statusColor(pct)}/>
              </div>
            );
          })}
        </div>

        <div style={{ padding: '28px 20px 8px' }}>
          <Eyebrow color={muted}>By agent</Eyebrow>
        </div>
        <div>
          {agents.map(a => <AgentRow key={a.id} agent={a} onClick={() => onOpenAgent(a)}/>)}
          {agents.length === 0 && (
            <div style={{ padding: '24px 20px', color: muted, fontFamily: REM.fontBody, fontSize: 13 }}>
              No active agents in the roster. Add rows in the Remnant Agents Notion DB.
            </div>
          )}
        </div>

        <div style={{ padding: '28px 20px 8px' }}>
          <Eyebrow color={muted}>4-week trend · team</Eyebrow>
        </div>
        <div style={{ padding: '0 20px 40px' }}>
          {kpis.map(k => <TrendLine key={k.id} kpi={k} agents={agents} today={team.today}/>)}
        </div>

        {loading && (
          <div style={{ padding: '12px 20px 28px', textAlign: 'center' }}>
            <Eyebrow color={muted} size={9}>Refreshing…</Eyebrow>
          </div>
        )}
      </div>
    </div>
  );
}

function AgentRow({ agent, onClick }) {
  const ink = REM.linen;
  const muted = 'rgba(240,238,234,.55)';
  const hair = 'rgba(240,238,234,.14)';

  const contactsWTD = agent.wtd.contacts || 0;
  const contactsTarget = agent.targets.contacts || 0;
  const pct = contactsTarget > 0 ? Math.round(contactsWTD / contactsTarget * 100) : 0;

  const todayContacts = agent.todayRow ? (agent.todayRow.values.contacts || 0) : null;
  const loggedToday = agent.loggedToday;

  return (
    <Press onClick={onClick} haptic={false} style={{ width: '100%', display: 'block', textAlign: 'left' }}>
      <div style={{ padding: '18px 20px', borderTop: `1px solid ${hair}`, display:'grid', gridTemplateColumns: 'auto 1fr auto', gap: 14, alignItems: 'center' }}>
        <div style={{
          width: 44, height: 44, borderRadius: 999,
          background: loggedToday ? REM.sage : 'rgba(240,238,234,.08)',
          display:'grid', placeItems:'center',
          fontFamily: REM.fontSub, fontWeight: 700, fontSize: 12, letterSpacing:'.1em',
          color: loggedToday ? REM.abyss : ink,
        }}>{agent.initials}</div>

        <div style={{ minWidth: 0 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap: 8 }}>
            <div style={{ fontFamily: REM.fontDisplay, fontSize: 18, fontWeight: 500, color: ink, letterSpacing:'-0.01em' }}>{agent.name}</div>
          </div>
          <div style={{ marginTop: 6, display:'flex', gap: 16, alignItems:'baseline' }}>
            <div style={{ display:'flex', alignItems:'baseline', gap: 5 }}>
              <Eyebrow color={muted} size={9}>Today</Eyebrow>
              <span style={{ fontFamily: REM.fontBody, fontSize: 13, color: loggedToday ? ink : muted, fontVariantNumeric:'tabular-nums' }}>
                {loggedToday ? todayContacts : '—'}
              </span>
            </div>
            <div style={{ display:'flex', alignItems:'baseline', gap: 5 }}>
              <Eyebrow color={muted} size={9}>Contacts WTD</Eyebrow>
              <span style={{ fontFamily: REM.fontBody, fontSize: 13, color: ink, fontVariantNumeric:'tabular-nums' }}>
                {contactsWTD}
              </span>
            </div>
          </div>
          <div style={{ marginTop: 10, maxWidth: 180 }}>
            <ProgressBar pct={pct} dark accent={statusColor(pct)}/>
          </div>
        </div>

        <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap: 4 }}>
          <div style={{
            fontFamily: REM.fontDisplay, fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em',
            color: statusColor(pct), fontVariantNumeric:'tabular-nums', lineHeight: 1,
          }}>{pct}<span style={{ fontSize: 13 }}>%</span></div>
          <Eyebrow color={muted} size={9}>Goal</Eyebrow>
        </div>
      </div>
    </Press>
  );
}

function TrendLine({ kpi, agents, today }) {
  const ink = REM.linen;
  const muted = 'rgba(240,238,234,.55)';
  const days = 28;
  const dateList = lastNDays(days, today);

  const series = dateList.map(d => {
    let total = 0;
    for (const a of agents) {
      const row = (a.history || []).find(r => r.date === d);
      if (row) total += row.values[kpi.id] || 0;
    }
    return total;
  });

  const max = Math.max(...series, 1);
  const W = 350, H = 44, pad = 2;
  const points = series.map((v, i) => {
    const x = pad + (i / (series.length - 1 || 1)) * (W - pad*2);
    const y = H - pad - (v / max) * (H - pad*2);
    return [x, y];
  });
  const d = points.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const last = points[points.length - 1] || [0, 0];
  const sum = series.reduce((a,b) => a+b, 0);

  return (
    <div style={{ padding: '14px 0', borderTop: `1px solid rgba(240,238,234,.14)` }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 6 }}>
        <div style={{ fontFamily: REM.fontBody, fontSize: 13, color: ink }}>{kpi.label}</div>
        <div style={{ fontFamily: REM.fontBody, fontSize: 12, color: muted, fontVariantNumeric:'tabular-nums' }}>
          <span style={{ color: ink, fontFamily: REM.fontDisplay, fontSize: 14, marginRight: 4 }}>{sum}</span>· 4 weeks
        </div>
      </div>
      <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display:'block' }}>
        {[7, 14, 21].map(w => {
          const x = pad + (w / (series.length - 1 || 1)) * (W - pad*2);
          return <line key={w} x1={x} x2={x} y1={0} y2={H} stroke="rgba(240,238,234,.08)" strokeWidth="1" strokeDasharray="2 3"/>;
        })}
        <path d={d} stroke={REM.sage} strokeWidth="1.25" fill="none" strokeLinejoin="round" strokeLinecap="round"/>
        <circle cx={last[0]} cy={last[1]} r="2.5" fill={REM.sage}/>
      </svg>
    </div>
  );
}

Object.assign(window, { TeamDashboard });
