const prCell = { padding: '8px 12px', borderTop: '1px solid #EEF1F7', font: '400 12px/1.35 var(--font-body)', color: 'var(--yk-charcoal)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', verticalAlign: 'middle' };
const prHead = { padding: '7px 12px', font: '500 11px/1.3 var(--font-body)', color: 'var(--text-muted)', textAlign: 'left', whiteSpace: 'nowrap', background: '#FAFBFE', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 0 };

function BentoCard({ title, body, children, span, style, rise = 50, split = false }) {
  const wideSplit = useMedia('(min-width: 1040px)') && split;
  const [h, setH] = React.useState(false);
  return (
    <ScrollRise from={rise} scaleFrom={0.97} style={{ gridColumn: span, display: 'flex', minWidth: 0 }}>
      <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{ flex: 1, display: wideSplit ? 'grid' : 'flex', gridTemplateColumns: wideSplit ? 'minmax(0,.62fr) minmax(0,1.38fr)' : undefined, flexDirection: 'column', background: 'var(--glass-bg)', backdropFilter: 'var(--glass-blur)', WebkitBackdropFilter: 'var(--glass-blur)', boxShadow: 'var(--glass-shadow)', border: `1px solid ${h ? 'var(--border-accent)' : 'var(--glass-border)'}`, borderRadius: 20, overflow: 'hidden', transition: 'border-color .22s', minWidth: 0, ...style }}>
        <div style={{ padding: wideSplit ? '32px 8px 32px 32px' : '24px 24px 0' }}><h3 style={{ font: '600 20px/1.3 var(--font-display)', color: 'var(--yk-indigo)', letterSpacing: '-.01em' }}>{title}</h3><p style={{ font: '400 15px/1.6 var(--font-body)', color: 'var(--yk-charcoal)', marginTop: 8, maxWidth: 520 }}>{body}</p></div>
        <div style={{ flex: 1, padding: wideSplit ? 24 : '20px 24px 24px', display: 'flex', alignItems: wideSplit ? 'center' : 'flex-end', minWidth: 0 }}><div style={{ width: '100%', minWidth: 0 }}>{children}</div></div>
      </div>
    </ScrollRise>
  );
}

