// Sections: Nav, Logos, Services, Process, Work, Stats, Team, Testimonials, Contact, Footer
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS, useMemo: useMemoS } = React;

// ── Nav ─────────────────────────────────────────────────────────────────────
function Nav({ onOpenMenu, theme, onToggleTheme }) {
  const [scrolled, setScrolled] = useStateS(false);
  useEffectS(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    ['Services', '#services'],
    ['Work', '#work'],
    ['Process', '#process'],
    ['Team', '#team'],
    ['Contact', '#contact'],
  ];

  return (
    <header className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
      <div className="shell nav__inner">
        <a href="#home" className="nav__logo" aria-label="QA SONIC home">
          <BrandMark size={44} />
        </a>

        <nav className="nav__links">
          {links.map(([label, href], idx) => (
            <a key={href} href={href} className="nav__link">{label}</a>
          ))}
        </nav>

        <div className="nav__right">
          <div className="theme-toggle" role="group" aria-label="Theme">
            <button
              type="button"
              className={`theme-toggle__seg ${theme === 'light' ? 'is-active' : ''}`}
              onClick={() => theme === 'dark' && onToggleTheme()}
              aria-pressed={theme === 'light'}
              aria-label="Light theme"
              title="Light theme"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
            </button>
            <button
              type="button"
              className={`theme-toggle__seg ${theme === 'dark' ? 'is-active' : ''}`}
              onClick={() => theme === 'light' && onToggleTheme()}
              aria-pressed={theme === 'dark'}
              aria-label="Dark theme"
              title="Dark theme"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
            </button>
            <span className={`theme-toggle__indicator ${theme === 'dark' ? 'is-right' : ''}`} aria-hidden="true" />
          </div>
          <a href="#contact" className="btn btn--accent nav__cta">Start a project →</a>
          <button className="nav__menu" onClick={onOpenMenu} aria-label="Open menu">
            <span /><span /><span />
          </button>
        </div>
      </div>
    </header>
  );
}

