// Henry's widgets: Agents strip, Blockers, Priorities, Client Health, Goals,
// Transcript Recs, Churn Risk placeholder, plus the Client detail Drawer body.

const { Monogram, WidgetCard, Sparkline, Empty, ExtArrow } = window.DC;

// ── KPI Strip (Revenue MTD lead) ────────────────────────────────────────────
function KPIStrip({ kpis }) {
  if (!kpis) return null;
  const items = [
    { ...kpis.revenueMTD,    key: 'rev',     emphasis: true  },
    { ...kpis.demosBooked,   key: 'demos',   emphasis: false },
    { ...kpis.activeClients, key: 'clients', emphasis: false },
  ].filter(k => k.label);
  const trendColor = (t) => t === 'good' ? 'var(--status-green)' : t === 'warn' ? 'var(--status-amber)' : 'var(--ink-soft)';
  return (
    <section className="card card-elev" style={{ padding: 0 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
        {items.map((k, i) => (
          <div key={k.key} style={{
            flex: k.emphasis ? '1.4 1 280px' : '1 1 220px', minWidth: 0,
            borderRight: i < items.length - 1 ? '1px solid var(--border)' : 'none',
            padding: 'var(--pad-card)',
            background: k.emphasis ? 'rgba(248,197,48,.05)' : 'transparent',
            position: 'relative',
          }}>
            {k.emphasis && (
              <span style={{
                position: 'absolute', top: 10, right: 12,
                fontSize: 9.5, fontWeight: 600, letterSpacing: '0.08em',
                color: 'var(--gold-deep)', textTransform: 'uppercase',
              }}>Headline</span>
            )}
            <div className="eyebrow" style={{ marginBottom: 6 }}>{k.label}</div>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
              <div>
                <div className="serif" style={{ fontSize: k.emphasis ? 38 : 30, lineHeight: 1, fontWeight: 400 }}>{k.value}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 4 }}>
                  <span style={{ color: trendColor(k.trend), fontWeight: 600 }}>{k.delta}</span>
                  <span style={{ margin: '0 6px', opacity: .4 }}>·</span>
                  <span>{k.target}</span>
                </div>
              </div>
              {k.series && (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                  <Sparkline series={k.series} width={88} height={36} sentiment={k.sentiment === 'down' ? 'bad' : k.sentiment === 'up' ? 'good' : undefined} goodIs={k.key === 'rev' ? 'up' : k.key === 'demos' ? 'up' : 'up'} />
                  <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-soft)', marginTop: 2 }}>
                    {k.prefix || ''}{k.series[0].toLocaleString()} → {k.prefix || ''}{k.series[k.series.length-1].toLocaleString()}
                  </span>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ── Recommend Focus box (one-sentence CTA above the fold) ───────────────────
function FocusBox({ focus }) {
  if (!focus) return null;
  const tone = focus.tone || 'amber';
  const accent = tone === 'amber' ? 'var(--status-amber)' : tone === 'red' ? 'var(--status-red)' : 'var(--forest-500)';
  const bg = tone === 'amber' ? 'rgba(248,197,48,.10)' : tone === 'red' ? 'rgba(154,42,42,.06)' : 'var(--surface-2)';
  return (
    <section style={{
      background: bg, border: `1px solid ${accent}`, borderLeft: `4px solid ${accent}`,
      padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
    }}>
      <span style={{
        fontSize: 9.5, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase',
        color: accent, whiteSpace: 'nowrap',
      }}>Recommend focus</span>
      <span style={{ fontSize: 14, color: 'var(--ink)', flex: 1, minWidth: 200 }}>
        {focus.headline}
      </span>
      <button className="btn-gold" style={{ whiteSpace: 'nowrap' }}>{focus.cta} →</button>
      {focus.source && <span style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{focus.source}</span>}
    </section>
  );
}

// ── Agent Status Panel ──────────────────────────────────────────────────────
function AgentStrip({ agents, expandedId, setExpandedId }) {
  if (!agents || !agents.length) return null;
  return (
    <section className="card card-elev" style={{ padding: 0 }}>
      <div className="agent-strip" style={{ display: 'flex', flexWrap: 'wrap' }}>
        {agents.map((a, i) => {
          const expanded = expandedId === a.id;
          return (
            <div key={a.id} style={{
              flex: '1 1 240px', minWidth: 0,
              borderRight: i < agents.length - 1 ? '1px solid var(--border)' : 'none',
              padding: 'var(--pad-card)',
              cursor: 'pointer',
              background: expanded ? 'var(--paper-100)' : 'transparent',
              transition: 'background .15s',
            }}
            onClick={() => setExpandedId(expanded ? null : a.id)}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Monogram initials={a.initials} tone={i % 2 === 0 ? 'forest' : 'gold'} size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{a.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-soft)', display: 'flex', gap: 6, alignItems: 'center', marginTop: 2 }}>
                    <span className="tag" style={{ padding: '1px 6px', fontSize: 9.5 }}>{a.role}</span>
                    {a.scope && <span style={{ fontSize: 9.5, color: 'var(--ink-soft)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>· {a.scope.replace('-', ' ')}</span>}
                    <span>· {timeAgo(a.lastRun)}</span>
                  </div>
                </div>
                {a.flaggedCount > 0 ? (
                  <span style={{
                    background: 'var(--gold)', color: 'var(--forest-900)',
                    fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em',
                    padding: '3px 7px', minWidth: 22, textAlign: 'center',
                  }}>{a.flaggedCount} for you</span>
                ) : (
                  <span style={{ fontSize: 10.5, color: 'var(--ink-soft)', fontStyle: 'italic' }}>quiet</span>
                )}
              </div>
              {expanded && (
                <ul style={{ margin: '12px 0 0 46px', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {a.priorities.map((p, j) => (
                    <li key={j} style={{ fontSize: 12.5, color: 'var(--ink)', display: 'flex', gap: 8 }}>
                      <span style={{ color: 'var(--forest-500)', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, lineHeight: '1.4' }}>0{j+1}</span>
                      <span style={{ flex: 1 }}>{p}</span>
                    </li>
                  ))}
                  {a.cta && (
                    <li style={{ marginTop: 6, marginLeft: -22 }}>
                      <button className="btn-mini primary" onClick={(e) => { e.stopPropagation(); a.cta.onClick && a.cta.onClick(); }}>
                        {a.cta.label} →
                      </button>
                    </li>
                  )}
                </ul>
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}

function timeAgo(iso) {
  const now = new Date('2026-04-29T09:00:00Z');
  const d = new Date(iso);
  const m = Math.round((now - d) / 60000);
  if (m < 60) return `${m}m ago`;
  const h = Math.round(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.round(h/24)}d ago`;
}

// ── Blockers Board (Kanban, 4 cols) ─────────────────────────────────────────
function BlockersBoard({ blockers, setBlockers }) {
  const cols = [
    { key: 'me',       label: 'On me',       sub: 'Henry'    },
    { key: 'team',     label: 'On team',     sub: 'Internal' },
    { key: 'client',   label: 'On client',   sub: 'Awaiting' },
    { key: 'external', label: 'External',    sub: 'Vendors'  },
  ];
  const [dragId, setDragId] = useState(null);
  const [overCol, setOverCol] = useState(null);

  const onDragStart = (id) => setDragId(id);
  const onDragOver  = (e, col) => { e.preventDefault(); setOverCol(col); };
  const onDrop      = (col) => {
    if (!dragId) return;
    setBlockers(prev => prev.map(b => b.id === dragId ? { ...b, owner: col } : b));
    setDragId(null); setOverCol(null);
  };

  return (
    <WidgetCard eyebrow="Workflow" title="Blockers" padded={true}>
      <div className="h-scroll blockers-board" style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(4, minmax(220px, 1fr))',
        gap: 10,
      }}>
        {cols.map(c => {
          const items = blockers.filter(b => b.owner === c.key);
          return (
            <div key={c.key}
                 onDragOver={(e) => onDragOver(e, c.key)}
                 onDrop={() => onDrop(c.key)}
                 style={{
                   background: 'var(--paper-100)',
                   border: overCol === c.key ? '1px dashed var(--gold-deep)' : '1px solid var(--border-soft)',
                   padding: 10, minHeight: 120,
                 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
                <span className="eyebrow">{c.label}</span>
                <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{items.length}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {items.length === 0 && (
                  <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', fontStyle: 'italic', padding: '8px 4px' }}>
                    {c.key === 'me' ? "Nothing on you." : c.key === 'team' ? "Nothing for the team." : c.key === 'client' ? "Nothing pending." : "All clear."}
                  </div>
                )}
                {items.map(b => {
                  const aged = b.ageDays > 5;
                  return (
                    <a key={b.id} href={b.clickupUrl} target="_blank" rel="noreferrer"
                       draggable
                       onDragStart={() => onDragStart(b.id)}
                       className={dragId === b.id ? 'dragging' : ''}
                       style={{
                         display: 'block',
                         background: aged ? 'rgba(154,42,42,.04)' : 'var(--surface-2)',
                         border: aged ? '1px solid rgba(154,42,42,.25)' : '1px solid var(--border)',
                         padding: 10,
                         textDecoration: 'none',
                         color: 'inherit',
                         cursor: 'grab',
                         borderLeft: aged ? '3px solid var(--status-red)' : '3px solid transparent',
                       }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 6, alignItems: 'flex-start' }}>
                        <span style={{ fontSize: 12.5, lineHeight: 1.3, fontWeight: 500 }}>{b.title}</span>
                        <ExtArrow />
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8, fontSize: 10.5, color: 'var(--ink-soft)' }}>
                        {b.client && <span>{b.client}</span>}
                        {b.client && <span style={{ opacity: .4 }}>·</span>}
                        <span>{b.ownerName}</span>
                        <span style={{
                          marginLeft: 'auto',
                          display: 'inline-flex', alignItems: 'center', gap: 4,
                          padding: aged ? '2px 6px' : '0',
                          background: aged ? 'var(--status-red)' : 'transparent',
                          color: aged ? 'var(--paper-50)' : 'var(--ink-soft)',
                          fontWeight: aged ? 700 : 400,
                          letterSpacing: aged ? '0.04em' : 'normal',
                        }}>
                          {aged && <span aria-hidden="true">⚑</span>}
                          {b.ageDays}d
                        </span>
                      </div>
                    </a>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 10, fontSize: 11, color: 'var(--ink-soft)', display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <span>Drag a card to reassign · aged &gt; 5d carry a flag</span>
        <span className="mono" style={{ opacity: .7 }}>External = ClickUp tag <span style={{ background: 'var(--paper-100)', padding: '1px 5px' }}>external-blocker</span></span>
      </div>
    </WidgetCard>
  );
}

// ── Top Priorities ──────────────────────────────────────────────────────────
function Priorities({ priorities, setPriorities }) {
  const [dragId, setDragId] = useState(null);
  const STATUS_ICON = { not_started: '○', in_progress: '◐', done: '●' };
  const STATUS_LABEL = { not_started: 'Not started', in_progress: 'In progress', done: 'Done' };
  const STATUS_COLOR = {
    not_started: 'var(--ink-soft)', in_progress: 'var(--status-amber)', done: 'var(--status-green)',
  };

  const onDragOver = (e, id) => { e.preventDefault();
    if (!dragId || dragId === id) return;
    setPriorities(prev => {
      const arr = [...prev];
      const from = arr.findIndex(p => p.id === dragId);
      const to   = arr.findIndex(p => p.id === id);
      if (from < 0 || to < 0) return prev;
      const [m] = arr.splice(from, 1);
      arr.splice(to, 0, m);
      return arr;
    });
  };

  return (
    <WidgetCard eyebrow="Today" title="Top priorities">
      <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 4 }}>
        {priorities.map((p, i) => (
          <li key={p.id}
              draggable
              onDragStart={() => setDragId(p.id)}
              onDragOver={(e) => onDragOver(e, p.id)}
              onDragEnd={() => setDragId(null)}
              className={dragId === p.id ? 'dragging' : ''}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 6px',
                borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)',
                cursor: 'grab',
              }}>
            <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)', width: 16 }}>0{i+1}</span>
            <span style={{ color: STATUS_COLOR[p.status], fontSize: 16, lineHeight: 1, width: 14 }}>{STATUS_ICON[p.status]}</span>
            <a href={p.clickupUrl} target="_blank" rel="noreferrer"
               style={{ flex: 1, fontSize: 13.5, color: 'var(--ink)', textDecoration: p.status === 'done' ? 'line-through' : 'none' }}>
              {p.title}
            </a>
            <span style={{ fontSize: 10.5, color: STATUS_COLOR[p.status], letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
              {STATUS_LABEL[p.status]}
            </span>
            <ExtArrow />
          </li>
        ))}
      </ul>
    </WidgetCard>
  );
}

// ── Client Health Grid ──────────────────────────────────────────────────────
function ClientHealth({ clients, onPickClient }) {
  const [filter, setFilter] = useState('all');
  const filters = [
    { k: 'all',    l: 'All' },
    { k: 'red',    l: 'Red' },
    { k: 'yellow', l: 'Yellow' },
    { k: 'green',  l: 'Green' },
  ];
  const visible = filter === 'all' ? clients : clients.filter(c => c.status === filter);
  const counts = {
    red:    clients.filter(c => c.status === 'red').length,
    yellow: clients.filter(c => c.status === 'yellow').length,
    green:  clients.filter(c => c.status === 'green').length,
  };
  return (
    <WidgetCard
      eyebrow="Portfolio"
      title="Client health"
      action={
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {filters.map(f => (
            <button key={f.k} onClick={() => setFilter(f.k)}
                    style={{
                      padding: '5px 10px', border: '1px solid var(--border)',
                      background: filter === f.k ? 'var(--ink)' : 'transparent',
                      color: filter === f.k ? 'var(--paper-50)' : 'var(--ink-soft)',
                      fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
                      cursor: 'pointer',
                    }}>
              {f.l}{f.k !== 'all' && counts[f.k] !== undefined && <span style={{ marginLeft: 6, opacity: .7 }}>{counts[f.k]}</span>}
            </button>
          ))}
        </div>
      }>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
        gap: 8,
      }}>
        {visible.map(c => (
          <button key={c.slug} onClick={() => onPickClient(c.slug)}
                  style={{
                    textAlign: 'left', cursor: 'pointer',
                    background: 'var(--surface-2)', border: '1px solid var(--border)',
                    padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 6,
                    borderTop: `3px solid ${
                      c.status === 'red' ? 'var(--status-red)' :
                      c.status === 'yellow' ? 'var(--status-amber)' :
                      'var(--status-green)'
                    }`,
                  }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <Monogram initials={c.initials} tone={c.tone} size={28} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{c.name}</div>
              </div>
              <span className={`pip ${c.status === 'red' ? 'red' : c.status === 'yellow' ? 'yellow' : 'green'}`} />
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink)', lineHeight: 1.3 }}>{c.drivingMetric}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 'auto', paddingTop: 4, borderTop: '1px dashed var(--border-soft)', fontSize: 10.5, color: 'var(--ink-soft)' }}>
              <span>CPB <span className="mono" style={{ color: 'var(--ink)' }}>${42 + ((c.slug.charCodeAt(0) + c.slug.length) % 60)}</span></span>
              <span>{c.daysSinceLastBooking}d since booked</span>
            </div>
          </button>
        ))}
        {visible.length === 0 && (
          <div style={{ gridColumn: '1 / -1' }}>
            <Empty icon="✓" title="All clear in this filter" />
          </div>
        )}
      </div>
    </WidgetCard>
  );
}

// ── Goals Tracker ───────────────────────────────────────────────────────────
function GoalsTracker({ goals }) {
  const items = Object.entries(goals).map(([k, g]) => ({ ...g, key: k }));
  const fmt = (g, v) => `${g.prefix || ''}${v.toLocaleString()}${g.suffix || ''}`;
  return (
    <WidgetCard eyebrow="April · supporting goals" title="Goals">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map(g => {
          const pct = Math.min(100, Math.round((g.current / g.target) * 100));
          const fillColor = pct >= 90 ? 'var(--status-green)' : pct >= 60 ? 'var(--gold-deep)' : 'var(--status-amber)';
          return (
            <div key={g.key}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{g.label}</span>
                <span style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>
                  <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{fmt(g, g.current)}</span>
                  <span style={{ margin: '0 4px', opacity: .5 }}>/</span>
                  <span>{fmt(g, g.target)}</span>
                  <span style={{ marginLeft: 8, color: fillColor, fontWeight: 600 }}>{pct}%</span>
                </span>
              </div>
              <div style={{ height: 4, background: 'var(--paper-100)', position: 'relative' }}>
                <div style={{ width: `${pct}%`, height: '100%', background: fillColor, transition: 'width .4s' }} />
              </div>
            </div>
          );
        })}
      </div>
    </WidgetCard>
  );
}

// ── Transcript Recommendations ──────────────────────────────────────────────
function TranscriptRecs({ recs, setRecs }) {
  const onAction = (id, action) => {
    console.log(`[transcript-rec] ${action} → ${id}`);
    setRecs(prev => prev.map(r => r.id === id ? { ...r, _action: action } : r));
  };
  const visible = recs.filter(r => !r._action || r._action === 'edit');
  return (
    <WidgetCard eyebrow="From calls this week" title="Transcript recs">
      <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column' }}>
        {visible.length === 0 && <Empty icon="”" title="Inbox zero" hint="No call recommendations to review." />}
        {visible.map((r, i) => (
          <li key={r.id} style={{ padding: '12px 0', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, marginBottom: 6 }}>
              <span style={{ fontSize: 11, color: 'var(--ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase', fontWeight: 600 }}>
                {r.callTitle}
              </span>
              <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{r.callDate}</span>
            </div>
            <p style={{ margin: '0 0 10px', fontSize: 13.5, lineHeight: 1.45 }}>{r.recommendation}</p>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <button className="btn-mini primary" onClick={() => onAction(r.id, 'approve')}>Approve</button>
              <button className="btn-mini" onClick={() => onAction(r.id, 'edit')}>Edit</button>
              <button className="btn-mini danger" onClick={() => onAction(r.id, 'dismiss')}>Dismiss</button>
              {r._action === 'edit' && <span style={{ fontSize: 11, color: 'var(--gold-deep)', alignSelf: 'center' }}>Editing…</span>}
            </div>
          </li>
        ))}
      </ul>
    </WidgetCard>
  );
}

// ── Churn Risk (placeholder) ────────────────────────────────────────────────
function ChurnRisk() {
  return (
    <WidgetCard eyebrow="In development" title="Churn risk"
      action={<span className="tag">Coming soon</span>}>
      <p style={{ margin: 0, fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5, maxWidth: 480 }}>
        We're building a model that scores accounts on disengagement signals — missed monthly reviews,
        slow client replies, declining estimator booking rate — to flag clients before they ask to pause.
        First pass ships in May.
      </p>
      <div style={{ marginTop: 14, height: 60, position: 'relative' }}>
        <svg width="100%" height="60" viewBox="0 0 400 60" preserveAspectRatio="none">
          <defs>
            <pattern id="hatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke="var(--rule-soft)" strokeWidth="1" />
            </pattern>
          </defs>
          <rect width="400" height="60" fill="url(#hatch)" />
        </svg>
      </div>
    </WidgetCard>
  );
}

// ── Client Drawer body (rich, scrollable) ───────────────────────────────────
function ClientDrawerBody({ slug, onClose }) {
  if (!slug) return null;
  const detail = window.DC_DATA.getClientDrawerData(slug);
  const { client, status, statusReason, summary, metaMetrics, cplSeries, bookingSeries, clickupActivity, recentCalls, lastUpdated } = detail;
  const statusColor = status === 'red' ? 'var(--status-red)' : status === 'yellow' ? 'var(--status-amber)' : 'var(--status-green)';
  const fmtAgo = (iso) => {
    const m = Math.round((new Date('2026-04-29T09:00:00Z') - new Date(iso)) / 60000);
    if (m < 60) return `${m}m`;
    const h = Math.round(m/60); return h < 24 ? `${h}h` : `${Math.round(h/24)}d`;
  };
  return (
    <React.Fragment>
      <header style={{ padding: '18px 20px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <Monogram initials={client.initials} tone={client.tone} size={40} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="eyebrow">Client detail</div>
          <h2 className="serif" style={{ margin: 0, fontSize: 24, lineHeight: 1.05, fontWeight: 400 }}>{client.name}</h2>
        </div>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: statusColor, fontWeight: 600, whiteSpace: 'nowrap' }}>
          <span className={`pip ${status === 'red' ? 'red' : status === 'yellow' ? 'yellow' : 'green'}`} />
          {status} <span style={{ opacity: .6, fontWeight: 500, textTransform: 'none', letterSpacing: 0 }}>· {statusReason}</span>
        </span>
        <button onClick={onClose} aria-label="Close" style={{
          background: 'transparent', border: 0, fontSize: 22, cursor: 'pointer', color: 'var(--ink-soft)', padding: '0 4px',
        }}>×</button>
      </header>

      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink)', borderLeft: `3px solid ${statusColor}`, paddingLeft: 12 }}>{summary}</div>

        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <a className="btn-mini" href="#" target="_blank" rel="noreferrer">ClickUp <ExtArrow /></a>
          <a className="btn-mini" href="#" target="_blank" rel="noreferrer">Meta Ads <ExtArrow /></a>
          <a className="btn-mini" href="#" target="_blank" rel="noreferrer">GHL <ExtArrow /></a>
          <button className="btn-mini primary">Schedule call</button>
        </div>

        <section>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <div className="eyebrow">Meta · last 14 days</div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-soft)' }}>updated {fmtAgo(lastUpdated.meta)} ago</span>
          </div>
          <div className="cd-meta-grid" style={{ display: 'grid', gap: 8 }}>
            {metaMetrics.map((m, i) => (
              <div key={m.k} style={{ background: i === 0 ? 'rgba(248,197,48,.08)' : 'var(--paper-100)', padding: 10, borderTop: i === 0 ? '2px solid var(--gold)' : 'none' }}>
                <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{m.k}</div>
                <div className="serif" style={{ fontSize: 22, lineHeight: 1.05, marginTop: 4 }}>{m.v}</div>
                <div style={{ fontSize: 10.5, color: m.good ? 'var(--status-green)' : 'var(--status-amber)', marginTop: 3, fontWeight: 600 }}>{m.cmp}</div>
              </div>
            ))}
          </div>
        </section>

        <section className="cd-spark-pair" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {[
            { l: 'Cost / booked', s: cplSeries,    color: 'var(--forest-700)', prefix: '$' },
            { l: 'Bookings / day', s: bookingSeries, color: 'var(--gold-deep)', prefix: '' },
          ].map((c, i) => {
            const lo = Math.min(...c.s), hi = Math.max(...c.s);
            const first = c.s[0], last = c.s[c.s.length-1];
            const trendBad = c.l.startsWith('Cost') ? last > first : last < first;
            return (
              <div key={i} style={{ border: '1px solid var(--border)', padding: 12 }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>{c.l}</div>
                <Sparkline series={c.s} width={220} height={56} color={c.color} />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 6 }}>
                  <span className="mono">{c.prefix}{first} → {c.prefix}{last}</span>
                  <span className="mono">lo {c.prefix}{lo} · hi {c.prefix}{hi}</span>
                </div>
                <div style={{ fontSize: 10.5, marginTop: 4, color: trendBad ? 'var(--status-amber)' : 'var(--status-green)', fontWeight: 600 }}>
                  {trendBad ? '▲ trending wrong way' : '▼ trending right way'}
                </div>
              </div>
            );
          })}
        </section>

        <section style={{ border: '1px solid var(--border)', padding: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8, gap: 12 }}>
            <div className="eyebrow">Recent calls · {recentCalls.count30d} in last 30d</div>
            <button onClick={() => { onClose && onClose(); window.dispatchEvent(new CustomEvent('dc:nav', { detail: 'transcripts' })); }} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, color: 'var(--forest-700)', borderBottom: '1px solid currentColor', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>View all →</button>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginBottom: 6 }}>
            <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{recentCalls.latest.title}</span>
            <span className="mono" style={{ marginLeft: 8 }}>{recentCalls.latest.date}</span>
          </div>
          <ul style={{ margin: '0 0 12px', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
            {recentCalls.latest.bullets.map((b, i) => (
              <li key={i} style={{ display: 'flex', gap: 8, fontSize: 13, lineHeight: 1.45 }}>
                <span style={{ color: 'var(--gold-deep)' }}>·</span>
                <span style={{ flex: 1 }}>{b}</span>
              </li>
            ))}
          </ul>
          <div style={{ borderTop: '1px solid var(--border-soft)', paddingTop: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>
            {recentCalls.others.map((o, i) => (
              <a key={i} href="#" style={{ display: 'grid', gridTemplateColumns: '70px 1fr', gap: 10, fontSize: 12, color: 'var(--ink-soft)', padding: '4px 0' }}>
                <span className="mono">{o.date}</span>
                <span><span style={{ color: 'var(--ink)', fontWeight: 500 }}>{o.title}</span> — {o.snippet}</span>
              </a>
            ))}
          </div>
        </section>

        <section>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <div className="eyebrow">Recent ClickUp activity</div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-soft)' }}>updated {fmtAgo(lastUpdated.clickup)} ago</span>
          </div>
          <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
            {clickupActivity.map((a, i) => (
              <li key={i}>
                <a href={a.url} target="_blank" rel="noreferrer" style={{
                  display: 'grid', gridTemplateColumns: '60px 70px 1fr auto', gap: 10,
                  padding: '8px 0', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)',
                  fontSize: 12.5, color: 'inherit',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--paper-100)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <span className="mono" style={{ color: 'var(--ink-soft)' }}>{a.date}</span>
                  <span style={{ color: 'var(--forest-700)', fontWeight: 600 }}>{a.who}</span>
                  <span style={{ color: 'var(--ink)' }}>{a.text}</span>
                  <ExtArrow />
                </a>
              </li>
            ))}
          </ul>
        </section>

        <div style={{ height: 24 }} />
      </div>
    </React.Fragment>
  );
}

window.DC = Object.assign(window.DC || {}, {
  AgentStrip, BlockersBoard, Priorities, ClientHealth, GoalsTracker,
  TranscriptRecs, ChurnRisk, ClientDrawerBody, KPIStrip, FocusBox,
});