function AppPanel({ icon, title, meta, right, children, bodyStyle }) {
  const { Icon } = DS;
  return (
    <div style={{ background: '#fff', border: '1px solid var(--border-default)', borderRadius: 12, boxShadow: 'var(--shadow-md)', overflow: 'hidden', minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 12px', borderBottom: '1px solid var(--border-default)' }}>
        <span style={{ width: 22, height: 22, borderRadius: 6, background: 'var(--yk-lavender)', color: 'var(--yk-violet)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon name={icon} size={13} /></span>
        <span style={{ font: '600 12.5px var(--font-body)', color: 'var(--yk-indigo)', whiteSpace: 'nowrap' }}>{title}</span>
        {meta && <MonoLabel style={{ fontSize: 10.5, overflow: 'hidden', textOverflow: 'ellipsis' }}>{meta}</MonoLabel>}
        <span style={{ flex: 1 }} />{right}
      </div>
      <div style={bodyStyle}>{children}</div>
    </div>
  );
}

/* 1 — Agent guardrails: threshold + decision log */
function ApprovalGate() {
  const { Badge, Icon } = DS;
  const [thr, setThr] = React.useState(80);
  const narrow = useMedia('(max-width: 560px)');
  const rows = [['message-circle', 'Refund · ₹2,400 · order 8812', 94, '14:02'], ['phone', 'Change delivery address', 88, '13:58'], ['mail', 'Contract clause 7.2 question', 71, '13:51'], ['message-square-text', 'Bulk discount request · 18%', 47, '13:44'], ['phone', 'Cancel recurring pickup', 83, '13:40']];
  return (
    <AppPanel icon="shield-check" title="Agent guardrails" meta="support-agent · v3" right={<Badge size="sm" tone="success" dot>Policy active</Badge>}>
      <div style={{ display: 'grid', gridTemplateColumns: 'auto minmax(80px,1fr) auto', gap: 12, alignItems: 'center', padding: '10px 12px', background: '#FAFBFE', borderBottom: '1px solid #EEF1F7' }}>
        <span style={{ font: '500 12px var(--font-body)', color: 'var(--yk-indigo)', whiteSpace: 'nowrap' }}>Auto-resolve above</span>
        <input type="range" min="50" max="95" value={thr} onChange={(e) => setThr(+e.target.value)} aria-label="Confidence threshold" style={{ width: '100%', accentColor: '#7C3AED' }} />
        <span style={{ font: '600 12px var(--font-mono)', color: 'var(--yk-violet)', border: '1px solid var(--border-soft)', borderRadius: 5, padding: '2px 6px', background: '#fff' }}>{thr}%</span>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
        <colgroup><col /><col style={{ width: narrow ? 74 : 96 }} /><col style={{ width: narrow ? 106 : 130 }} /><col style={{ width: narrow ? 46 : 60 }} /></colgroup>
        <thead><tr>{['Request', narrow ? 'Conf.' : 'Confidence', 'Outcome', 'Time'].map((h) => <th key={h} style={prHead}>{h}</th>)}</tr></thead>
        <tbody>{rows.map(([ic, t, c, tm]) => { const auto = c >= thr; return (
          <tr key={t}>
            <td style={prCell}><span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}><Icon name={ic} size={14} color="var(--yk-slate-500)" /><span style={{ overflow: 'hidden', textOverflow: 'ellipsis', color: 'var(--yk-indigo)', fontWeight: 500 }}>{t}</span></span></td>
            <td style={prCell}><span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ position: 'relative', flex: 1, height: 5, borderRadius: 3, background: '#EEF1F7' }}><span style={{ position: 'absolute', inset: 0, width: `${c}%`, borderRadius: 3, background: auto ? 'var(--yk-sky)' : '#F59E0B', transition: 'background .2s' }} /><span style={{ position: 'absolute', left: `${thr}%`, top: -3, bottom: -3, width: 1.5, background: 'var(--yk-indigo)' }} /></span><span style={{ font: '400 11px var(--font-mono)' }}>{c}</span></span></td>
            <td style={prCell}>{auto ? <Badge size="sm" tone="sky" icon="bot">Auto-resolved</Badge> : <Badge size="sm" tone="warning" icon="user">To Priya S.</Badge>}</td>
            <td style={{ ...prCell, font: '400 11px var(--font-mono)', color: 'var(--text-muted)' }}>{tm}</td>
          </tr>); })}</tbody>
      </table>
    </AppPanel>
  );
}

/* 2 — Unified customer timeline */
const PR_EVENTS = [
  ['phone', 'Voice', 'Mon 10:12', 'Called about weekly cold-chain pickups for 40 clinics.', 'agent'],
  ['message-square-text', 'Web Chat', 'Mon 16:40', 'Asked if Saturday pickups are possible.', 'agent'],
  ['message-circle', 'WhatsApp', 'Tue 09:05', 'Quote link opened · 2 views', 'system'],
  ['mail', 'Email', 'Tue 09:06', 'PDF quote + SLA sent to ops@medline.in', 'system'],
  ['smartphone', 'SMS', 'Tue 15:30', 'Callback confirmed for Wed 11:00', 'human'],
];
function ChannelThread() {
  const { Icon, Badge } = DS;
  const [f, setF] = React.useState('All');
  const chans = ['All', 'Voice', 'Web Chat', 'WhatsApp', 'Email', 'SMS'];
  return (
    <AppPanel icon="messages-square" title="Customer thread" meta="#C-1042">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderBottom: '1px solid #EEF1F7' }}>
        <span style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--yk-indigo)', color: '#fff', display: 'grid', placeItems: 'center', font: '600 11px var(--font-body)', flex: 'none' }}>AM</span>
        <div style={{ minWidth: 0, flex: 1 }}><div style={{ font: '600 12.5px var(--font-body)', color: 'var(--yk-indigo)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Anita Menon · Medline Clinics</div><MonoLabel style={{ fontSize: 10.5 }}>5 touchpoints · 1 record</MonoLabel></div>
        <Badge size="sm" tone="violet">Qualified</Badge>
      </div>
      <div style={{ display: 'flex', gap: 4, padding: '8px 12px', overflowX: 'auto', scrollbarWidth: 'none', borderBottom: '1px solid #EEF1F7' }}>
        {chans.map((c) => <button key={c} type="button" onClick={() => setF(c)} style={{ height: 24, padding: '0 9px', borderRadius: 999, border: `1px solid ${f === c ? 'var(--yk-violet)' : 'var(--border-default)'}`, background: f === c ? 'var(--yk-violet-50)' : '#fff', color: f === c ? 'var(--yk-violet)' : 'var(--yk-charcoal)', font: '500 11px var(--font-body)', cursor: 'pointer', whiteSpace: 'nowrap' }}>{c}</button>)}
      </div>
      <div style={{ padding: '10px 12px', display: 'grid', gap: 0 }}>
        {PR_EVENTS.map(([ic, ch, ts, txt, by], i) => { const dim = f !== 'All' && f !== ch; return (
          <div key={ts} style={{ display: 'grid', gridTemplateColumns: '24px minmax(0,1fr)', gap: 10, opacity: dim ? 0.3 : 1, transition: 'opacity .2s', position: 'relative', paddingBottom: i < PR_EVENTS.length - 1 ? 10 : 0 }}>
            {i < PR_EVENTS.length - 1 && <span aria-hidden style={{ position: 'absolute', left: 11.5, top: 24, bottom: 0, width: 1, background: 'var(--border-default)' }} />}
            <span style={{ width: 24, height: 24, borderRadius: 6, display: 'grid', placeItems: 'center', background: '#fff', border: '1px solid var(--border-default)', color: 'var(--yk-violet)', position: 'relative' }}><Icon name={ic} size={12} /></span>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', gap: 6, alignItems: 'baseline' }}><span style={{ font: '600 11.5px var(--font-body)', color: 'var(--yk-indigo)', whiteSpace: 'nowrap' }}>{ch}</span><MonoLabel style={{ fontSize: 10 }}>{ts}</MonoLabel><MonoLabel style={{ fontSize: 10, marginLeft: 'auto' }} color={by === 'human' ? 'var(--yk-violet)' : 'var(--text-subtle)'}>{by === 'human' ? 'Priya S.' : by === 'agent' ? 'AI agent' : 'auto'}</MonoLabel></div>
              <div style={{ font: '400 11.5px/1.45 var(--font-body)', color: 'var(--yk-charcoal)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{txt}</div>
            </div>
          </div>); })}
      </div>
    </AppPanel>
  );
}

/* 3 — Migration tracker */
function SchemaBridge() {
  const { Badge } = DS;
  const mods = [['Customer master', 'tbl_CUST', '/v1/customers', 'live', 100], ['Order entry', 'frmOrders.vb', '/v1/orders', 'parallel', 99.7], ['Invoicing', 'rpt_INV', '/v1/invoices', 'parallel', 98.9], ['Stock ledger', 'tbl_STK', '/v1/inventory', 'planned', 0]];
  const tone = { live: ['success', 'Live'], parallel: ['sky', 'Parallel run'], planned: ['neutral', 'Planned'] };
  return (
    <AppPanel icon="git-compare" title="Migration tracker" meta="legacy-erp → api">
      <div style={{ display: 'grid', gap: 0 }}>
        {mods.map(([n, from, to, st, match], i) => (
          <div key={n} style={{ padding: '9px 12px', borderTop: i ? '1px solid #EEF1F7' : 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ font: '600 12px var(--font-body)', color: 'var(--yk-indigo)', flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{n}</span><Badge size="sm" dot tone={tone[st][0]} pulse={st === 'parallel'}>{tone[st][1]}</Badge></div>
            <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 16px minmax(0,1fr) auto', gap: 6, alignItems: 'center', marginTop: 5 }}>
              <span style={{ font: '400 11px var(--font-mono)', color: '#B91C1C', background: '#FEF7F7', borderRadius: 4, padding: '2px 6px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{from}</span>
              <svg width="16" height="8" viewBox="0 0 16 8" aria-hidden><FlowPath d="M0 4 H16" active={st !== 'planned'} /></svg>
              <span style={{ font: '400 11px var(--font-mono)', color: '#047857', background: '#F3FCF8', borderRadius: 4, padding: '2px 6px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{to}</span>
              <MonoLabel style={{ fontSize: 10.5, width: 46, textAlign: 'right' }} color={st === 'planned' ? 'var(--text-subtle)' : 'var(--yk-indigo)'}>{st === 'planned' ? '—' : `${match}%`}</MonoLabel>
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: '7px 12px', background: '#FAFBFE', borderTop: '1px solid #EEF1F7', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '2px 10px' }}><MonoLabel style={{ fontSize: 10.5 }}>record match · nightly diff</MonoLabel><MonoLabel style={{ fontSize: 10.5 }} color="var(--yk-indigo)">2 / 4 modules off legacy</MonoLabel></div>
    </AppPanel>
  );
}

/* 4 — Reporting dashboard: call analytics */
const RPT_DAYS = Array.from({ length: 14 }, (_, i) => {
  const d = new Date(2026, 10, 14 + i);
  const wk = d.getDay() === 0 || d.getDay() === 6;
  const calls = Math.round((wk ? 140 : 300) + 60 * Math.sin(i * 1.3) + i * 6);
  const failed = Math.round(calls * (0.03 + 0.025 * Math.abs(Math.cos(i * 0.9))));
  const pos = +(58 + 9 * Math.sin(i * 0.55) + i * 0.6).toFixed(1);
  const talk = 168 + Math.round(26 * Math.cos(i * 0.7));
  const sent = +(0.42 + 0.18 * Math.sin(i * 0.5) + i * 0.01).toFixed(2);
  return { label: d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }), short: String(d.getDate()), calls, failed, ok: calls - failed, succ: +(100 * (calls - failed) / calls).toFixed(1), pos, talk, sent };
});
const fmtTalk = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;

function RptKpi({ label, value, delta, good = true, spark, color }) {
  return (
    <div style={{ border: '1px solid var(--border-default)', borderRadius: 8, padding: '8px 10px', minWidth: 0 }}>
      <div style={{ font: '500 10.5px var(--font-body)', color: 'var(--text-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
      <div style={{ font: '600 16px var(--font-display)', color: 'var(--yk-indigo)', marginTop: 2, letterSpacing: '-.01em', whiteSpace: 'nowrap' }}>{value}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 4, marginTop: 2 }}>
        <MonoLabel style={{ fontSize: 10 }} color={good ? 'var(--yk-success)' : 'var(--yk-danger)'}>{delta}</MonoLabel>
        <svg width="38" height="14" viewBox="0 0 38 14" aria-hidden style={{ flex: 'none' }}><polyline points={spark.map((v, i) => `${(i / (spark.length - 1)) * 38},${13 - v * 12}`).join(' ')} fill="none" stroke={color} strokeWidth="1.5" /></svg>
      </div>
    </div>
  );
}

function SentimentDonut({ pos = 64, neu = 27, neg = 9 }) {
  const R = 34, C = 2 * Math.PI * R;
  const segs = [[pos, '#10B981', 'Positive'], [neu, '#CBD5E1', 'Neutral'], [neg, '#F87171', 'Negative']];
  let off = 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <svg width="86" height="86" viewBox="0 0 86 86" style={{ flex: 'none' }} aria-hidden>
        <circle cx="43" cy="43" r={R} fill="none" stroke="#F1F3F9" strokeWidth="10" />
        {segs.map(([v, c], i) => { const len = (v / 100) * C; const el = <circle key={i} cx="43" cy="43" r={R} fill="none" stroke={c} strokeWidth="10" strokeDasharray={`${len - 1.5} ${C - len + 1.5}`} strokeDashoffset={-off} transform="rotate(-90 43 43)" />; off += len; return el; })}
        <text x="43" y="41" textAnchor="middle" style={{ font: '600 15px var(--font-display)', fill: 'var(--yk-indigo)' }}>+0.58</text>
        <text x="43" y="54" textAnchor="middle" style={{ font: '500 8.5px var(--font-mono)', fill: '#64748B' }}>avg score</text>
      </svg>
      <div style={{ display: 'grid', gap: 5, minWidth: 0 }}>
        {segs.map(([v, c, n]) => <div key={n} style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: c }} /><span style={{ font: '500 11.5px var(--font-body)', color: 'var(--yk-charcoal)', width: 56 }}>{n}</span><span style={{ font: '600 11.5px var(--font-mono)', color: 'var(--yk-indigo)' }}>{v}%</span></div>)}
      </div>
    </div>
  );
}

function TelemetryChart() {
  const { Tabs, Badge } = DS;
  const [metric, setMetric] = React.useState('pos');
  const rptWide = useMedia('(min-width: 1280px)');
  const rptNarrow = useMedia('(max-width: 560px)');
  const [hv, setHv] = React.useState(() => (typeof window !== 'undefined' && window.innerWidth <= 560 ? null : 10));
  const D = RPT_DAYS, n = D.length;
  const maxCalls = 450;
  const M = { pos: { key: 'pos', label: 'Positive response', unit: '%', min: 40, max: 80, color: '#06B6D4', fmt: (v) => v + '%' }, succ: { key: 'succ', label: 'Success rate', unit: '%', min: 90, max: 100, color: '#7C3AED', fmt: (v) => v + '%' }, talk: { key: 'talk', label: 'Avg talk time', unit: 's', min: 120, max: 220, color: '#2563EB', fmt: fmtTalk } }[metric];
  const bw = 100 / n;
  const ly = (v) => 100 - ((v - M.min) / (M.max - M.min)) * 100;
  const line = D.map((d, i) => `${i * bw + bw / 2},${ly(d[M.key])}`).join(' ');
  const cur = D[hv];
  const tot = D.reduce((a, d) => ({ calls: a.calls + d.calls, failed: a.failed + d.failed }), { calls: 0, failed: 0 });
  const norm = (k) => { const v = D.slice(-8).map((d) => d[k]); const mn = Math.min(...v), mx = Math.max(...v); return v.map((x) => (x - mn) / (mx - mn || 1)); };
  return (
    <AppPanel icon="chart-no-axes-combined" title="Agent analytics" meta="voice + chat · sample data" right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, font: '500 11px var(--font-body)', color: 'var(--yk-charcoal)', border: '1px solid var(--border-default)', borderRadius: 6, padding: '3px 8px', whiteSpace: 'nowrap' }}>14 – 27 Nov</span>}>
      <div style={{ padding: 12, display: 'grid', gap: 12 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(108px, 1fr))', gap: 8 }}>
          <RptKpi label="Sentiment score" value="+0.58" delta="+0.07" spark={norm('sent')} color="#10B981" />
          <RptKpi label="Success rate" value={(100 * (tot.calls - tot.failed) / tot.calls).toFixed(1) + '%'} delta="+0.6 pt" spark={norm('succ')} color="#7C3AED" />
          <RptKpi label="Failed calls" value={tot.failed} delta="−12%" spark={norm('failed')} color="#F87171" />
          <RptKpi label="Avg talk time" value={fmtTalk(Math.round(D.reduce((a, d) => a + d.talk, 0) / n))} delta="−0:14" spark={norm('talk')} color="#2563EB" />
          <RptKpi label="Positive response" value={D[n - 1].pos + '%'} delta="+4.1 pt" spark={norm('pos')} color="#06B6D4" />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: rptWide ? 'minmax(0,1.75fr) minmax(0,1fr)' : 'minmax(0,1fr)', gap: 10 }}>
          <div style={{ border: '1px solid var(--border-default)', borderRadius: 8, padding: '10px 10px 8px', minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 8 }}>
              <span style={{ font: '600 12px var(--font-body)', color: 'var(--yk-indigo)', whiteSpace: 'nowrap' }}>Calls handled</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, font: '400 10.5px var(--font-body)', color: 'var(--text-muted)' }}><span style={{ width: 8, height: 8, borderRadius: 2, background: '#DDD8FF' }} />Successful</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, font: '400 10.5px var(--font-body)', color: 'var(--text-muted)' }}><span style={{ width: 8, height: 8, borderRadius: 2, background: '#FCA5A5' }} />Failed</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, font: '400 10.5px var(--font-body)', color: 'var(--text-muted)' }}><span style={{ width: 10, height: 2, background: M.color }} /><span style={{ whiteSpace: 'nowrap' }}>{M.label}</span></span>
              <span style={{ flex: 1 }} />
              <Tabs size="sm" value={metric} onChange={setMetric} tabs={[{ value: 'pos', label: 'Positive' }, { value: 'succ', label: 'Success' }, { value: 'talk', label: 'Talk time' }]} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '26px minmax(0,1fr) 34px', gap: 6 }}>
              <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: 150 }}>{['450', '225', '0'].map((l) => <MonoLabel key={l} style={{ fontSize: 9.5, textAlign: 'right' }}>{l}</MonoLabel>)}</div>
              <div style={{ minWidth: 0 }}>
                <div onMouseLeave={() => setHv(n - 4)} style={{ position: 'relative', height: 150, borderBottom: '1px solid var(--border-default)' }}>
                  {[0, 50].map((y) => <span key={y} aria-hidden style={{ position: 'absolute', left: 0, right: 0, top: `${y}%`, borderTop: '1px dashed #EEF1F7' }} />)}
                  {cur != null && <span aria-hidden style={{ position: 'absolute', top: 0, bottom: 0, left: `${hv * bw + bw / 2}%`, width: 1, background: 'rgba(30,27,75,.25)', transition: 'left .12s' }} />}
                  <svg viewBox="0 0 100 100" preserveAspectRatio="none" width="100%" height="100%" style={{ position: 'absolute', inset: 0, cursor: 'crosshair' }}>
                    {D.map((d, i) => { const x = i * bw + bw * 0.2, w = bw * 0.6, hOk = (d.ok / maxCalls) * 100, hF = (d.failed / maxCalls) * 100; return (
                      <g key={i} onMouseEnter={() => setHv(i)}>
                        <rect x={i * bw} y="0" width={bw} height="100" fill="transparent" />
                        <rect x={x} y={100 - hOk} width={w} height={hOk} fill={hv === i ? '#7C3AED' : '#DDD8FF'} />
                        <rect x={x} y={100 - hOk - hF} width={w} height={hF} fill={hv === i ? '#F87171' : '#FCA5A5'} />
                      </g>); })}
                  </svg>
                  <svg viewBox="0 0 100 100" preserveAspectRatio="none" width="100%" height="100%" style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'visible' }} aria-hidden>
                    <polyline points={line} fill="none" stroke={M.color} strokeWidth="2" vectorEffect="non-scaling-stroke" style={{ transition: 'all .3s' }} />
                  </svg>
                  {cur != null && <span aria-hidden style={{ position: 'absolute', left: `calc(${hv * bw + bw / 2}% - 4px)`, top: `calc(${ly(cur[M.key])}% - 4px)`, width: 8, height: 8, borderRadius: '50%', background: '#fff', border: `2px solid ${M.color}`, pointerEvents: 'none', transition: 'left .12s, top .12s' }} />}
                  {cur != null && <div style={{ position: 'absolute', top: 4, left: hv > n / 2 ? 'auto' : `calc(${hv * bw + bw}% + 6px)`, right: hv > n / 2 ? `calc(${100 - hv * bw}% + 6px)` : 'auto', background: 'var(--yk-indigo)', color: '#fff', borderRadius: 8, padding: '8px 10px', boxShadow: 'var(--shadow-md)', pointerEvents: 'none', zIndex: 3, minWidth: rptNarrow ? 148 : 176, whiteSpace: 'nowrap' }}>
                    <div style={{ font: '600 11px var(--font-body)', marginBottom: 4 }}>{cur.label}</div>
                    {[['Calls', cur.calls], ['Success rate', cur.succ + '%'], ['Failed', cur.failed], ['Avg talk time', fmtTalk(cur.talk)], ['Positive response', cur.pos + '%'], ['Sentiment', (cur.sent > 0 ? '+' : '') + cur.sent]].map(([k, v]) => <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, font: '400 10.5px/1.6 var(--font-mono)' }}><span style={{ color: '#C7C4F2' }}>{k}</span><span>{v}</span></div>)}
                  </div>}
                </div>
                <div style={{ display: 'flex', marginTop: 4 }}>{D.map((d, i) => <MonoLabel key={i} style={{ flex: 1, textAlign: 'center', fontSize: 9.5 }} color={hv === i ? 'var(--yk-indigo)' : undefined}>{d.short}</MonoLabel>)}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: 150 }}>{[M.max, (M.max + M.min) / 2, M.min].map((l) => <MonoLabel key={l} style={{ fontSize: 9.5 }} color={M.color}>{M.fmt(l)}</MonoLabel>)}</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: rptWide ? 'minmax(0,1fr)' : 'repeat(auto-fit, minmax(220px, 1fr))', gap: 10, alignContent: 'start' }}>
            <div style={{ border: '1px solid var(--border-default)', borderRadius: 8, padding: 10 }}>
              <div style={{ font: '600 12px var(--font-body)', color: 'var(--yk-indigo)', marginBottom: 8 }}>Sentiment mix</div>
              <SentimentDonut />
            </div>
            <div style={{ border: '1px solid var(--border-default)', borderRadius: 8, padding: 10 }}>
              <div style={{ font: '600 12px var(--font-body)', color: 'var(--yk-indigo)', marginBottom: 8 }}>Top failure reasons</div>
              {[['No answer / voicemail', 46], ['Caller dropped', 28], ['Out-of-scope request', 17], ['Telephony error', 9]].map(([r, p]) => (
                <div key={r} style={{ marginBottom: 6 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, font: '400 11px var(--font-body)', color: 'var(--yk-charcoal)', whiteSpace: 'nowrap' }}><span>{r}</span><span style={{ fontFamily: 'var(--font-mono)' }}>{p}%</span></div>
                  <div style={{ height: 4, borderRadius: 2, background: '#F1F3F9', marginTop: 3 }}><div style={{ width: `${p}%`, height: '100%', borderRadius: 2, background: '#F87171' }} /></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </AppPanel>
  );
}

/* 5 — Lead generation & qualification */
const LG_SOURCES = [['All', 'layers', 1], ['Meta Ads', 'megaphone', 0.38], ['Google Search', 'search', 0.27], ['Website form', 'globe', 0.18], ['WhatsApp', 'message-circle', 0.11], ['Referral', 'users', 0.06]];
const LG_STAGES = [
  ['Captured', 1240, 'inbox', 'Form, ad lead form, chat or call creates a lead with UTM source and consent flag.'],
  ['Enriched', 1172, 'database', 'Company, city, size and duplicate check added from your CRM and public data.'],
  ['Scored', 1172, 'gauge', 'Fit (ICP match) + intent (pages, replies) + engagement (opens, clicks), 0–100.'],
  ['MQL', 418, 'filter', 'Score ≥ 60 and a valid phone or work email. Nurture sequence starts automatically.'],
  ['SQL', 141, 'user-round-check', 'Budget, timeline and need confirmed by the chat/voice agent or a rep.'],
  ['Booked', 63, 'calendar-check', 'Meeting booked on the rep calendar; CRM deal created with full history.'],
];
const LG_LEADS = [
  ['Neha Joshi', 'Meta Ads', 'Interior design · Pune', 82, 'SQL'],
  ['Arjun Rao', 'Google Search', 'Clinic chain · Bengaluru', 74, 'MQL'],
  ['Kavita Shah', 'Website form', 'Retail · Ahmedabad', 91, 'Booked'],
  ['Imran Khan', 'WhatsApp', 'Logistics · Mumbai', 58, 'Nurture'],
  ['Sana Patel', 'Referral', 'Manufacturing · Surat', 69, 'MQL'],
];
function LeadFunnel() {
  const { Badge, Icon } = DS;
  const [src, setSrc] = React.useState('All');
  const [st, setSt] = React.useState(3);
  const narrow = useMedia('(max-width: 560px)');
  const share = LG_SOURCES.find((s) => s[0] === src)[2];
  const top = LG_STAGES[0][1] * share;
  const leads = LG_LEADS.filter((l) => src === 'All' || l[1] === src);
  const tone = { Booked: 'violet', SQL: 'sky', MQL: 'neutral', Nurture: 'warning' };
  return (
    <AppPanel icon="filter" title="Lead pipeline" meta="last 30 days · sample data" right={<Badge size="sm" tone="success" dot>Syncing to CRM</Badge>}>
      <div style={{ display: 'flex', gap: 4, padding: '8px 12px', overflowX: 'auto', scrollbarWidth: 'none', borderBottom: '1px solid #EEF1F7' }}>
        {LG_SOURCES.map(([s, ic, sh]) => <button key={s} type="button" onClick={() => setSrc(s)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 26, padding: '0 10px', borderRadius: 999, border: `1px solid ${src === s ? 'var(--yk-violet)' : 'var(--border-default)'}`, background: src === s ? 'var(--yk-violet-50)' : '#fff', color: src === s ? 'var(--yk-violet)' : 'var(--yk-charcoal)', font: '500 11px var(--font-body)', cursor: 'pointer', whiteSpace: 'nowrap' }}><Icon name={ic} size={12} />{s}<span style={{ font: '500 10px var(--font-mono)', opacity: 0.75 }}>{Math.round(1240 * sh)}</span></button>)}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(0,1fr))', gap: narrow ? 3 : 6, padding: '12px 12px 4px' }}>
        {LG_STAGES.map(([n, v], i) => { const val = Math.round(v * share); const on = st === i; return (
          <button key={n} type="button" onClick={() => setSt(i)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'stretch', gap: 6, border: 0, background: 'none', padding: 0, cursor: 'pointer', textAlign: 'left', minWidth: 0 }}>
            <div style={{ height: 84, display: 'flex', alignItems: 'flex-end', background: on ? 'var(--yk-violet-50)' : '#FAFBFE', borderRadius: 6, padding: 4 }}><span style={{ width: '100%', height: `${Math.max(6, (val / top) * 100)}%`, borderRadius: 4, background: on ? 'linear-gradient(180deg,#7C3AED,#06B6D4)' : '#DDD8FF', transition: 'height .45s cubic-bezier(.22,1,.36,1), background .2s' }} /></div>
            <span style={{ font: '600 11.5px var(--font-body)', color: on ? 'var(--yk-violet)' : 'var(--yk-indigo)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{n}</span>
            <span style={{ display: 'flex', flexDirection: narrow ? 'column' : 'row', justifyContent: 'space-between', alignItems: narrow ? 'flex-start' : undefined, gap: narrow ? 0 : 4 }}><span style={{ font: `600 ${narrow ? 12 : 13}px var(--font-mono)`, color: 'var(--yk-indigo)' }}>{val}</span>{i > 0 && <MonoLabel style={{ fontSize: 9.5 }}>{Math.round((v / LG_STAGES[i - 1][1]) * 100)}%</MonoLabel>}</span>
          </button>); })}
      </div>
      <div key={st} style={{ margin: '8px 12px 10px', display: 'flex', gap: 10, alignItems: 'flex-start', padding: '9px 11px', borderRadius: 8, background: 'var(--yk-indigo)', color: '#fff', animation: 'yk-fade-up .35s cubic-bezier(.22,1,.36,1) both' }}>
        <Icon name={LG_STAGES[st][2]} size={15} color="#A5F3FC" style={{ marginTop: 1, flex: 'none' }} />
        <div style={{ minWidth: 0 }}><div style={{ font: '600 12px var(--font-body)' }}>How a lead reaches {LG_STAGES[st][0]}</div><div style={{ font: '400 11.5px/1.5 var(--font-body)', color: '#D6D3F5', marginTop: 2 }}>{LG_STAGES[st][3]}</div></div>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
        <colgroup><col /><col style={{ width: narrow ? 74 : 112 }} /><col style={{ width: narrow ? 66 : 92 }} /><col style={{ width: narrow ? 68 : 84 }} /></colgroup>
        <thead><tr>{['Lead', 'Source', 'Score', 'Stage'].map((h) => <th key={h} style={prHead}>{h}</th>)}</tr></thead>
        <tbody>{leads.map(([nm, s, co, sc, stage]) => (
          <tr key={nm}>
            <td style={prCell}><span style={{ color: 'var(--yk-indigo)', fontWeight: 500 }}>{nm}</span><span style={{ color: 'var(--text-muted)' }}> · {co}</span></td>
            <td style={prCell}>{s}</td>
            <td style={prCell}><span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ position: 'relative', flex: 1, height: 5, borderRadius: 3, background: '#EEF1F7' }}><span style={{ position: 'absolute', inset: 0, width: `${sc}%`, borderRadius: 3, background: sc >= 60 ? 'var(--yk-sky)' : '#F59E0B' }} /></span><span style={{ font: '400 11px var(--font-mono)' }}>{sc}</span></span></td>
            <td style={prCell}><Badge size="sm" tone={tone[stage]}>{stage}</Badge></td>
          </tr>))}</tbody>
      </table>
    </AppPanel>
  );
}