function MenuOverlay({ open, onClose }) {
  useEffectS(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const items = [
    ['Services', '#services', 'Six practices, pick one or the whole stack'],
    ['Work', '#work', 'Selected case studies'],
    ['Process', '#process', 'How a QA sprint runs'],
    ['Team', '#team', 'Humans behind the tests'],
    ['Contact', '#contact', 'Start a conversation'],
  ];

  return (
    <div className={`menu ${open ? 'menu--open' : ''}`} aria-hidden={!open}>
      <div className="menu__bg" onClick={onClose} />
      <div className="menu__panel">
        <div className="shell menu__inner">
          <div className="menu__top">
            <span className="eyebrow">// Navigation</span>
            <button className="btn btn--ghost" onClick={onClose}>Close ✕</button>
          </div>
          <ul className="menu__list">
            {items.map(([label, href, sub], i) => (
              <li key={href} style={{ transitionDelay: `${i*60}ms` }}>
                <a href={href} onClick={onClose}>
                  <span className="mono menu__num">0{i+1} /</span>
                  <span className="display menu__label">{label}</span>
                  <span className="menu__sub">{sub}</span>
                  <span className="menu__arrow">→</span>
                </a>
              </li>
            ))}
          </ul>
          <div className="menu__footer">
            <span className="mono">hello@qasonic.com</span>
            <span className="mono">Islamabad · Remote</span>
            <span className="mono">ISTQB Certified · Top Rated Plus · 6,000+ hrs</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Logo marquee ────────────────────────────────────────────────────────────
function LogoMarquee() {
  const names = ['dropFleet', '101 Digital', 'Tictales', 'Kasper', 'FitNexus', 'GreetEat', 'Wicked Web', 'QPR', 'Luna Park', 'aphra', 'Lexamica'];
  const row = [...names, ...names];
  return (
    <section id="clients" className="logos">
      <div className="shell">
        <h2 className="display logos__title reveal">Trusted by teams that can't afford a regression.</h2>
      </div>
      <div className="logos__strip reveal">
        <div className="marquee">
          {row.map((n, i) => (
            <div key={i} className="logos__item">
              <LogoGlyph i={i % 6} />
              <span>{n}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function LogoGlyph({ i }) {
  const glyphs = [
    <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" fill="none"/><circle cx="12" cy="12" r="4" fill="currentColor"/></svg>,
    <svg viewBox="0 0 24 24"><path d="M4 20L12 4l8 16H4z" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>,
    <svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M3 12h18M12 3v18" stroke="currentColor" strokeWidth="1.5"/></svg>,
    <svg viewBox="0 0 24 24"><path d="M3 12a9 9 0 0118 0M3 12a9 9 0 009 9M21 12a9 9 0 01-9 9" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>,
    <svg viewBox="0 0 24 24"><path d="M4 4h8v8H4zM12 12h8v8h-8z" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>,
    <svg viewBox="0 0 24 24"><path d="M12 2l10 6v8l-10 6L2 16V8z" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>,
  ];
  return <span className="logos__glyph">{glyphs[i]}</span>;
}

// ── Services ────────────────────────────────────────────────────────────────
const SERVICES = [
  {
    code: 'S.01', title: 'Test Automation',
    body: 'Fast, reliable automated test suites that catch bugs before they reach production. Web, API, mobile, cross-browser — CI-wired and maintainable.',
    cover: ['End-to-end application flows', 'API and integration testing', 'Cross-browser compatibility', 'Mobile app automation', 'CI/CD pipeline integration'],
    stack: ['Playwright', 'Cypress', 'Selenium', 'Appium'],
    best: 'SaaS teams shipping continuously, startups scaling testing infrastructure',
  },
  {
    code: 'S.02', title: 'Payment Gateway Testing',
    body: 'Flawless payment flows across 11+ processors and every edge case that matters.',
    cover: ['Checkout journeys and user flows', 'Stripe, PayPal, Authorize.net, Square, Braintree + 6 more', 'Error handling and failed payments', 'Refund and subscription workflows', 'PCI compliance verification'],
    stack: ['Stripe', 'PayPal', 'Braintree', 'Square'],
    best: 'E-commerce platforms, fintech applications, subscription services',
  },
  {
    code: 'S.03', title: 'AI / LLM Testing',
    body: 'Validate AI-powered features with specialized frameworks designed for large language models.',
    cover: ['Response quality and accuracy', 'RAG pipeline performance', 'Hallucination detection', 'Prompt injection vulnerabilities', 'AI feature regression testing'],
    stack: ['DeepEval', 'RAGAs', 'LangSmith'],
    best: 'AI startups, companies integrating LLMs, chatbot applications',
  },
  {
    code: 'S.04', title: 'Performance Engineering',
    body: 'Ensure your application scales perfectly under load — before your users find out it doesn\'t.',
    cover: ['Load and stress testing', 'Performance benchmarking', 'Bottleneck identification', 'Database query optimization', 'CDN and caching validation'],
    stack: ['k6', 'JMeter', 'Lighthouse', 'sitespeed.io'],
    best: 'Apps expecting traffic spikes, platforms scaling infrastructure',
  },
  {
    code: 'S.05', title: 'Mobile App Testing',
    body: 'Comprehensive iOS and Android coverage with real devices, real scenarios.',
    cover: ['Functional testing across device matrix', 'Performance and battery impact', 'UI/UX validation', 'App store submission requirements', 'Push notifications and offline behavior'],
    stack: ['Appium', 'XCTest', 'Espresso', 'Real devices'],
    best: 'Mobile-first companies, apps with complex user flows',
  },
  {
    code: 'S.06', title: 'Continuous Testing & CI/CD',
    body: 'Testing wired directly into your deployment pipeline. Every commit, every PR, instant feedback.',
    cover: ['Automated tests on every pull request', 'Performance regression detection', 'Test result dashboards and alerts', 'Slack / email notifications', 'Automated rollback triggers'],
    stack: ['GitHub Actions', 'CircleCI', 'Jenkins', 'GitLab'],
    best: 'Teams practicing continuous deployment, DevOps-focused engineering',
  },
];

function Services() {
  return (
    <section id="services" className="services">
      <div className="shell">
        <div className="section-head reveal">
          <div></div>
          <div>
            <h2 className="display">Six practices.<br/><span style={{ color: 'var(--fg-dim)' }}>One job: break it before users do.</span></h2>
            <p>We run as a dedicated QA unit attached to your product team. Pick one practice or the whole stack — testing that scales with your velocity, not your headcount.</p>
          </div>
        </div>
        <div className="grid services__grid">
          {SERVICES.map((s, i) => (
            <ServiceCard key={s.code} s={s} delay={i * 60} />
          ))}
        </div>
      </div>
    </section>
  );
}

function ServiceCard({ s, delay }) {
  return (
    <article className="card card--hover service reveal" style={{ '--rd': `${delay}ms` }}>
      <div className="service__head">
        <span className="mono">{s.code}</span>
        <span className="service__plus">+</span>
      </div>
      <h3 className="display service__title">{s.title}</h3>
      <p className="service__body">{s.body}</p>
      <div className="service__cover mono">// What we cover</div>
      <ul className="service__list">
        {s.cover.map(c => <li key={c}>{c}</li>)}
      </ul>
      <div className="service__tags">
        {s.stack.map(t => <span key={t} className="mono service__tag">{t}</span>)}
      </div>
      <div className="service__best mono">
        <span style={{ color: 'var(--fg-mute)' }}>// Best for</span> {s.best}
      </div>
    </article>
  );
}

// ── Process (sticky scroll) ─────────────────────────────────────────────────
const PROCESS = [
  { n: '01', t: 'Discovery', when: 'Week 1', b: 'We analyze your application, tech stack, and critical user flows.', items: ['Test strategy document', 'Risk assessment', 'Coverage roadmap', 'Proposed automation framework'] },
  { n: '02', t: 'Setup', when: 'Weeks 1–2', b: 'We build the automated test infrastructure tailored to your stack.', items: ['Test environment configuration', 'Initial smoke test suite', 'CI/CD integration', 'Documentation and handoff'] },
  { n: '03', t: 'Execution', when: 'Ongoing', b: 'Comprehensive test runs on every release with detailed reporting.', items: ['Automated test execution', 'Bug reports with reproduction steps', 'Quality metrics dashboard', 'Weekly status updates', 'Slack / email integration'] },
  { n: '04', t: 'Optimization', when: 'Monthly', b: 'Continuous improvement of coverage, speed, and reliability.', items: ['Expanded test coverage', 'Performance optimization', 'New edge case coverage', 'Quarterly QA health reports'] },
  { n: '05', t: 'Scale', when: 'As needed', b: 'Grow testing capacity to match your velocity.', items: ['Add engineers in 1–2 weeks', 'Expand to new platforms', 'Increase test frequency', 'Additional service modules'] },
];

function Process() {
  return (
    <section id="process" className="process">
      <div className="shell">
        <div className="section-head reveal">
          <div></div>
          <div>
            <h2 className="display">A five-step loop<br/><span style={{ color: 'var(--fg-dim)' }}>that doesn't end at launch.</span></h2>
            <p>QA is a practice, not a milestone. Our process threads into your sprint rhythm and runs continuously.</p>
          </div>
        </div>

        <div className="process__wrap">
          <aside className="process__rail">
            <div className="process__rail-inner">
              <div className="mono" style={{ color: 'var(--fg-mute)', marginBottom: 20 }}>// loop.exe</div>
              <ProcessDiagram />
            </div>
          </aside>
          <ol className="process__list">
            {PROCESS.map((p, i) => (
              <li key={p.n} className="process__item reveal" style={{ '--rd': `${i*60}ms` }}>
                <div className="process__n display">{p.n}</div>
                <div>
                  <div className="mono" style={{ color: 'var(--fg-mute)', marginBottom: 4 }}>// {p.when}</div>
                  <h3 className="display process__t">{p.t}</h3>
                  <p className="process__b">{p.b}</p>
                  <ul className="process__items">
                    {p.items.map(it => <li key={it}>{it}</li>)}
                  </ul>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </div>
    </section>
  );
}

function ProcessDiagram() {
  const [active, setActive] = useStateS(0);
  useEffectS(() => {
    const id = setInterval(() => setActive(x => (x + 1) % 5), 1800);
    return () => clearInterval(id);
  }, []);
  const labels = ['Discovery', 'Setup', 'Execution', 'Optimization', 'Scale'];
  const icons = ['🔍', '⚙', '▶', '⚡', '↗'];
  return (
    <div className="loop-anim">
      <svg viewBox="0 0 260 260" width="100%" style={{ maxWidth: 280 }}>
        <defs>
          <filter id="pw-glow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="4" result="b"/>
            <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>
        {/* Orbit ring */}
        <circle cx="130" cy="130" r="100" fill="none" stroke="var(--line-strong)" strokeDasharray="2 4"/>
        <circle cx="130" cy="130" r="100" fill="none" stroke="var(--accent)" strokeWidth="2"
          strokeDasharray="15 600" strokeLinecap="round"
          transform={`rotate(${active * 72 - 90} 130 130)`}
          style={{ transition: 'transform .9s cubic-bezier(.6,0,.2,1)', filter: 'url(#pw-glow)' }}/>
        {/* Step nodes */}
        {[0,1,2,3,4].map(i => {
          const a = (i / 5) * Math.PI * 2 - Math.PI/2;
          const x = 130 + Math.cos(a) * 100;
          const y = 130 + Math.sin(a) * 100;
          const on = i === active;
          return (
            <g key={i} style={{ transition: 'all .4s' }}>
              <circle cx={x} cy={y} r={on ? 18 : 13}
                fill={on ? 'var(--accent)' : 'var(--bg-elev)'}
                stroke={on ? 'var(--accent)' : 'var(--line-strong)'}
                strokeWidth="1.5"
                style={{ transition: 'all .4s cubic-bezier(.2,.8,.2,1)' }}/>
              <text x={x} y={y+4} textAnchor="middle"
                fontFamily="var(--font-mono)" fontSize="10"
                fill={on ? 'var(--accent-ink)' : 'var(--fg)'}
                style={{ transition: 'fill .4s' }}>0{i+1}</text>
            </g>
          );
        })}
        {/* Center hub */}
        <circle cx="130" cy="130" r="32" fill="var(--bg-elev-2)" stroke="var(--line-strong)"/>
        <circle cx="130" cy="130" r="32" fill="none" stroke="var(--accent)" strokeWidth="2"
          strokeDasharray="6 8" opacity="0.6">
          <animateTransform attributeName="transform" type="rotate"
            from="0 130 130" to="360 130 130" dur="12s" repeatCount="indefinite"/>
        </circle>
        <text x="130" y="128" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="8" fill="var(--fg-mute)">STEP</text>
        <text x="130" y="144" textAnchor="middle" fontFamily="var(--font-display)" fontSize="16"
          fontWeight="600" fill="var(--fg)"
          key={active}
          style={{ animation: 'loopPop .4s ease-out' }}>0{active+1}</text>
      </svg>
      <div className="loop-anim__label mono">
        <span style={{ color: 'var(--accent)' }}>›</span> {labels[active]}
      </div>
    </div>
  );
}

// ── Case studies ────────────────────────────────────────────────────────────
const CASES = [
  {
    id: 'northwind',
    client: 'Northwind Freight', sector: 'Logistics · Web + iOS', year: '2025',
    title: 'Cutting release rollbacks to near-zero on a 14-day sprint cadence',
    stat: [['-96%', 'rollbacks'], ['89%', 'coverage'], ['2x', 'release frequency'], ['0.2/mo', 'rollback rate']],
    challenge: 'Weekly releases were triggering 3–4 rollbacks per month. Critical bugs in dispatch logic were reaching production despite manual QA.',
    approach: 'Built comprehensive E2E test suite covering dispatch workflows, driver assignments, and real-time tracking. Integrated into CI/CD with mandatory gates.',
    results: ['Rollbacks reduced from 4/month to 0.2/month', 'Test coverage increased from 31% to 89%', 'Release confidence allowed team to ship twice per week'],
    hue: 130,
  },
  {
    id: 'helio',
    client: 'Helio Health', sector: 'Healthtech · Web', year: '2025',
    title: 'Passing SOC 2 audit without freezing feature development',
    stat: [['0', 'engineer-hours added'], ['1st', 'attempt pass'], ['Type II', 'certification'], ['Ongoing', 'compliance']],
    challenge: 'SOC 2 Type II audit required comprehensive security testing documentation without disrupting product roadmap.',
    approach: 'Implemented automated security regression suite, penetration testing schedule, and audit-ready documentation — all running parallel to feature work.',
    results: ['Passed SOC 2 audit first attempt', 'Zero engineering time diverted from roadmap', 'Ongoing compliance testing automated'],
    hue: 48,
  },
  {
    id: 'kestrel',
    client: 'Kestrel Banking', sector: 'Fintech · iOS + Android', year: '2024',
    title: 'From 40% to 94% mobile test coverage without slowing the roadmap',
    stat: [['94%', 'coverage'], ['8 wks', 'timeline'], ['12 min', 'suite runtime'], ['6 hrs', 'before']],
    challenge: 'Mobile app coverage was stuck at 40%. Manual testing couldn\'t keep up with 2-week release cycles.',
    approach: 'Built parallel automated test infrastructure while team continued shipping. Prioritized critical paths first, expanded coverage incrementally.',
    results: ['Test coverage: 40% → 94% in 8 weeks', 'Regression suite runtime: 6 hours → 12 minutes', 'Release process unchanged, confidence transformed'],
    hue: 250,
  },
  {
    id: 'ovrlp',
    client: 'Ovrlp', sector: 'Consumer · Web', year: '2024',
    title: 'Load-testing a launch that handled 11x its projected traffic without flinching',
    stat: [['11x', 'peak vs. plan'], ['110K', 'concurrent users'], ['<200ms', 'peak response'], ['0', 'downtime']],
    challenge: 'Product Hunt launch projected 10K concurrent users. Architecture untested under real load.',
    approach: 'Simulated 100K concurrent user scenarios, identified 7 critical bottlenecks, optimized before launch day.',
    results: ['Launch handled 110K concurrent users (11x projection)', 'Zero downtime during peak traffic', 'Response times stayed under 200ms at peak'],
    hue: 8,
  },
];

function Work({ onOpen }) {
  return (
    <section id="work" className="work">
      <div className="shell">
        <div className="section-head reveal">
          <div></div>
          <div>
            <h2 className="display">Bugs we found<br/><span style={{ color: 'var(--fg-dim)' }}>so nobody else had to.</span></h2>
            <p>A handful of engagements we're allowed to talk about. Real problems, real results. Click any card for the dossier.</p>
          </div>
        </div>

        <div className="work__grid">
          {CASES.map((c, i) => (
            <WorkCard key={c.id} c={c} onOpen={onOpen} delay={i*80} />
          ))}
        </div>
      </div>
    </section>
  );
}

function WorkCard({ c, onOpen, delay }) {
  return (
    <article
      className="work__card card card--hover reveal"
      style={{ '--rd': `${delay}ms`, '--hue': c.hue }}
      onClick={() => onOpen(c)}
      data-magnetic
    >
      <div className="work__thumb">
        <div className="work__thumb-grid" />
        <WorkGraphic id={c.id} />
        <div className="work__thumb-tag mono">{c.sector} · {c.year}</div>
        <div className="work__thumb-stat">
          <div className="display" style={{ fontSize: 72 }}>{c.stat[0][0]}</div>
          <div className="mono" style={{ color: 'var(--fg-dim)' }}>{c.stat[0][1]}</div>
        </div>
      </div>
      <div className="work__meta">
        <div className="mono" style={{ color: 'var(--fg-mute)' }}>{c.client}</div>
        <h3 className="display work__title">{c.title}</h3>
        <div className="work__stats-strip">
          {c.stat.slice(1, 4).map(([v, l]) => (
            <div key={l} className="work__stat-chip">
              <div className="work__stat-v">{v}</div>
              <div className="work__stat-l mono">{l}</div>
            </div>
          ))}
        </div>
        <div className="work__more">Open dossier →</div>
      </div>
    </article>
  );
}

function WorkGraphic({ id }) {
  if (id === 'northwind') {
    // Bar chart trending down (rollbacks reduced)
    return (
      <svg className="work__graphic" viewBox="0 0 300 140" preserveAspectRatio="none">
        <g fill="var(--brand)" opacity="0.85">
          <rect x="10" y="20" width="32" height="100" rx="4"/>
          <rect x="54" y="38" width="32" height="82" rx="4"/>
          <rect x="98" y="56" width="32" height="64" rx="4"/>
          <rect x="142" y="78" width="32" height="42" rx="4"/>
          <rect x="186" y="96" width="32" height="24" rx="4"/>
          <rect x="230" y="110" width="32" height="10" rx="4"/>
        </g>
        <path d="M26 30 L70 48 L114 66 L158 88 L202 106 L246 116" stroke="var(--brand-dark)" strokeWidth="2" fill="none" strokeLinecap="round"/>
        <circle cx="246" cy="116" r="5" fill="var(--brand-dark)"/>
      </svg>
    );
  }
  if (id === 'helio') {
    // Shield with checkmark for compliance
    return (
      <svg className="work__graphic" viewBox="0 0 300 140">
        <g transform="translate(10 10)">
          <path d="M60 5 L110 18 V60 C110 85 88 110 60 118 C32 110 10 85 10 60 V18 Z" fill="var(--brand)" opacity="0.2" stroke="var(--brand)" strokeWidth="2"/>
          <path d="M38 62 L54 78 L82 48" stroke="var(--brand)" strokeWidth="4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </g>
        <g transform="translate(150 20)" fontFamily="var(--font-mono)" fontSize="10" fill="var(--fg-dim)">
          <text x="0" y="12">✓ SOC 2 TYPE II</text>
          <text x="0" y="32">✓ HIPAA ready</text>
          <text x="0" y="52">✓ Pen-test passed</text>
          <text x="0" y="72">✓ Automated audit</text>
          <text x="0" y="92">✓ Zero findings</text>
        </g>
      </svg>
    );
  }
  if (id === 'kestrel') {
    // Coverage gauge — 40 → 94
    return (
      <svg className="work__graphic" viewBox="0 0 300 140">
        <g transform="translate(60 30)">
          <circle cx="40" cy="40" r="34" fill="none" stroke="var(--line-strong)" strokeWidth="8"/>
          <circle cx="40" cy="40" r="34" fill="none" stroke="var(--brand)" strokeWidth="8"
            strokeDasharray="201"
            strokeDashoffset="12"
            strokeLinecap="round"
            transform="rotate(-90 40 40)"/>
          <text x="40" y="45" textAnchor="middle" fontFamily="var(--font-display)" fontSize="20" fontWeight="600" fill="var(--brand)">94%</text>
        </g>
        <g transform="translate(170 40)" fontFamily="var(--font-mono)" fontSize="11" fill="var(--fg-dim)">
          <text x="0" y="0">was: 40%</text>
          <text x="0" y="20">now: 94%</text>
          <text x="0" y="40">runtime: 12m</text>
        </g>
        <path d="M150 70 L165 70" stroke="var(--brand)" strokeWidth="2" markerEnd="url(#arr)"/>
        <defs>
          <marker id="arr" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto">
            <path d="M0 0 L10 5 L0 10 z" fill="var(--brand)"/>
          </marker>
        </defs>
      </svg>
    );
  }
  if (id === 'ovrlp') {
    // Load wave at scale
    return (
      <svg className="work__graphic" viewBox="0 0 300 140" preserveAspectRatio="none">
        <defs>
          <linearGradient id="loadGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="var(--brand)" stopOpacity="0.4"/>
            <stop offset="1" stopColor="var(--brand)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d="M0 100 L20 90 L40 85 L60 88 L80 60 L100 40 L120 50 L140 30 L160 20 L180 15 L200 25 L220 40 L240 55 L260 70 L280 75 L300 72 L300 140 L0 140 Z" fill="url(#loadGrad)"/>
        <path d="M0 100 L20 90 L40 85 L60 88 L80 60 L100 40 L120 50 L140 30 L160 20 L180 15 L200 25 L220 40 L240 55 L260 70 L280 75 L300 72" stroke="var(--brand)" strokeWidth="2" fill="none"/>
        <g>
          <circle cx="180" cy="15" r="5" fill="var(--brand)"/>
          <circle cx="180" cy="15" r="10" fill="none" stroke="var(--brand)" strokeWidth="1.5" opacity="0.5">
            <animate attributeName="r" from="5" to="16" dur="1.6s" repeatCount="indefinite"/>
            <animate attributeName="opacity" from="0.6" to="0" dur="1.6s" repeatCount="indefinite"/>
          </circle>
        </g>
        <text x="188" y="12" fontFamily="var(--font-mono)" fontSize="10" fill="var(--fg)">peak: 110K</text>
      </svg>
    );
  }
  return null;
}

function CaseDetail({ c, onClose }) {
  useEffectS(() => {
    if (!c) return;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [c, onClose]);
  if (!c) return null;
  return (
    <div className="detail" role="dialog" aria-modal="true">
      <div className="detail__bg" onClick={onClose} />
      <div className="detail__panel">
        <div className="detail__top">
          <div className="detail__top-meta">
            <div className="mono detail__crumbs">
              <span>{c.client}</span>
              <span className="detail__crumb-sep">›</span>
              <span>{c.sector}</span>
              <span className="detail__crumb-sep">›</span>
              <span>{c.year}</span>
            </div>
            <h3 className="display detail__title">{c.title}</h3>
          </div>
          <button className="btn btn--ghost detail__close" onClick={onClose} aria-label="Close">✕</button>
        </div>

        <div className="detail__hero">
          <div className="detail__hero-grid" />
          <div className="detail__hero-orb" />
          <div className="detail__hero-graphic"><WorkGraphic id={c.id} /></div>
          <div className="detail__hero-stat">
            <div className="mono detail__hero-label">// Headline result</div>
            <div className="display detail__hero-num">{c.stat[0][0]}</div>
            <div className="mono detail__hero-cap">{c.stat[0][1]}</div>
          </div>
        </div>

        <div className="detail__body">
          <div className="detail__body-l">
            <div className="detail__block">
              <div className="eyebrow">[ The challenge ]</div>
              <p>{c.challenge}</p>
            </div>
            <div className="detail__block">
              <div className="eyebrow">[ Our approach ]</div>
              <p>{c.approach}</p>
            </div>
            <div className="detail__block">
              <div className="eyebrow">[ Results ]</div>
              <ul className="detail__results">
                {c.results.map(r => <li key={r}>{r}</li>)}
              </ul>
            </div>
          </div>
          <div className="detail__body-r">
            <div className="eyebrow">[ Outcomes ]</div>
            <ul className="detail__stats">
              {c.stat.map(([v, l], i) => (
                <li key={l} className={i === 0 ? 'is-lead' : ''}>
                  <div className="display detail__stat-v">{v}</div>
                  <div className="mono detail__stat-l">{l}</div>
                </li>
              ))}
            </ul>
            <div className="detail__cta">
              <a href="#contact" className="btn btn--accent" onClick={onClose}>Start a similar engagement →</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Stats strip ─────────────────────────────────────────────────────────────
function useCounter(target, inView, duration = 1400) {
  const [v, setV] = useStateS(0);
  useEffectS(() => {
    if (!inView) return;
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setV(Math.round(target * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView, target, duration]);
  return v;
}

function Stats() {
  const ref = useRefS(null);
  const [inView, setInView] = useStateS(false);
  useEffectS(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) setInView(true); }, { threshold: 0.3 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const a = useCounter(10, inView);
  const b = useCounter(2814, inView);
  const c = useCounter(94, inView);
  const d = useCounter(6000, inView);
  return (
    <section ref={ref} className="stats">
      <div className="shell">
        <div className="stats__grid">
          <StatCell k={`${a} yrs`} v="// Running QA sprints since 2014" />
          <StatCell k={b.toLocaleString()} v="// Bugs caught per month, on average" />
          <StatCell k={`${c}.7%`} v="// Median test coverage across clients" />
          <StatCell k={`${d.toLocaleString()}+`} v="// Hours delivered, 100% job success" />
        </div>
      </div>
    </section>
  );
}

function StatCell({ k, v }) {
  return (
    <div className="stats__cell reveal">
      <div className="display stats__k">{k}</div>
      <div className="mono stats__v">{v}</div>
    </div>
  );
}

// ── Team ────────────────────────────────────────────────────────────────────
const TEAM = [
  { n: 'Muhammad Ahsan Qadeer', r: 'Founder & Lead QA Engineer', loc: 'Islamabad', tag: 'ISTQB · 10+ yrs', tone: 'brand' },
  { n: 'Automation Engineer', r: 'Playwright & Cypress specialist', loc: 'Remote', tag: '8 yrs · Ex-fintech', tone: 'brand-deep' },
  { n: 'Performance Engineer', r: 'Load testing expert', loc: 'Remote', tag: '6 yrs · Ex-SaaS', tone: 'brand-soft' },
  { n: 'Mobile QA Engineer', r: 'iOS / Android', loc: 'Remote', tag: '7 yrs · Ex-mobile', tone: 'brand-ink' },
];

function Team() {
  return (
    <section id="team" className="team">
      <div className="shell">
        <div className="section-head reveal">
          <div></div>
          <div>
            <h2 className="display">The humans<br/><span style={{ color: 'var(--fg-dim)' }}>who read the test logs.</span></h2>
            <p>Senior-heavy, globally distributed, pragmatic. Every engagement is staffed by engineers who've shipped products like yours.</p>
          </div>
        </div>
        <div className="team__grid">
          {TEAM.map((p, i) => <TeamCard key={p.n} p={p} delay={i*50} />)}
        </div>
      </div>
    </section>
  );
}

function TeamCard({ p, delay }) {
  return (
    <article className="team__card card--hover reveal" style={{ '--rd': `${delay}ms` }} data-tone={p.tone}>
      <div className="team__portrait">
        <div className="team__portrait-grain" />
        <div className="team__portrait-initials display">{p.n.split(' ').map(x => x[0]).join('').slice(0,3)}</div>
        <div className="team__portrait-tag mono">{p.tag}</div>
      </div>
      <div className="team__meta">
        <div className="display team__name">{p.n}</div>
        <div className="mono team__role">{p.r} — {p.loc}</div>
      </div>
    </article>
  );
}

// ── Testimonials ────────────────────────────────────────────────────────────
const QUOTES = [
  { q: "Ahsan was my most trusted partner. He adapted to unpredictable situations with minimal oversight. I truly cannot say enough good things.", n: 'Andrew Epprecht', r: 'Phase 5 Analytics', tag: 'Trust' },
  { q: "Ahsan was able to free up so much of my time. A self-starter who doesn't need much direction. We are looking to work with him for a long time.", n: 'Rohit Maharjan', r: 'Wicked Web', tag: 'Efficiency' },
  { q: "He picks up on things super quickly and spots issues on his own initiative. Always made sure his work was thorough.", n: 'Ben Yihdego', r: 'Product-Led, Inc.', tag: 'Initiative' },
];

function Testimonials() {
  const [i, setI] = useStateS(0);
  useEffectS(() => {
    const id = setInterval(() => setI(x => (x + 1) % QUOTES.length), 6500);
    return () => clearInterval(id);
  }, []);
  const q = QUOTES[i];
  return (
    <section id="testimonials" className="quote">
      <div className="shell">
        <div className="section-head reveal in" style={{ textAlign: 'center', marginBottom: 32 }}>
          <h2 className="display" style={{ fontSize: 'clamp(32px, 4vw, 56px)', margin: 0 }}>What our clients say.</h2>
        </div>
        <blockquote className="display quote__q in" key={i}>
          “{q.q}”
        </blockquote>
        <div className="quote__meta reveal in">
          <div>
            <div className="display" style={{ fontSize: 20 }}>{q.n}</div>
            <div className="mono" style={{ color: 'var(--fg-dim)' }}>{q.r}</div>
          </div>
          <div className="quote__dots">
            {QUOTES.map((_, j) => (
              <button key={j} aria-label={`Quote ${j+1}`} onClick={() => setI(j)} className={`quote__dot ${i===j?'is-on':''}`} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Contact ─────────────────────────────────────────────────────────────────
const SERVICE_OPTIONS = [
  ['automation', 'Test Automation'],
  ['perf', 'Performance Engineering'],
  ['payments', 'Payment Gateway Testing'],
  ['ai', 'AI / LLM Testing'],
  ['mobile', 'Mobile Testing'],
  ['audit', 'QA Audit & Strategy'],
];

function Contact() {
  const [form, setForm] = useStateS({ name: '', email: '', company: '', services: [], budget: '5-20k', message: '' });
  const [errors, setErrors] = useStateS({});
  const [sent, setSent] = useStateS(false);

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = 'Valid email required';
    if (!form.company.trim()) e.company = 'Required';
    if (form.message.trim().length < 20) e.message = 'Tell us more (20+ chars)';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (validate()) setSent(true);
  };

  const toggleService = (v) => {
    setForm({
      ...form,
      services: form.services.includes(v) ? form.services.filter(s => s !== v) : [...form.services, v]
    });
  };

  if (sent) {
    return (
      <section id="contact" className="contact">
        <div className="shell contact__sent reveal">
          <div className="eyebrow">[ Transmission received ]</div>
          <h2 className="display" style={{ fontSize: 'clamp(48px,7vw,96px)' }}>Thanks, {form.name.split(' ')[0]}.<br/><span style={{ color: 'var(--accent)' }}>We'll reply within 24h.</span></h2>
          <p style={{ color: 'var(--fg-dim)', maxWidth: '52ch' }}>NDAs signed same day. First audit delivered in under two weeks.</p>
        </div>
      </section>
    );
  }

  return (
    <section id="contact" className="contact">
      <div className="shell">
        <div className="section-head reveal">
          <div></div>
          <div>
            <h2 className="display">Tell us what<br/><span style={{ color: 'var(--fg-dim)' }}>you're afraid will break.</span></h2>
            <p>24-hour response. NDAs signed same day. First audit delivered in under two weeks.</p>
          </div>
        </div>

        <form className="contact__form reveal" onSubmit={submit} noValidate>
          <div className="contact__row">
            <Field label="Name" error={errors.name}>
              <input value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Your name" />
            </Field>
            <Field label="Email" error={errors.email}>
              <input value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="your.email@company.com" />
            </Field>
          </div>
          <Field label="Company" error={errors.company}>
            <input value={form.company} onChange={e => setForm({...form, company: e.target.value})} placeholder="Your company name" />
          </Field>
          <Field label="Budget">
            <div className="chips chips--center">
              {[['<5k','<$5K'],['5-20k','$5–20K'],['20-50k','$20–50K'],['50k+','$50K+'],['discuss',"Let's discuss"]].map(([v,l]) => (
                <button key={v} type="button" className={`chip ${form.budget===v?'is-on':''}`} onClick={() => setForm({...form, budget: v})}>{l}</button>
              ))}
            </div>
          </Field>
          <Field label="Services needed (select all that apply)">
            <div className="chips chips--center">
              {SERVICE_OPTIONS.map(([v,l]) => (
                <button key={v} type="button" className={`chip ${form.services.includes(v)?'is-on':''}`} onClick={() => toggleService(v)}>
                  <span style={{ marginRight: 6 }}>{form.services.includes(v) ? '☑' : '☐'}</span>{l}
                </button>
              ))}
            </div>
          </Field>
          <Field label="What keeps you up at night?" error={errors.message}>
            <textarea rows={5} value={form.message} onChange={e => setForm({...form, message: e.target.value})} placeholder="We ship every two weeks and rollbacks are killing us…" />
          </Field>
          <div className="contact__submit">
            <span className="mono" style={{ color: 'var(--fg-mute)' }}>// Encrypted in transit. Human reply within 24h.</span>
            <Magnetic><button type="submit" className="btn btn--accent">Start the conversation →</button></Magnetic>
          </div>
        </form>
      </div>
    </section>
  );
}

// ── AI Loop (Rescue & Recovery) ─────────────────────────────────────────────
const AILOOP_SYMPTOMS = [
  ['Your devs use AI to write and fix code', 'but nobody is checking whether the fixes actually work end-to-end before they hit production.'],
  ['A bug gets fixed. Two new ones appear.', 'You fix those. The first one comes back. The cycle has no exit.'],
  ['Your team is testing manually more than building', 'and still missing critical flows because nobody mapped them properly.'],
  ['The deadline is real. The pressure is real.', 'But the product is not ready — and you are not sure how far it is from ready.'],
  ['You have considered delaying the launch. Again.', 'But you cannot afford to.'],
];

const AILOOP_CARDS = [
  {
    title: 'Rapid audit',
    body: 'We assess your current product state and tell you exactly what is broken, what is at risk, and what is actually fine — in 48 hours.',
    svg: (<svg width="18" height="18" viewBox="0 0 14 14" fill="none"><rect x="1" y="1" width="12" height="12" rx="2" stroke="currentColor" strokeWidth="1.5"/><path d="M4 7l2 2 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>)
  },
  {
    title: 'Structured test plan',
    body: 'We map every critical user journey and build a repeatable test suite — so fixes are verified properly before they ship.',
    svg: (<svg width="18" height="18" viewBox="0 0 14 14" fill="none"><path d="M2 4h10M2 7h7M2 10h5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>)
  },
  {
    title: 'Timeline recovery',
    body: 'We work inside your existing sprint — not around it. Parallel QA so your team keeps building while we keep checking.',
    svg: (<svg width="18" height="18" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" strokeWidth="1.5"/><path d="M7 4v3l2 1.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>)
  },
  {
    title: 'Automation foundation',
    body: 'After the crisis is resolved, we leave you with automated regression tests so this never happens to you again.',
    svg: (<svg width="18" height="18" viewBox="0 0 14 14" fill="none"><path d="M3 11V6l4-4 4 4v5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><rect x="5" y="8" width="4" height="3" rx="0.5" stroke="currentColor" strokeWidth="1.2"/></svg>)
  },
];

const AILOOP_TRUST = ['10+ years in QA engineering', 'ISTQB certified', 'Upwork Top Rated Plus', '6,000+ hours delivered'];

function AILoop() {
  return (
    <section id="ai-loop" className="ailoop">
      <div className="shell">
        <div className="ailoop__frame reveal">
          <div className="ailoop__eyebrow mono">Rescue &amp; recovery</div>
          <h2 className="display ailoop__h">
            Your team is shipping code.<br/>
            <span className="ailoop__accent">Your product is still broken.</span>
          </h2>
          <p className="ailoop__lead">
            You hired good developers. You gave them AI tools. The code is coming out faster than ever — and so are the bugs. Each fix breaks something else. Your deadline is tomorrow. Your inbox has seven client escalations. You are running in circles, and you know it.
          </p>

          <div className="ailoop__symptoms">
            <div className="ailoop__symptoms-title mono">Sound familiar?</div>
            {AILOOP_SYMPTOMS.map(([lead, rest], i) => (
              <div key={i} className="ailoop__symptom">
                <span className="ailoop__dot" />
                <div className="ailoop__symptom-text">{lead} <span>{rest}</span></div>
              </div>
            ))}
          </div>

          <blockquote className="ailoop__quote">
            <span className="ailoop__quote-mark">“</span>AI writes the code in minutes. But AI does not know what your users actually do — or what breaks when they do it. <strong>That gap is exactly where products fall apart.</strong>
          </blockquote>

          <div className="ailoop__divider" />

          <div className="ailoop__solution-label mono">How we help</div>
          <h3 className="display ailoop__solution-h">
            We have been inside this loop before.<br/>
            <span style={{ color: 'var(--fg-dim)' }}>We know exactly how to break it.</span>
          </h3>
          <p className="ailoop__solution-p">
            We step in as your dedicated QA layer — mapping every critical user flow, building a structured test plan, and systematically validating what works and what does not. You get a clear picture of your product's actual state within days, not weeks. No guessing. No more flying blind into your release.
          </p>

          <div className="ailoop__grid">
            {AILOOP_CARDS.map((c, i) => (
              <article key={c.title} className="ailoop__card reveal" style={{ '--rd': `${i*60}ms` }}>
                <div className="ailoop__card-icon">{c.svg}</div>
                <div className="ailoop__card-title">{c.title}</div>
                <div className="ailoop__card-body">{c.body}</div>
              </article>
            ))}
          </div>

          <div className="ailoop__cta">
            <a href="#contact" className="btn btn--accent">Talk to us about your project ↗</a>
            <a href="#work" className="ailoop__ghost">See how we have done this before →</a>
          </div>

          <div className="ailoop__trust">
            {AILOOP_TRUST.map(t => (
              <div key={t} className="ailoop__trust-item">
                <span className="ailoop__check">
                  <svg width="9" height="9" viewBox="0 0 7 7" fill="none"><path d="M1 3.5l2 2 3-3" stroke="white" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </span>
                {t}
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Field({ label, error, children }) {
  return (
    <label className={`field ${error ? 'field--error' : ''}`}>
      <span className="field__label mono">{label}{error && <span className="field__err"> — {error}</span>}</span>
      {children}
    </label>
  );
}

// ── Footer ──────────────────────────────────────────────────────────────────
function Footer() {
  const bigRef = useRefS(null);
  const [hovered, setHovered] = useStateS(-1);
  useEffectS(() => {
    const el = bigRef.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = (e.clientX - cx) / r.width;
      const dy = (e.clientY - cy) / r.height;
      el.style.setProperty('--tx', `${dx * 14}px`);
      el.style.setProperty('--ty', `${dy * 10}px`);
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  const lines = ['Ship', 'without', 'flinching.'];
  return (
    <footer className="footer">
      <div className="shell">
        <div ref={bigRef} className="footer__big display">
          {lines.map((line, li) => (
            <div key={li} className="footer__big-line">
              {line.split('').map((ch, ci) => {
                const k = `${li}-${ci}`;
                return (
                  <span
                    key={k}
                    className={`footer__big-ch ${hovered === li ? 'is-hot' : ''}`}
                    onMouseEnter={() => setHovered(li)}
                    onMouseLeave={() => setHovered(-1)}
                    style={{ transitionDelay: `${ci * 20}ms` }}
                  >{ch}</span>
                );
              })}
            </div>
          ))}
        </div>
        <div className="footer__cols footer__cols--4">
          <div>
            <div className="eyebrow">// QA SONIC</div>
            <p style={{ color: 'var(--fg-dim)', maxWidth: '36ch' }}>A boutique quality engineering agency based in Islamabad, Pakistan. Working with startups and growth companies across North America, Europe, and the Middle East.</p>
          </div>
          <div>
            <div className="eyebrow">// Contact</div>
            <ul className="footer__list">
              <li><a href="mailto:hello@qasonic.com">hello@qasonic.com</a></li>
              <li>Islamabad, Pakistan</li>
              <li>GMT+5 · Flexible hours</li>
            </ul>
            <div className="eyebrow" style={{ marginTop: 24 }}>// Connect</div>
            <ul className="footer__list">
              <li><a href="#">LinkedIn ↗</a></li>
              <li><a href="#">GitHub ↗</a></li>
              <li><a href="#">Upwork Profile ↗</a></li>
            </ul>
          </div>
          <div>
            <div className="eyebrow">// Services</div>
            <ul className="footer__list">
              <li><a href="#services">Test Automation</a></li>
              <li><a href="#services">Payment Gateway Testing</a></li>
              <li><a href="#services">AI / LLM Testing</a></li>
              <li><a href="#services">Performance Engineering</a></li>
              <li><a href="#services">Mobile App Testing</a></li>
              <li><a href="#services">QA Consulting</a></li>
            </ul>
          </div>
          <div>
            <div className="eyebrow">// Company</div>
            <ul className="footer__list">
              <li><a href="#team">About</a></li>
              <li><a href="#process">Process</a></li>
              <li><a href="#team">Team</a></li>
              <li><a href="#work">Case Studies</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom mono">
          <span>© 2026 QA SONIC — Quality Engineering Agency.</span>
          <span>ISTQB Certified · Top Rated Plus on Upwork</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, MenuOverlay, LogoMarquee, Services, Process, Work, CaseDetail, Stats, Team, Testimonials, Contact, Footer, AILoop
});
