// cases.jsx - "What One Principal Delivers". 6 real case studies, glass cards + detail modal.
// Engagement: social proof, metric anchoring, curiosity-gap card → full-story modal.

const CASES = [
  {
    company: 'Sanford Rose Associates', industry: 'Executive Search', url: 'https://sanfordrose.com/',
    title: '16+ Hours to 10 Minutes: AI Recruiting Automation',
    metrics: [['10 min', 'Per recruiting cycle (from 16h)'], ['5', 'Workflows automated'], ['3×', 'Recruiter output']],
    timeline: '10 weeks',
    impact: 'From 16 hours to 10 minutes per recruiting cycle. Five workflows automated end-to-end, recruiter throughput tripled.',
    challenge: 'Part of a 16-firm executive search network, they relied on manual documentation for every recruiting workflow. Intake forms, candidate submittals, interview prep, and talent reports consumed 16+ hours per cycle, capping recruiter capacity and slowing placements.',
    solution: 'Built srAi Agents: an AI platform automating 5 core recruiting workflows: search kickoffs, candidate submittals, interview prep packets, opportunity comparisons, and talent vault profiles - all generated in minutes instead of hours. Self-hosted on n8n so client data never touches third-party servers.',
    tech: ['JavaScript', 'n8n', 'REST APIs', 'AI/LLM'],
  },
  {
    company: 'PCA Insurance Services', industry: 'Insurance Brokerage', url: 'https://www.pcainsuranceservices.com/',
    title: '8 Disconnected Platforms, Zero Manual Handoffs',
    metrics: [['8', 'Platforms unified'], ['$50K+', 'Annual savings'], ['100%', 'Renewal coverage']],
    timeline: '10 weeks',
    impact: 'Eight disconnected platforms unified into one real-time hub. $50K saved yearly, 100% renewal coverage, row-level security baked in.',
    challenge: 'Daily operations ran across 8 disconnected platforms: policies, sales, payroll, calls, email, scheduling, and finances in spreadsheets. Nothing synced. Staff re-entered the same data across tools every day, with zero automation for renewals or reporting.',
    solution: 'Built PCA Cortex: a unified platform connecting all 8 systems in real time. Automated client sync, smart renewal reminders at 90/60/30/15 days, AI document processing, financial dashboards, and 12+ automated notifications. Fully bilingual, with row-level security and real-time Postgres triggers for zero-latency sync.',
    tech: ['React', 'TypeScript', 'Supabase', 'PostgreSQL', 'Google Gemini AI', 'Cloud Functions'],
  },
  {
    company: 'Next Level Exchange', industry: 'Recruiter Training', url: 'https://nlexchange.com/',
    title: 'From Silent Churn to 100% Revenue Capture',
    metrics: [['<5 min', 'Response time'], ['100%', 'Revenue events captured'], ['24/7', 'Automated follow-up']],
    timeline: '4 weeks',
    impact: 'Every Stripe event now triggers the right CRM action in under 5 minutes. Zero missed upsells, zero silent churn across storefronts.',
    challenge: 'Multiple e-commerce storefronts where every post-sale event (purchases, upgrades, cancellations, failed payments) required manual tracking across platforms. The sales team had no systematic way to act on revenue signals, leading to missed upsells and silent churn.',
    solution: 'Built an event-driven revenue pipeline connecting Stripe webhooks to Pipedrive CRM in real time. Every transaction triggers targeted CRM activities: onboarding for new purchases, expansion for upgrades, retention for cancellations, recovery for failed payments. Idempotent handlers and dead-letter queues mean failed messages retry automatically.',
    tech: ['Stripe Webhooks', 'Pipedrive API', 'n8n', 'JavaScript'],
  },
  {
    company: 'GS Service', industry: 'Industrial Services', url: '',
    title: 'Zero Digital Tools to Full Operational Command',
    metrics: [['0→1', 'Digital platform'], ['100%', 'Job traceability'], ['3×', 'Faster invoicing']],
    timeline: '8 weeks',
    impact: 'Paper to real-time operations in 8 weeks. Every job tracked dispatch-to-invoice, 3× faster billing, offline-first PWA for field crews.',
    challenge: 'An industrial machinery maintenance firm ran its entire operation on paper and basic spreadsheets. Project assignments, scheduling, service records, and invoicing were all manual, with no centralized record, no real-time crew availability, and invoices created days late from memory.',
    solution: 'Built a comprehensive operations platform covering the full service lifecycle: project assignment, real-time technician scheduling, equipment service history, automated completion reports, and invoices tied to signed-off work orders. Designed as an offline-first PWA so field crews can log jobs in dead zones and sync later.',
    tech: ['React', 'TypeScript', 'Supabase', 'PostgreSQL', 'Cloud Functions'],
  },
  {
    company: 'Confidential Client', industry: 'FinTech / WealthTech', url: '', confidential: true,
    title: 'From No-Code Ceiling to Live Wealth-Tech Platform',
    metrics: [['18K+', 'Transactions reconciled'], ['99.95%', 'Data accuracy'], ['3 yrs', 'History rebuilt']],
    timeline: '4 weeks',
    impact: 'Evolved from a no-code rebuild into a production wealth-tech platform serving real investors. Multi-account analytics, real-time positions, accounting-grade precision.',
    challenge: 'A wealth-tech operator managing complex multi-account investor portfolios had outgrown their no-code platform. The tool couldn\u2019t deliver accounting-grade precision, real-time multi-account analytics, or the operational depth needed to serve real investors at scale.',
    solution: 'Rebuilt as a full-stack platform from scratch: real-time multi-account portfolio analytics, automated daily sync with broker data, accounting-grade reconciliation, and historical reconstruction from raw transaction data. Hardened for multi-tenant isolation and now in continuous production as a subscription product.',
    tech: ['React', 'TypeScript', 'PostgreSQL', 'Real-Time Analytics', 'Subscription SaaS'],
  },
  {
    company: 'Medora', industry: 'Health-Tech', url: 'https://medora.solutions',
    title: 'AI Copilot for Clinical Decisions',
    metrics: [['Live', 'In production'], ['AI', 'Clinical copilot'], ['Unified', 'Patient records']],
    timeline: 'In production',
    impact: 'A clinical AI copilot that turns heterogeneous patient records into a unified case view, surfacing red flags traceable to clinical guidelines.',
    challenge: 'Doctors face short consults with heterogeneous patient records (PDFs, photos, lab reports, discharge summaries) from multiple providers with no common standard. The result: late diagnoses, dangerous polypharmacy, and avoidable readmissions.',
    solution: 'A clinical AI copilot that structures heterogeneous patient records into a unified case view and surfaces cross-document red flags traceable to standard clinical guidelines. Diagnostic responsibility stays with the doctor; the copilot raises patterns a short consult would miss.',
    tech: ['AI Vision', 'Cloud-Native', 'Healthcare Data'],
  },
];

