// KPI Detail Screen — full page with deep detail per agreed KPI

const KPI_DETAIL_DATA = {
  bookings: {
    history: [
      { date: 'Apr 1', actual: 14, target: 16 }, { date: 'Apr 8', actual: 22, target: 18 },
      { date: 'Apr 15', actual: 19, target: 20 }, { date: 'Apr 22', actual: 38, target: 22 },
      { date: 'Apr 29', actual: 96, target: 24 }, { date: 'May 6', actual: 31, target: 26 },
      { date: 'May 13', actual: 28, target: 28 }, { date: 'May 20', actual: 34, target: 30 },
      { date: 'May 27', actual: 36, target: 30 }, { date: 'Jun 3', actual: 41, target: 32 },
      { date: 'Jun 10', actual: 53, target: 32 }, { date: 'Jun 17', actual: 0, target: 32, forecast: 36 },
      { date: 'Jun 24', actual: 0, target: 30, forecast: 38 },
    ],
    breakdown: [
      { label: 'Direct (organic + brand)', value: 168, share: 41, color: '#10b981' },
      { label: 'Google Ads',                value: 122, share: 30, color: '#2563eb' },
      { label: 'Sykes',                     value: 78,  share: 19, color: '#d97706' },
      { label: 'Hoseasons',                 value: 32,  share: 8,  color: '#7c3aed' },
      { label: 'Other OTAs',                value: 12,  share: 3,  color: '#6b7280' },
    ],
    forecast: { value: 494, vsTarget: '+14 nights', tone: 'positive', confidence: 'High · 87%' },
    activity: [
      { date: 'Apr 29', body: 'Easter + bank holiday delivered 96 nights vs forecast 78. Knock-on into May expected.', who: 'Joe Marshall' },
      { date: 'May 12', body: 'Performance Max budget reallocated from Hosp Display → Lodge Search. Bookings cost dropped £4.20.', who: 'Matt Jones' },
      { date: 'Jun 8',  body: 'Late availability email sent to 14k subscribers — 38 incremental nights booked in 72h.', who: 'Hayley Roberts' },
    ],
    actions: [
      'Approve June half-term promotional spend lift (+£4k)',
      'Review whether to re-baseline Q3 target upwards',
    ],
  },
  revenue: {
    history: [
      { date: 'Apr 1', actual: 5400, target: 6100 }, { date: 'Apr 8', actual: 8800, target: 6900 },
      { date: 'Apr 15', actual: 7600, target: 7700 }, { date: 'Apr 22', actual: 14600, target: 8400 },
      { date: 'Apr 29', actual: 36800, target: 9200 }, { date: 'May 6', actual: 11900, target: 10000 },
      { date: 'May 13', actual: 10800, target: 10800 }, { date: 'May 20', actual: 13100, target: 11500 },
      { date: 'May 27', actual: 13900, target: 11500 }, { date: 'Jun 3', actual: 15800, target: 12300 },
      { date: 'Jun 10', actual: 19720, target: 12300 },
    ],
    breakdown: [
      { label: 'Direct',     value: 64720, share: 41, color: '#10b981' },
      { label: 'Google Ads', value: 47260, share: 30, color: '#2563eb' },
      { label: 'Sykes',      value: 29960, share: 19, color: '#d97706' },
      { label: 'Hoseasons',  value: 12480, share: 8,  color: '#7c3aed' },
      { label: 'Other',      value: 4000,  share: 2,  color: '#6b7280' },
    ],
    forecast: { value: 189200, vsTarget: '+£5.2k', tone: 'positive', confidence: 'High · 84%' },
    activity: [
      { date: 'May 3',  body: 'AOV up £41 vs LY thanks to longer mid-week stays in 3-bed lodges.', who: 'Joe Marshall' },
      { date: 'May 18', body: 'Cancellation rate dropped to 6.1% (was 8.7% Q1). Tighter deposit terms working.', who: 'Hayley Roberts' },
      { date: 'Jun 5',  body: 'Two large group bookings (£8.4k combined) for September — booked early via brand search.', who: 'Matt Jones' },
    ],
    actions: [
      'Confirm September pricing tier — early demand suggests +5% feasible',
      'Brief on AOV growth tactics for Q3 plan',
    ],
  },
  cpb: {
    history: [
      { date: 'Apr 1', actual: 38, target: 38 }, { date: 'Apr 8', actual: 36, target: 38 },
      { date: 'Apr 15', actual: 34, target: 38 }, { date: 'Apr 22', actual: 33, target: 38 },
      { date: 'Apr 29', actual: 29, target: 38 }, { date: 'May 6', actual: 31, target: 38 },
      { date: 'May 13', actual: 32, target: 38 }, { date: 'May 20', actual: 31, target: 38 },
      { date: 'May 27', actual: 30, target: 38 }, { date: 'Jun 3', actual: 32, target: 38 },
      { date: 'Jun 10', actual: 31, target: 38 },
    ],
    breakdown: [
      { label: 'Brand Search',       value: 8.40,  share: 4,  color: '#10b981' },
      { label: 'Generic Search',     value: 28.10, share: 38, color: '#2563eb' },
      { label: 'Performance Max',    value: 41.20, share: 36, color: '#d97706' },
      { label: 'Display + YouTube',  value: 62.90, share: 14, color: '#7c3aed' },
      { label: 'Sykes commission',   value: 78.50, share: 8,  color: '#6b7280' },
    ],
    forecast: { value: 30.80, vsTarget: '−£7.20 vs target', tone: 'positive', confidence: 'High · 91%' },
    activity: [
      { date: 'Apr 19', body: 'Branded auctions softened — Booking.com pulled brand bids. CPB on brand dropped to £6.20.', who: 'Matt Jones' },
      { date: 'May 8',  body: 'Reallocated 22% of Display budget into Generic Search. Generic CPB up £3, blended down £2.', who: 'Matt Jones' },
      { date: 'Jun 1',  body: 'Sykes commission rate review — accounting flagged 17% effective rate vs 15% contract.', who: 'Hayley Roberts' },
    ],
    actions: [
      'Resolve Sykes commission discrepancy (open ticket #4081)',
      'Decide whether to invest the CPB headroom in volume',
    ],
  },
  roas: {
    history: [
      { date: 'Apr 1', actual: 6.2, target: 6.5 }, { date: 'Apr 8', actual: 6.8, target: 6.5 },
      { date: 'Apr 15', actual: 7.1, target: 6.5 }, { date: 'Apr 22', actual: 7.4, target: 6.5 },
      { date: 'Apr 29', actual: 8.9, target: 6.5 }, { date: 'May 6', actual: 7.6, target: 6.5 },
      { date: 'May 13', actual: 7.3, target: 6.5 }, { date: 'May 20', actual: 7.5, target: 6.5 },
      { date: 'May 27', actual: 7.4, target: 6.5 }, { date: 'Jun 3', actual: 7.5, target: 6.5 },
      { date: 'Jun 10', actual: 7.6, target: 6.5 },
    ],
    breakdown: [
      { label: 'Brand Search',      value: 18.4, share: 35, color: '#10b981' },
      { label: 'Generic Search',    value: 6.2,  share: 28, color: '#2563eb' },
      { label: 'Performance Max',   value: 4.1,  share: 25, color: '#d97706' },
      { label: 'Display + YouTube', value: 1.8,  share: 8,  color: '#7c3aed' },
      { label: 'Email',             value: 22.3, share: 4,  color: '#0891b2' },
    ],
    forecast: { value: 7.5, vsTarget: '+1.0x vs target', tone: 'positive', confidence: 'Medium · 76%' },
    activity: [
      { date: 'Apr 25', body: 'PMax holding 4.1x ROAS — within target band. Search remains the engine at 11.2x blended.', who: 'Matt Jones' },
      { date: 'May 18', body: 'Display ROAS dipped to 1.8x. Recommend shift to YouTube view-through campaigns.', who: 'Matt Jones' },
      { date: 'Jun 4',  body: 'Email automation series shipped — driving 22.3x ROAS on new welcome flow.', who: 'Hayley Roberts' },
    ],
    actions: [
      'Approve Display → YouTube reallocation (£1.2k/month)',
      'Set Q3 ROAS target — current trajectory supports 7.0x',
    ],
  },
  directshare: {
    history: [
      { date: 'Apr 1', actual: 68, target: 70 }, { date: 'Apr 8', actual: 67, target: 70 },
      { date: 'Apr 15', actual: 66, target: 70 }, { date: 'Apr 22', actual: 64, target: 70 },
      { date: 'Apr 29', actual: 62, target: 70 }, { date: 'May 6', actual: 63, target: 70 },
      { date: 'May 13', actual: 64, target: 70 }, { date: 'May 20', actual: 64, target: 70 },
      { date: 'May 27', actual: 65, target: 70 }, { date: 'Jun 3', actual: 64, target: 70 },
      { date: 'Jun 10', actual: 64, target: 70 },
    ],
    breakdown: [
      { label: 'Direct (brand + organic)', value: 64, share: 64, color: '#10b981' },
      { label: 'Sykes',                    value: 19, share: 19, color: '#d97706' },
      { label: 'Hoseasons',                value: 8,  share: 8,  color: '#7c3aed' },
      { label: 'Booking.com',              value: 6,  share: 6,  color: '#1d4ed8' },
      { label: 'Airbnb + other',           value: 3,  share: 3,  color: '#6b7280' },
    ],
    forecast: { value: 67, vsTarget: '−3pp vs target', tone: 'warning', confidence: 'Medium · 72%' },
    activity: [
      { date: 'Apr 30', body: 'Sykes commissions ticking up — share of bookings rose from 14% to 19% over 8 weeks.', who: 'Joe Marshall' },
      { date: 'May 11', body: 'Brand search investment scheduled for May 14 — projected to recapture 4-5pp direct share.', who: 'Matt Jones' },
      { date: 'Jun 7',  body: 'Direct share holding at 64%; brand campaign delayed to Jun 18 due to creative review.', who: 'Hayley Roberts' },
    ],
    actions: [
      'Unblock brand creative review — biggest lever on this CPT',
      'Audit OTA contracts — Sykes margin review with Joe',
    ],
  },
  ownership: {
    history: [
      { date: 'Apr 1', actual: 4, target: 5 }, { date: 'Apr 8', actual: 5, target: 5 },
      { date: 'Apr 15', actual: 6, target: 5 }, { date: 'Apr 22', actual: 4, target: 5 },
      { date: 'Apr 29', actual: 5, target: 5 }, { date: 'May 6', actual: 6, target: 5 },
      { date: 'May 13', actual: 4, target: 5 }, { date: 'May 20', actual: 5, target: 5 },
      { date: 'May 27', actual: 5, target: 5 }, { date: 'Jun 3', actual: 4, target: 5 },
      { date: 'Jun 10', actual: 4, target: 5 },
    ],
    breakdown: [
      { label: 'Google Ads (ownership)', value: 21, share: 45, color: '#2563eb' },
      { label: 'Direct enquiry form',    value: 14, share: 30, color: '#10b981' },
      { label: 'Open day events',        value: 8,  share: 17, color: '#d97706' },
      { label: 'Referrals',              value: 4,  share: 8,  color: '#7c3aed' },
    ],
    forecast: { value: 58, vsTarget: '−2 leads', tone: 'warning', confidence: 'Medium · 68%' },
    activity: [
      { date: 'Apr 22', body: 'Qualified-lead rate now 38% (was 29% in Q1). Quality up even though volume is flat.', who: 'Hayley Roberts' },
      { date: 'May 9',  body: 'New ownership landing page published — bounce rate 41% (was 67%). Conversion +24%.', who: 'Joe Marshall' },
      { date: 'Jun 2',  body: 'Open day on June 22 — capacity 30 visitors, 21 confirmed. Expecting 6-8 enquiries.', who: 'Hayley Roberts' },
    ],
    actions: [
      'Confirm spend uplift on ownership Search (target: +12 leads in Q3)',
      'Schedule Q3 open day before peak season ends',
    ],
  },
};

