// Agent drill-down for Leader view — takes `history` object from /api/history.

function AgentDrilldown({ history, onBack, loading }) {
  const kpis = KPI_DEFS;
  const ink = REM.linen;
  const muted = 'rgba(240,238,234,.55)';
  const hair = 'rgba(240,238,234,.14)';
  const [selKpi, setSelKpi] = React.useState('contacts');

  const agent = history?.agent || { name: '', role: '', initials: '', targets: {} };
  const today = history?.today || '';
  const streak = history?.streak ?? 0;

  // Build 30-day series for the selected KPI
  const byDate = new Map((history?.rows || []).map(r => [r.date, r]));
  const dateList = lastNDays(30, today);
  const series = dateList.map(d => {
    const row = byDate.get(d);
    return {
      date: d,
      v: row ? (row.values[selKpi] || 0) : null,
      missed: !row && !isWeekendISO(d) && d !== today,
      weekend: isWeekendISO(d),
      pending: d === today && !row,
    };
  });
  const vals = series.filter(s => s.v != null).map(s => s.v);
  const max = Math.max(...vals, 1);
  const avg = vals.length ? Math.round(vals.reduce((a,b)=>a+b,0)/vals.length) : 0;
  const total = vals.reduce((a,b)=>a+b,0);
  const kpiDef = kpis.find(k => k.id === selKpi);

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%', background: REM.obsidian, color: ink }}>
      <PhoneChrome
        dark
        left={<Press onClick={onBack} style={{ padding: 6 }}>
          <svg width="20" height="12" viewBox="0 0 20 12"><path d="M6 1L1 6l5 5M1 6h18" stroke={ink} strokeWidth="1" fill="none" strokeLinecap="round"/></svg>
        </Press>}
        right={<Eyebrow color={muted} size={9}>{loading ? 'Loading…' : ''}</Eyebrow>}
      />

      <div style={{ flex:1, overflow:'auto' }}>
        <div style={{ padding: '18px 20px 20px', borderBottom: `1px solid ${hair}` }}>
          <Eyebrow color={muted}>{agent.role} · 30-day window</Eyebrow>
          <div style={{
            marginTop: 10, fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 42,
            lineHeight: 1, letterSpacing: '-0.025em', color: ink,
          }}>{agent.name || '—'}</div>
          <div style={{ marginTop: 16, display:'flex', gap: 32 }}>
            <StatBlock eyebrow="Streak" value={streak} suffix="days" dark/>
            <StatBlock eyebrow="Logged" value={vals.length} suffix="/ 30" dark/>
          </div>
        </div>

        <div style={{ borderBottom: `1px solid ${hair}`, padding: '12px 12px', display:'flex', gap: 6, overflowX:'auto' }}>
          {kpis.map(k => {
            const on = selKpi === k.id;
            return (
              <Press key={k.id} haptic={false} onClick={() => setSelKpi(k.id)}
                style={{
                  padding: '8px 14px',
                  background: on ? REM.linen : 'transparent',
                  color: on ? REM.obsidian : ink,
                  border: `1px solid ${on ? REM.linen : 'rgba(240,238,234,.3)'}`,
                  flexShrink: 0,
                }}>
                <Eyebrow color={on ? REM.obsidian : ink} size={10}>{k.short}</Eyebrow>
              </Press>
            );
          })}
        </div>

        <div style={{ padding: '22px 20px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom: 18 }}>
            <div>
              <Eyebrow color={muted}>{kpiDef.label} · total</Eyebrow>
              <div style={{
                marginTop: 8, fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 56, lineHeight: 1,
                letterSpacing:'-0.03em', color: ink, fontVariantNumeric:'tabular-nums',
              }}>{total}</div>
            </div>
            <div style={{ textAlign:'right' }}>
              <Eyebrow color={muted}>Daily avg</Eyebrow>
              <div style={{
                marginTop: 8, fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 28, lineHeight: 1,
                letterSpacing:'-0.02em', color: ink, fontVariantNumeric:'tabular-nums',
              }}>{avg}</div>
            </div>
          </div>

          <div style={{ position:'relative', height: 160, display:'flex', alignItems:'flex-end', gap: 3, borderBottom: `1px solid ${hair}` }}>
            {series.map((s, i) => {
              const h = s.v != null ? Math.max(2, (s.v / max) * 150) : 0;
              return (
                <div key={i} style={{ flex:1, display:'flex', alignItems:'flex-end', justifyContent:'center', height: '100%' }}>
                  {s.missed ? (
                    <div style={{ width: '60%', height: 6, background: '#B23A2E', opacity: .9 }}/>
                  ) : s.weekend ? (
                    <div style={{ width: '60%', height: 2, background: 'rgba(240,238,234,.08)' }}/>
                  ) : s.pending ? (
                    <div style={{ width: '80%', height: 6, background: 'rgba(240,238,234,.25)', borderTop: `2px solid ${REM.sage}` }}/>
                  ) : (
                    <div style={{ width: '80%', height: h, background: i === series.length - 1 ? REM.sage : REM.linen, opacity: i === series.length - 1 ? 1 : .9 }}/>
                  )}
                </div>
              );
            })}
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', marginTop: 10 }}>
            <Eyebrow color={muted} size={9}>30 days ago</Eyebrow>
            <Eyebrow color={muted} size={9}>Today</Eyebrow>
          </div>

          <div style={{ marginTop: 20, display:'flex', gap: 16, flexWrap:'wrap' }}>
            <Legend color={REM.linen} label="Logged"/>
            <Legend color="#B23A2E" label="Missed"/>
            <Legend color="rgba(240,238,234,.3)" label="Weekend"/>
          </div>
        </div>

        <div style={{ padding: '6px 20px 10px' }}>
          <Eyebrow color={muted}>Recent entries</Eyebrow>
        </div>
        <div style={{ paddingBottom: 40 }}>
          {[...series].reverse().slice(0, 10).map((s, i) => {
            const d = new Date(s.date + 'T12:00:00Z');
            const md = `${String(d.getUTCMonth()+1).padStart(2,'0')}.${String(d.getUTCDate()).padStart(2,'0')}`;
            const dow = d.toLocaleDateString('en-US',{weekday:'short', timeZone:'UTC'}).toUpperCase();
            return (
              <div key={i} style={{
                padding: '14px 20px', borderTop: `1px solid ${hair}`,
                display:'grid', gridTemplateColumns: 'auto 1fr auto', gap: 14, alignItems:'center',
              }}>
                <div style={{ width: 52 }}>
                  <Eyebrow color={muted} size={9}>{dow}</Eyebrow>
                  <div style={{ marginTop: 2, fontFamily: REM.fontBody, fontSize: 13, color: ink, fontVariantNumeric:'tabular-nums' }}>{md}</div>
                </div>
                <div style={{ fontFamily: REM.fontBody, fontSize: 13, color: muted }}>
                  {s.weekend ? '—' :
                   s.missed ? <span style={{ color: '#E98474' }}>No entry</span> :
                   s.pending ? <span style={{ color: REM.sage }}>Pending today</span> :
                   s.v != null ? `${s.v} ${kpiDef.short.toLowerCase()}` : '—'}
                </div>
                <div style={{ minWidth: 60 }}>
                  {s.v != null && (
                    <div style={{ height: 2, background: 'rgba(240,238,234,.14)', position:'relative' }}>
                      <div style={{ position:'absolute', inset:0, width: `${Math.min(100, (s.v/max)*100)}%`, background: REM.sage }}/>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function Legend({ color, label }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
      <div style={{ width: 12, height: 6, background: color }}/>
      <Eyebrow color="rgba(240,238,234,.55)" size={9}>{label}</Eyebrow>
    </div>
  );
}

Object.assign(window, { AgentDrilldown });