// ── Spotlight: one featured case at a time + a tab strip of all six ──

function CaseTab({ cs, i, active, onSelect }) {
  return (
    <button onClick={() => onSelect(i)} aria-pressed={active} style={{
      all: 'unset', boxSizing: 'border-box', cursor: 'pointer', flexShrink: 0,
      padding: '10px 16px', borderRadius: 12, transition: 'all 260ms ease',
      background: active ? 'var(--accent-bg)' : 'transparent',
      border: `1px solid ${active ? 'var(--eyebrow-bd)' : 'var(--hairline)'}`,
    }}>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 600, lineHeight: 1.2,
        color: active ? 'var(--accent)' : 'var(--fg)', whiteSpace: 'nowrap' }}>{cs.company}</span>
      <span className="mono" style={{ display: 'block', fontSize: 9.5, letterSpacing: '0.1em',
        textTransform: 'uppercase', color: 'var(--fg-faint)', marginTop: 3, whiteSpace: 'nowrap' }}>{cs.industry}</span>
    </button>
  );
}

function FeaturedCase({ cs, onOpen }) {
  return (
    <div className="glass eglass eglass-soft case-feature" style={{ borderRadius: 24, overflow: 'hidden' }}>
      <div className="case-feature-grid">
        {/* left: story */}
        <div style={{ padding: 'clamp(18px, 2.6vh, 38px) clamp(20px, 2.6vw, 38px)', display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
            {cs.url ? (
              <a href={cs.url} target="_blank" rel="noopener noreferrer" style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18, color: 'var(--fg)', textDecoration: 'none' }}>{cs.company} ↗</a>
            ) : (
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18, color: 'var(--fg)' }}>{cs.company}</span>
            )}
            <span className="mono" style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-faint)' }}>{cs.industry}</span>
          </div>

          <h3 key={cs.company} style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 'clamp(1.25rem, min(2.3vw, 3vh), 1.85rem)', lineHeight: 1.16, letterSpacing: '-0.02em',
            color: 'var(--fg)', margin: 'clamp(10px, 1.4vh, 14px) 0 0', animation: 'fadeq 500ms cubic-bezier(0.16,1,0.3,1)',
          }}>{cs.title}</h3>

          <p key={`i${cs.company}`} style={{ fontSize: 'clamp(13.5px, 1.1vw, 15px)', lineHeight: 1.55, color: 'var(--fg-muted)', margin: 'clamp(10px, 1.4vh, 16px) 0 0', maxWidth: 520, animation: 'fadeq 500ms cubic-bezier(0.16,1,0.3,1)' }}>{cs.impact}</p>

          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, margin: 'clamp(14px, 2vh, 22px) 0 0' }}>
            {cs.tech.slice(0, 5).map((tch) => (
              <span key={tch} style={{ fontSize: 11.5, padding: '5px 11px', borderRadius: 999, color: 'var(--fg-muted)', background: 'color-mix(in srgb, var(--fg) 5%, transparent)', border: '1px solid var(--hairline)' }}>{tch}</span>
            ))}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 'auto', paddingTop: 'clamp(14px, 2vh, 24px)', flexWrap: 'wrap' }}>
            <button onClick={onOpen} className="gcta" style={{
              all: 'unset', position: 'relative', overflow: 'hidden', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: 'clamp(9px, 1.2vh, 12px) clamp(18px, 2vh, 22px)', borderRadius: 12, fontSize: 14, fontWeight: 600, boxSizing: 'border-box',
              color: 'var(--platinum)', background: 'var(--violet)', transition: 'background 200ms ease, transform 200ms ease',
            }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = 'none'; }}
            >Full case study
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="square"><path d="M9 5l7 7-7 7" /></svg>
            </button>
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--fg-faint)' }}>{cs.timeline}</span>
          </div>
        </div>

        {/* right: anchor metrics */}
        <div className="case-feature-metrics">
          {cs.metrics.map(([v, l], k) => (
            <div key={l} style={{ paddingBlock: 4 }}>
              <div key={`${cs.company}-${k}`} style={{ fontFamily: 'var(--font-display)', fontWeight: 650, fontSize: 'clamp(1.5rem, min(2.7vw, 3.4vh), 2.4rem)', lineHeight: 1, color: 'var(--accent)', animation: 'fadeq 500ms cubic-bezier(0.16,1,0.3,1)' }}>{v}</div>
              <div style={{ fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)', marginTop: 'clamp(5px, 0.8vh, 8px)', lineHeight: 1.3 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CaseModal({ idx, setIdx, onClose }) {
  const cs = CASES[idx];
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft' && idx > 0) setIdx(idx - 1);
      if (e.key === 'ArrowRight' && idx < CASES.length - 1) setIdx(idx + 1);
    };
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [idx]);

  return (
    <div role="dialog" aria-modal="true" onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, background: 'color-mix(in srgb, var(--bg) 55%, transparent)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
    }}>
      <div className="glass-strong glass" onClick={(e) => e.stopPropagation()} style={{
        borderRadius: 24, maxWidth: 880, width: '100%', maxHeight: '88vh', overflowY: 'auto', padding: 'clamp(24px, 4vw, 44px)',
      }}>
        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, minWidth: 0 }}>
            {cs.url ? (
              <a href={cs.url} target="_blank" rel="noopener noreferrer" className="eyebrow" style={{ color: 'var(--accent)' }}>{cs.company} ↗</a>
            ) : (
              <span className="eyebrow">{cs.company}</span>
            )}
            <span className="mono" style={{ fontSize: 11, color: 'var(--fg-faint)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{cs.industry}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <NavBtn disabled={idx === 0} onClick={() => setIdx(idx - 1)} dir="left" />
            <span className="mono" style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{idx + 1}/{CASES.length}</span>
            <NavBtn disabled={idx === CASES.length - 1} onClick={() => setIdx(idx + 1)} dir="right" />
            <span style={{ width: 1, height: 20, background: 'var(--hairline)', margin: '0 4px' }} />
            <NavBtn onClick={onClose} dir="close" />
          </div>
        </div>

        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(1.4rem,3vw,2rem)', color: 'var(--fg)', lineHeight: 1.2, margin: '22px 0 24px' }}>{cs.title}</h3>

        {/* metrics */}
        <div className="grid-3" style={{ gap: 14, marginBottom: 18 }}>
          {cs.metrics.map(([v, l]) => (
            <div key={l} style={{ textAlign: 'center', padding: '18px 10px', borderRadius: 14, background: 'var(--accent-bg)', border: '1px solid var(--hairline)' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 650, fontSize: 'clamp(1.4rem,3vw,1.9rem)', color: 'var(--accent)', lineHeight: 1 }}>{v}</div>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)', marginTop: 8, lineHeight: 1.3 }}>{l}</div>
            </div>
          ))}
        </div>

        <span style={{ display: 'inline-flex', padding: '7px 14px', borderRadius: 999, fontSize: 12.5, fontWeight: 500, color: 'var(--accent)', border: '1px solid var(--eyebrow-bd)', background: 'var(--accent-bg)', marginBottom: 22 }}>{cs.timeline}</span>

        {/* before / after */}
        <div className="grid-2" style={{ marginBottom: 22 }}>
          <div style={{ borderRadius: 14, padding: 20, background: 'color-mix(in srgb, var(--fg) 4%, transparent)', border: '1px solid var(--hairline)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--fg-faint)' }} />
              <span className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--fg-faint)' }}>Before</span>
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.65, color: 'var(--fg-muted)', margin: 0 }}>{cs.challenge}</p>
          </div>
          <div style={{ borderRadius: 14, padding: 20, background: 'var(--accent-bg)', border: '1px solid var(--eyebrow-bd)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--accent)' }} />
              <span className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--accent)' }}>After</span>
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.65, color: 'var(--fg)', margin: 0 }}>{cs.solution}</p>
          </div>
        </div>

        {/* tech */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 26 }}>
          {cs.tech.map((t) => (
            <span key={t} style={{ fontSize: 12, padding: '5px 12px', borderRadius: 999, color: 'var(--fg-muted)', background: 'color-mix(in srgb, var(--fg) 5%, transparent)', border: '1px solid var(--hairline)' }}>{t}</span>
          ))}
        </div>

        <a href="#contact" onClick={onClose} className="gcta" style={{
          display: 'inline-block', padding: '12px 22px', borderRadius: 12, fontSize: 14, fontWeight: 600,
          color: 'var(--accent)', border: '1px solid var(--eyebrow-bd)', background: 'var(--accent-bg)', textDecoration: 'none',
        }}>Booking Q2 2026: is your project a fit? →</a>

        {/* dots */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginTop: 28 }}>
          {CASES.map((_, i) => (
            <button key={i} onClick={() => setIdx(i)} aria-label={`Case ${i + 1}`} style={{
              height: 8, width: i === idx ? 24 : 8, borderRadius: 999, border: 'none', cursor: 'pointer',
              background: i === idx ? 'var(--accent)' : 'var(--hairline)', transition: 'all 300ms ease',
            }} />
          ))}
        </div>
      </div>
    </div>
  );
}