function Principles() {
  const { SectionHeader } = DS;
  const wide = useMedia('(min-width: 1040px)');
  return (
    <section id="solutions" style={{ padding: `${wide ? 112 : 72}px 0` }}>
      <Container>
        <Reveal><SectionHeader eyebrow="Engineering principles" title="Built for control, not black boxes." lead="Every system we ship can be inspected, overridden and reported on by your team." /></Reveal>
        <div style={{ display: 'grid', gridTemplateColumns: wide ? 'repeat(12, minmax(0,1fr))' : 'minmax(0,1fr)', gap: 20, marginTop: 48 }}>
          <BentoCard span={wide ? 'span 12' : undefined} split title="Omnichannel continuity" body="Voice, chat, WhatsApp, email and SMS write to one customer thread. Each channel keeps its own interface: call recordings with emotion and sentiment, AI chat qualification, WhatsApp and SMS replies, and email drafts that wait for review. Pick a touchpoint to open it."><OmniThread /></BentoCard>
          <BentoCard span={wide ? 'span 7' : undefined} title="Human-in-the-loop by default" body="Agents act on their own only above a confidence threshold you set. Drag the slider to see which requests go to a person."><ApprovalGate /></BentoCard>
          <BentoCard span={wide ? 'span 5' : undefined} rise={90} title="Modernisation without disruption" body="We put an API in front of legacy systems first, then move modules across with nightly record checks."><SchemaBridge /></BentoCard>
          <BentoCard span={wide ? 'span 12' : undefined} split title="Transparent reporting pipelines" body="Every call and chat feeds a dashboard your team owns: sentiment, success rate, failures, talk time and positive responses. Hover a day to inspect it, or switch the trend line."><TelemetryChart /></BentoCard>
          <BentoCard span={wide ? 'span 12' : undefined} split title="Lead generation you can audit" body="Digital marketing leads from ads, search, your website, WhatsApp and referrals land in one pipeline. Each lead is enriched, scored on fit, intent and engagement, then qualified by rules you can read before it reaches a rep. Filter by source or click a stage to see how leads get there."><LeadFunnel /></BentoCard>
        </div>
      </Container>
    </section>
  );
}

Object.assign(window, { Principles });
