// case-studies.jsx — UI/dashboard mockups as live "case study" panels

const Sparkline = ({ data, color }) => {
  const w = 120, h = 28;
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => [
    (i / (data.length - 1)) * w,
    h - ((v - min) / (max - min || 1)) * h
  ]);
  const d = `M ${pts.map(p => p.join(',')).join(' L ')}`;
  const area = `${d} L ${w},${h} L 0,${h} Z`;
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <path d={area} fill={color} opacity="0.15" />
      <path d={d} stroke={color} strokeWidth="1.4" fill="none" />
    </svg>
  );
};

// ─── Case 1: Lead response dashboard ──────────────────────────────────────────
const LeadDash = () => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 2200);
    return () => clearInterval(id);
  }, []);
  const recents = [
    { name: 'Maria Chen', co: 'Ridgepoint Studio', score: 92, status: 'replied', ago: '12s' },
    { name: 'Daniel Okafor', co: 'Forge & Co.', score: 78, status: 'replied', ago: '38s' },
    { name: 'Priya S.', co: 'Northwind Realty', score: 64, status: 'queued', ago: '1m' },
    { name: 'Theo Vasquez', co: 'Lumen Health', score: 88, status: 'replied', ago: '2m' },
    { name: 'Isabel Wu', co: 'Atlas Recruit', score: 41, status: 'nurture', ago: '4m' },
  ];
  const highlight = tick % recents.length;
  return (
    <div className="cs-frame cs-lead">
      <div className="cs-toolbar">
        <div className="cs-tb-l">
          <span className="cs-app-dot" />
          <span className="cs-app-name">Lead Response · live</span>
        </div>
        <div className="cs-tb-r"><span className="cs-live"><span className="cs-pulse"></span>connected</span></div>
      </div>
      <div className="cs-body">
        <div className="cs-stats">
          <div className="cs-stat">
            <div className="cs-stat-l">Response time</div>
            <div className="cs-stat-v">47<span className="cs-u">s</span></div>
            <div className="cs-stat-d good">−98% vs manual</div>
          </div>
          <div className="cs-stat">
            <div className="cs-stat-l">Leads today</div>
            <div className="cs-stat-v">{142 + (tick % 7)}</div>
            <Sparkline data={[80, 92, 110, 88, 124, 142, 138, 142 + (tick % 7)]} color="var(--accent)" />
          </div>
          <div className="cs-stat">
            <div className="cs-stat-l">Qualified</div>
            <div className="cs-stat-v">68<span className="cs-u">%</span></div>
            <Sparkline data={[51, 58, 60, 64, 66, 68, 67, 68]} color="var(--success)" />
          </div>
        </div>
        <div className="cs-table">
          <div className="cs-th">
            <span>Lead</span><span>Score</span><span>Status</span><span>When</span>
          </div>
          {recents.map((r, i) => (
            <div className={`cs-tr ${i === highlight ? 'flash' : ''}`} key={i}>
              <span className="cs-cell">
                <span className="cs-avatar">{r.name.split(' ').map(s => s[0]).join('')}</span>
                <span>
                  <div className="cs-name">{r.name}</div>
                  <div className="cs-sub">{r.co}</div>
                </span>
              </span>
              <span className="cs-cell">
                <div className="cs-bar">
                  <div className="cs-bar-f" style={{ width: `${r.score}%`, background: r.score > 70 ? 'var(--success)' : r.score > 50 ? 'var(--accent)' : 'var(--muted)' }} />
                </div>
                <span className="cs-score">{r.score}</span>
              </span>
              <span className="cs-cell">
                <span className={`cs-pill cs-pill-${r.status}`}>{r.status}</span>
              </span>
              <span className="cs-cell cs-mono">{r.ago} ago</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ─── Case 2: AI inbox ─────────────────────────────────────────────────────────
const InboxMock = () => {
  const msgs = [
    { from: 'sarah@oakwoodrealty.com', subj: 'Question about the listing on 4th', cat: 'Inquiry', prio: 'high', summ: 'Wants showing this Saturday. Mentions budget $850k.' },
    { from: 'billing@stripe.com', subj: 'Receipt for invoice #INV-2041', cat: 'Receipt', prio: 'low', summ: 'Auto-archived. Logged to bookkeeping.' },
    { from: 'mike@forgeagency.io', subj: 'Re: project handoff timeline', cat: 'Client', prio: 'med', summ: 'Confirms Friday handoff. Asks about phase 2 quote.' },
    { from: 'support@shopify.com', subj: 'Webhook delivery report', cat: 'Ops', prio: 'low', summ: 'All deliveries succeeded last 24h.' },
  ];
  return (
    <div className="cs-frame cs-inbox">
      <div className="cs-toolbar">
        <div className="cs-tb-l">
          <span className="cs-app-dot" style={{ background: 'var(--ai)' }} />
          <span className="cs-app-name">AI Inbox Assistant</span>
        </div>
        <div className="cs-tb-r"><span className="cs-mono cs-muted">12 of 47 triaged</span></div>
      </div>
      <div className="cs-inbox-body">
        {msgs.map((m, i) => (
          <div className="cs-msg" key={i}>
            <div className="cs-msg-row">
              <span className={`cs-prio cs-prio-${m.prio}`} />
              <span className="cs-msg-from">{m.from}</span>
              <span className={`cs-tag cs-tag-${m.cat.toLowerCase()}`}>{m.cat}</span>
            </div>
            <div className="cs-msg-subj">{m.subj}</div>
            <div className="cs-msg-summ"><span className="cs-ai-tag">AI</span> {m.summ}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ─── Case 3: Pipeline kanban ──────────────────────────────────────────────────
const PipelineMock = () => {
  const cols = [
    { name: 'New', count: 14, color: 'var(--muted)', items: [{ n: 'Forge & Co.', v: '$8.4k' }, { n: 'Lumen Health', v: '$24k' }] },
    { name: 'Qualified', count: 9, color: 'var(--accent)', items: [{ n: 'Ridgepoint', v: '$12k' }, { n: 'Northwind', v: '$6.8k' }] },
    { name: 'Proposal', count: 5, color: 'var(--ai)', items: [{ n: 'Atlas Recruit', v: '$18k' }] },
    { name: 'Won', count: 3, color: 'var(--success)', items: [{ n: 'Beacon Studio', v: '$32k' }] },
  ];
  return (
    <div className="cs-frame cs-pipe">
      <div className="cs-toolbar">
        <div className="cs-tb-l">
          <span className="cs-app-dot" style={{ background: 'var(--success)' }} />
          <span className="cs-app-name">Pipeline · auto-updating</span>
        </div>
        <div className="cs-tb-r"><span className="cs-mono cs-muted">31 deals · $284k</span></div>
      </div>
      <div className="cs-pipe-body">
        {cols.map((c, i) => (
          <div className="cs-pipe-col" key={i}>
            <div className="cs-pipe-h">
              <span className="cs-pipe-dot" style={{ background: c.color }} />
              <span>{c.name}</span>
              <span className="cs-pipe-c">{c.count}</span>
            </div>
            {c.items.map((it, j) => (
              <div className="cs-pipe-card" key={j}>
                <div className="cs-pipe-n">{it.n}</div>
                <div className="cs-pipe-v">{it.v}</div>
              </div>
            ))}
            <div className="cs-pipe-ghost">+ {c.count - c.items.length} more</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const CaseStudies = () => {
  const cases = [
    {
      tag: 'Lead Follow-Up',
      title: 'Real estate agency: from 6h to 47s',
      copy: 'New inquiries used to wait through the afternoon. Now AI qualifies, drafts, and sends — before the lead has finished closing the tab.',
      Component: LeadDash,
      stats: [{ k: 'response time', v: '−98%' }, { k: 'qualified leads', v: '+34%' }, { k: 'manual work', v: '−12h/wk' }],
    },
    {
      tag: 'AI Inbox',
      title: 'Consultancy: 47 emails, 12 minutes',
      copy: 'Every message triaged, summarized, and tagged. Replies pre-drafted in the founder’s voice. The inbox stops being the to-do list.',
      Component: InboxMock,
      stats: [{ k: 'first-reply time', v: '−95%' }, { k: 'inbox volume', v: '−71%' }, { k: 'response rate', v: '+22%' }],
    },
    {
      tag: 'CRM Pipeline',
      title: 'B2B sales team: a CRM that tells the truth',
      copy: 'Activity logs itself. Stages advance on real signals. Stale records flag themselves. The forecast finally matches reality.',
      Component: PipelineMock,
      stats: [{ k: 'stale records', v: '−91%' }, { k: 'forecast accuracy', v: '+38%' }, { k: 'admin time', v: '−9h/wk' }],
    },
  ];
  return (
    <section className="section cases">
      <Reveal><SectionLabel num="06" label="Case studies" /></Reveal>
      <Reveal delay={80}><h2 className="sec-h">What it looks like in production.</h2></Reveal>
      <Reveal delay={140}><p className="sec-sub">Live examples — these panels run on mock data, but the systems behind them are real builds.</p></Reveal>
      <div className="cs-stack">
        {cases.map((c, i) => (
          <div className={`cs-row ${i % 2 ? 'rev' : ''}`} key={i}>
            <Reveal x={i % 2 ? 30 : -30} y={0} className="cs-text">
              <div className="cs-tag-pill">{c.tag}</div>
              <h3>{c.title}</h3>
              <p>{c.copy}</p>
              <div className="cs-stat-row">
                {c.stats.map((s, j) => (
                  <div className="cs-st" key={j}>
                    <div className="cs-st-v">{s.v}</div>
                    <div className="cs-st-k">{s.k}</div>
                  </div>
                ))}
              </div>
            </Reveal>
            <Reveal x={i % 2 ? -30 : 30} y={0} delay={120} className="cs-vis">
              <c.Component />
            </Reveal>
          </div>
        ))}
      </div>
    </section>
  );
};

window.CaseStudies = CaseStudies;