function NavBtn({ disabled, onClick, dir }) {
  const paths = { left: 'M15 19l-7-7 7-7', right: 'M9 5l7 7-7 7', close: 'M18 6L6 18M6 6l12 12' };
  return (
    <button onClick={onClick} disabled={disabled} aria-label={dir} style={{
      width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 999,
      border: '1px solid var(--hairline)', background: 'transparent', color: 'var(--accent)', cursor: disabled ? 'default' : 'pointer',
      opacity: disabled ? 0.25 : 1,
    }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square"><path d={paths[dir]} /></svg>
    </button>
  );
}

function Cases() {
  const [open, setOpen] = React.useState(null);
  const [sel, setSel] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [ref, inView] = useInView({ threshold: 0.3 });

  // slow auto-advance through the cases, paused on interaction / when a modal is open
  React.useEffect(() => {
    if (!inView || paused || open !== null) return;
    const id = setInterval(() => setSel((s) => (s + 1) % CASES.length), 5200);
    return () => clearInterval(id);
  }, [inView, paused, open]);

  const pick = (i) => { setSel(i); setPaused(true); };

  return (
    <section id="cases" data-screen-label="Cases" className="sec" aria-labelledby="cases-h"
      style={{ minHeight: 'calc(100svh - 72px)', display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingBlock: 'clamp(24px, 3.5vh, 56px)' }}>
      <div className="sec-wrap" ref={ref}
        onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
        <SectionHead eyebrow="Proof, not promises" align="center" max={780} style={{ marginBottom: 'clamp(20px, 3vh, 34px)' }}
          sub="Six industries, one principal: the engineer who scopes your problem is the one who ships it.">
          <span id="cases-h">Real systems, <span className="accent">real results</span></span>
        </SectionHead>

        {/* tab strip */}
        <Reveal delay={100} className="case-tabs">
          {CASES.map((cs, i) => (
            <CaseTab key={cs.company} cs={cs} i={i} active={i === sel} onSelect={pick} />
          ))}
        </Reveal>

        {/* featured case */}
        <Reveal delay={160} style={{ marginTop: 'clamp(16px, 2.4vh, 26px)' }}>
          <FeaturedCase cs={CASES[sel]} onOpen={() => setOpen(sel)} />
        </Reveal>

        {/* progress dots + trust line */}
        <Reveal delay={200} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginTop: 'clamp(16px, 2.4vh, 26px)', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 7 }}>
            {CASES.map((_, i) => (
              <button key={i} onClick={() => pick(i)} aria-label={`Case ${i + 1}`} style={{
                height: 7, width: i === sel ? 22 : 7, borderRadius: 999, border: 'none', cursor: 'pointer',
                background: i === sel ? 'var(--accent)' : 'var(--hairline)', transition: 'all 300ms ease', padding: 0,
              }} />
            ))}
          </div>
          <span style={{ width: 1, height: 14, background: 'var(--hairline)' }} />
          <span style={{ fontSize: 12.5, letterSpacing: '0.03em', color: 'var(--fg-faint)' }}>6/6 still in production · founder-led, no handoffs</span>
        </Reveal>
      </div>

      {open !== null && <CaseModal idx={open} setIdx={setOpen} onClose={() => setOpen(null)} />}
    </section>
  );
}

window.Cases = Cases;