const KpiDetailScreen = ({ kpiKey, onBack, setActive }) => {
  const kpi = window.AGREED_KPIS.find(k => k.key === kpiKey) || window.AGREED_KPIS[0];
  const detail = KPI_DETAIL_DATA[kpi.key] || KPI_DETAIL_DATA.bookings;
  const tone = STATUS_TONES[kpi.status] || STATUS_TONES['on-track'];
  const { LineChart, Line, XAxis, YAxis, Tooltip, CartesianGrid, ResponsiveContainer, ReferenceLine, Legend } = window.Recharts;

  const [noteOpen, setNoteOpen] = React.useState(false);
  const [note, setNote] = React.useState('');
  const [noteSent, setNoteSent] = React.useState(false);

  const fmt = (v) => formatKpi(v, kpi.unit);
  const deltaColor = kpi.deltaTone === 'warning' ? 'var(--warning)'
                  : kpi.deltaTone === 'negative' ? 'var(--negative)'
                  : 'var(--positive)';

  return (
    <div>
      {/* Breadcrumb / back */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 12, fontSize: 12 }}>
        <button onClick={onBack} style={{
          background: 'transparent', border: 'none', color: 'var(--text-muted)',
          cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, padding: 0,
          display: 'flex', alignItems: 'center', gap: 4,
        }}>
          <span style={{ width: 14, height: 14 }}>{I.chevLeft}</span>
          Dashboard
        </button>
        <span style={{ color: 'var(--text-faint)' }}>/</span>
        <span style={{ color: 'var(--text-muted)' }}>Performance Targets · Q2 2026</span>
        <span style={{ color: 'var(--text-faint)' }}>/</span>
        <span style={{ color: 'var(--text)', fontWeight: 500 }}>{kpi.label}</span>
      </div>

      {/* Hero */}
      <Card padding={0} style={{ marginBottom: 16 }}>
        <div style={{ padding: '20px 24px', display: 'flex', alignItems: 'flex-start', gap: 20, flexWrap: 'wrap' }}>
          <span style={{
            width: 56, height: 56, flexShrink: 0,
            borderRadius: 10,
            background: 'color-mix(in oklab, var(--primary) 12%, transparent)',
            color: 'var(--primary)',
            display: 'grid', placeItems: 'center',
          }}>
            <span style={{ display: 'block', transform: 'scale(1.6)' }}>{KPI_ICONS[kpi.key] || I.target}</span>
          </span>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <h1 style={{ fontSize: 24, fontWeight: 700, margin: 0, letterSpacing: '-0.02em' }}>{kpi.label}</h1>
              <span style={{
                fontSize: 11, fontWeight: 600, padding: '3px 8px', borderRadius: 99,
                background: tone.bg, color: tone.fg,
              }}>{tone.label}</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>{kpi.sub}</div>
            {/* Source line — explains how this CPT's value gets captured */}
            {(() => {
              const source = (window.SOURCE_META || {})[kpi.source];
              if (!source) return null;
              return (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                    padding: '3px 8px', borderRadius: 99,
                    background: source.bg, color: source.fg,
                    fontSize: 11, fontWeight: 600,
                  }}>
                    {kpi.source === 'google-ads' ? (
                      <span style={{
                        width: 6, height: 6, borderRadius: '50%',
                        background: 'currentColor',
                        boxShadow: '0 0 0 3px color-mix(in oklab, currentColor 25%, transparent)',
                        animation: 'kpiPulse 2s ease-in-out infinite',
                      }}/>
                    ) : (
                      <span style={{ width: 12, height: 12, display: 'inline-flex' }}>{source.icon}</span>
                    )}
                    {source.label}
                  </span>
                  <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>
                    {kpi.sourceDetail}
                  </span>
                  <span style={{ color: 'var(--text-faint)' }}>·</span>
                  <span style={{ fontSize: 11.5, color: 'var(--text-faint)' }}>{kpi.lastUpdated}</span>
                </div>
              );
            })()}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="secondary" icon={I.send} onClick={() => setNoteOpen(o => !o)}>Note for AM</Btn>
            <Btn variant="secondary" icon={I.ticket} onClick={() => setActive('tickets')}>Raise ticket</Btn>
            <Btn variant="secondary" icon={I.download}>Export</Btn>
            {(kpi.key === 'cpb' || kpi.key === 'roas' || kpi.key === 'ownership') && (
              <Btn variant="primary" icon={I.google} onClick={() => setActive('google')}>Open Google Ads</Btn>
            )}
          </div>
        </div>

        {/* Note composer */}
        {noteOpen && (
          <div style={{ borderTop: '1px solid var(--border)', padding: '14px 24px', background: 'var(--surface-2)' }}>
            {noteSent ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--positive)', fontSize: 13 }}>
                <span style={{ width: 18 }}>{I.check}</span>
                Sent to Joe Marshall — he'll reply within 1 working day.
              </div>
            ) : (
              <>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>
                  Note for Joe Marshall · Account Manager
                </div>
                <textarea value={note} onChange={e => setNote(e.target.value)}
                  placeholder={`Ask Joe a question about ${kpi.label.toLowerCase()}…`}
                  style={{
                    width: '100%', minHeight: 70, padding: 10, fontSize: 13,
                    border: '1px solid var(--border)', borderRadius: 6, background: 'var(--surface)',
                    color: 'var(--text)', fontFamily: 'inherit', resize: 'vertical',
                  }} />
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 8 }}>
                  <Btn variant="ghost" size="sm" onClick={() => { setNoteOpen(false); setNote(''); }}>Cancel</Btn>
                  <Btn variant="primary" size="sm" icon={I.send}
                    onClick={() => { if (note.trim()) { setNoteSent(true); setTimeout(() => { setNoteSent(false); setNoteOpen(false); setNote(''); }, 2200); } }}>
                    Send
                  </Btn>
                </div>
              </>
            )}
          </div>
        )}

        {/* Stat strip — or pending setup panel when the CPT isn't tracking yet */}
        {kpi.source === 'pending' ? (
          <div style={{ borderTop: '1px solid var(--border)', padding: '20px 24px', background: 'var(--surface-2)' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Awaiting setup</div>
                <div style={{ fontSize: 17, fontWeight: 600, marginTop: 4, color: 'var(--text)' }}>This Performance Target isn't tracking yet</div>
                <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 6, lineHeight: 1.55, maxWidth: 560 }}>
                  {kpi.note || 'Your account manager will set this up before the next review.'}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14, fontSize: 12, color: 'var(--text-muted)' }}>
                  <PersonAvatar name={kpi.owner} size={22} />
                  <span><span style={{ color: 'var(--text)', fontWeight: 600 }}>{kpi.owner}</span> · scheduled to enable for next monthly review</span>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 200 }}>
                <Btn variant="primary" icon={I.send} onClick={() => setNoteOpen(true)}>Ask AM to enable</Btn>
                <Btn variant="secondary">View setup checklist</Btn>
              </div>
            </div>
            {/* Setup steps */}
            <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px dashed var(--border)' }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 10 }}>Setup checklist</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  { done: true,  label: 'Performance Target defined and agreed with client' },
                  { done: true,  label: 'Target value set for Q2' },
                  { done: false, label: 'Connect HubSpot lead pipeline' },
                  { done: false, label: 'Map qualifying form fields' },
                  { done: false, label: 'First weekly value logged by AM' },
                ].map((s, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: s.done ? 'var(--text-muted)' : 'var(--text)' }}>
                    <span style={{
                      width: 16, height: 16, borderRadius: 4,
                      border: s.done ? 'none' : '1.5px dashed var(--text-faint)',
                      background: s.done ? 'var(--positive)' : 'transparent',
                      color: '#fff',
                      display: 'grid', placeItems: 'center',
                      fontSize: 10,
                    }}>{s.done && '✓'}</span>
                    <span style={{ textDecoration: s.done ? 'line-through' : 'none' }}>{s.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        ) : (
          <div style={{ borderTop: '1px solid var(--border)', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)' }}>
          {[
            { label: 'Actual',         value: fmt(kpi.actual),     sub: 'Quarter to date' },
            { label: 'Target',         value: fmt(kpi.target),     sub: 'Q2 2026 plan' },
            { label: 'YoY change',     value: kpi.delta,           sub: 'vs Q2 2025', color: deltaColor },
            { label: 'Forecast EoQ',   value: fmt(detail.forecast.value), sub: detail.forecast.vsTarget,
              color: detail.forecast.tone === 'warning' ? 'var(--warning)' : 'var(--positive)' },
          ].map((m, i) => (
            <div key={i} style={{
              padding: '14px 20px',
              borderRight: i < 3 ? '1px solid var(--border)' : 'none',
            }}>
              <div style={{ fontSize: 10, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>{m.label}</div>
              <div style={{ fontSize: 22, fontWeight: 700, marginTop: 4, fontVariantNumeric: 'tabular-nums', color: m.color || 'var(--text)' }}>{m.value}</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{m.sub}</div>
            </div>
          ))}
          </div>
        )}
      </Card>

      {/* Two-up: Trend chart + Forecast pacing */}
      {kpi.source !== 'pending' && (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16, marginBottom: 16 }}>
        {/* Trend chart */}
        <Card padding={0}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Trend · Actual vs target</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>Weekly · last 12 weeks</div>
            </div>
            <Btn variant="ghost" size="sm" iconRight={I.arrowRight}>View 90 days</Btn>
          </div>
          <div style={{ padding: 16, height: 280 }}>
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={detail.history} margin={{ top: 10, right: 16, left: -8, bottom: 0 }}>
                <CartesianGrid strokeDasharray="2 4" stroke="var(--border)" vertical={false} />
                <XAxis dataKey="date" tick={{ fontSize: 11, fill: 'var(--text-muted)' }} axisLine={{ stroke: 'var(--border)' }} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: 'var(--text-muted)' }} axisLine={false} tickLine={false} width={50} />
                <Tooltip
                  contentStyle={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 6, fontSize: 12 }}
                  labelStyle={{ color: 'var(--text)' }}
                  formatter={(v, name) => [fmt(v), name]}
                />
                <Line type="monotone" dataKey="target" stroke="var(--text-faint)" strokeWidth={1.5} strokeDasharray="4 4" dot={false} name="Target" />
                <Line type="monotone" dataKey="actual" stroke="var(--primary)" strokeWidth={2.5} dot={{ r: 3, fill: 'var(--primary)' }} activeDot={{ r: 5 }} name="Actual" />
                {detail.history.some(h => h.forecast) && (
                  <Line type="monotone" dataKey="forecast" stroke="var(--primary)" strokeWidth={2} strokeDasharray="3 3" dot={{ r: 3 }} name="Forecast" />
                )}
              </LineChart>
            </ResponsiveContainer>
          </div>
        </Card>

        {/* Pacing forecast */}
        <Card padding={0}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', fontWeight: 600, fontSize: 14 }}>End-of-quarter pacing</div>
          <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Forecast at quarter end</div>
              <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>{fmt(detail.forecast.value)}</div>
              <div style={{ fontSize: 12, color: detail.forecast.tone === 'warning' ? 'var(--warning)' : 'var(--positive)', fontWeight: 600, marginTop: 2 }}>{detail.forecast.vsTarget}</div>
            </div>
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--text-muted)', marginBottom: 6 }}>
                <span>Quarter progress</span>
                <span style={{ fontWeight: 600, color: 'var(--text)' }}>67%</span>
              </div>
              <div style={{ height: 6, borderRadius: 99, background: 'var(--surface-2)', overflow: 'hidden' }}>
                <div style={{ width: '67%', height: '100%', background: 'var(--text-faint)' }}/>
              </div>
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 4 }}>Forecast confidence</div>
              {detail.forecast.confidence}
            </div>
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12 }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 6 }}>Owner</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <PersonAvatar name={kpi.owner} size={28} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{kpi.owner}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Last reviewed today</div>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>
      )}

      {/* Two-up: Channel breakdown + Recommended actions */}
      {kpi.source !== 'pending' && (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        {/* Channel breakdown */}
        <Card padding={0}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', fontWeight: 600, fontSize: 14 }}>
            Breakdown by channel
            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, fontWeight: 400 }}>Quarter to date</div>
          </div>
          <div style={{ padding: '14px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {detail.breakdown.map(b => (
              <div key={b.label}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                  <div style={{ fontSize: 13, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: b.color, display: 'inline-block' }}/>
                    {b.label}
                  </div>
                  <div style={{ fontSize: 13, fontVariantNumeric: 'tabular-nums', display: 'flex', gap: 10 }}>
                    <span style={{ color: 'var(--text)', fontWeight: 600 }}>{fmt(b.value)}</span>
                    <span style={{ color: 'var(--text-muted)', minWidth: 32, textAlign: 'right' }}>{b.share}%</span>
                  </div>
                </div>
                <div style={{ height: 4, background: 'var(--surface-2)', borderRadius: 99, overflow: 'hidden' }}>
                  <div style={{ width: b.share + '%', height: '100%', background: b.color }}/>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Recommended actions */}
        <Card padding={0}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Recommended actions</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>From your Clicky team</div>
            </div>
            <Badge tone="primary">{detail.actions.length} open</Badge>
          </div>
          <div style={{ padding: '8px 18px 14px' }}>
            {detail.actions.map((a, i) => (
              <div key={i} style={{
                display: 'flex', gap: 12, alignItems: 'flex-start',
                padding: '12px 0',
                borderBottom: i < detail.actions.length - 1 ? '1px solid var(--border)' : 'none',
              }}>
                <span style={{
                  width: 22, height: 22, borderRadius: 99,
                  background: 'color-mix(in oklab, var(--primary) 12%, transparent)',
                  color: 'var(--primary)',
                  display: 'grid', placeItems: 'center',
                  fontSize: 11, fontWeight: 700, flexShrink: 0,
                  fontVariantNumeric: 'tabular-nums',
                }}>{i + 1}</span>
                <div style={{ flex: 1, fontSize: 13, lineHeight: 1.5, color: 'var(--text)', paddingTop: 2 }}>{a}</div>
                <Btn variant="ghost" size="sm">Review</Btn>
              </div>
            ))}
          </div>
        </Card>
      </div>
      )}

      {/* Activity log */}
      <Card padding={0}>
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', fontWeight: 600, fontSize: 14 }}>
          Activity & commentary
          <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, fontWeight: 400 }}>What's moved this Performance Target this quarter</div>
        </div>
        <div style={{ padding: 18 }}>
          {detail.activity.map((a, i) => (
            <div key={i} style={{ display: 'flex', gap: 14, position: 'relative', paddingBottom: i < detail.activity.length - 1 ? 16 : 0 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                <PersonAvatar name={a.who} size={28} />
                {i < detail.activity.length - 1 && (
                  <div style={{ flex: 1, width: 1.5, background: 'var(--border)', marginTop: 4 }}/>
                )}
              </div>
              <div style={{ flex: 1, paddingBottom: 4 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 2 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{a.who}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>· {a.date}</span>
                </div>
                <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.55 }}>{a.body}</div>
              </div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
};

window.KpiDetailScreen = KpiDetailScreen;
