'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { validate, v, Errors } from '@/lib/validation';
import { capitalizeFirst } from '@/lib/format';
import { ThemeToggle } from '@/lib/theme';

const API = process.env.NEXT_PUBLIC_API_URL ?? '';

/* Locally vendored stock photography (public/landing) — no runtime CDN dependency. */

/* ================= Navbar (solid, sticky) ================= */
const NAV = [
  { href: '/features', label: 'Features' },
  { href: '/how-it-works', label: 'How it works' },
  { href: '/clients', label: 'Clients' },
  { href: '/reviews', label: 'Reviews' },
  { href: '/pricing', label: 'Pricing' },
  { href: '/faq', label: 'FAQ' },
];

export function Navbar({ overlay = false }: { overlay?: boolean }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    if (!overlay) return;
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [overlay]);
  const transparent = overlay && !scrolled && !open;
  return (
    <header className={`inset-x-0 top-0 z-40 transition ${overlay ? 'fixed' : 'sticky'} ${transparent ? 'border-b border-transparent' : 'shadow-sm border-b'}`}
      style={transparent ? undefined : { background: 'var(--surface)', borderColor: 'var(--line)' }}>
      <div className="max-w-6xl mx-auto px-4">
        <div className="flex items-center gap-3 h-16">
          <Link href="/" className={`font-bold text-lg tracking-tight ${transparent ? 'text-white' : ''}`} style={transparent ? undefined : { color: 'var(--ink)' }}>
            Qtrial
          </Link>
          <nav aria-label="Site" className="hidden lg:block ml-6">
            <ul className="flex gap-5">
              {NAV.map((n) => (
                <li key={n.href}>
                  <Link href={n.href} className={`text-sm font-medium ${transparent ? 'text-white/90 hover:text-white' : ''}`}>{n.label}</Link>
                </li>
              ))}
            </ul>
          </nav>
          <div className="ml-auto hidden sm:flex items-center gap-2">
            <ThemeToggle />
            <Link href="/login" className={`text-sm font-semibold px-3 py-2 ${transparent ? 'text-white' : ''}`}>Login</Link>
            <Link href="/pricing#estimate" className="btn-primary btn-sm !h-9">Request Quote</Link>
          </div>
          <button className="lg:hidden ml-auto btn-ghost btn-icon" onClick={() => setOpen(v => !v)}
            aria-expanded={open} aria-controls="mobile-nav" aria-label={open ? 'Close menu' : 'Open menu'}
            style={transparent ? { color: '#fff', borderColor: 'rgba(255,255,255,.4)' } : undefined}>
            {open ? '✕' : '☰'}
          </button>
        </div>
      </div>
      {open && (
        <nav id="mobile-nav" aria-label="Mobile" className="lg:hidden border-t px-4 pb-4"
          style={{ background: 'var(--surface)', borderColor: 'var(--line)' }}>
          <ul className="py-2 space-y-1">
            {NAV.map((n) => (
              <li key={n.href}><Link href={n.href} onClick={() => setOpen(false)} className="block px-3 py-2.5 rounded-xl text-sm font-medium">{n.label}</Link></li>
            ))}
            <li className="flex gap-2 pt-2 items-center">
              <Link href="/login" className="btn-ghost btn-sm flex-1">Login</Link>
              <Link href="/pricing#estimate" onClick={() => setOpen(false)} className="btn-primary btn-sm flex-1">Request Quote</Link>
              <ThemeToggle />
            </li>
          </ul>
        </nav>
      )}
    </header>
  );
}

/* ================= Hero (full-height carousel) ================= */
const SLIDES = [
  {
    img: '/landing/hero-1.jpg',
    alt: 'Quality scientist examining test tubes in a pharmaceutical laboratory',
    kicker: 'Built for pharmaceutical teams',
    title: 'Every deviation, CAPA and QC sample test — audit-ready.',
    sub: 'Qtrial unifies deviations, CAPAs, QC sample testing schedules and evidence in one compliance-grade workspace.',
  },
  {
    img: '/landing/hero-2.jpg',
    alt: 'Researcher operating a microscope during quality analysis',
    kicker: 'Never miss a due date',
    title: 'Escalations that climb themselves — in hours, not days.',
    sub: 'Critical deviations reach management in 12 hours. Reminders, push alerts and L1–L3 escalation run automatically.',
  },
  {
    img: '/landing/hero-3.jpg',
    alt: 'Laboratory glassware prepared for sample testing',
    kicker: 'Sample testing, end to end',
    title: 'From sample receipt to signed-off report.',
    sub: 'Testing windows, team assignments, recurring schedules, evidence uploads and expiry tracking — per organisation, fully isolated.',
  },
];

function useAutoPlay(count: number, ms: number, paused: boolean, setIndex: (i: number) => void) {
  const idx = useRef(0);
  useEffect(() => {
    if (paused) return;
    if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
    const t = setInterval(() => {
      idx.current = (idx.current + 1) % count;
      setIndex(idx.current);
    }, ms);
    return () => clearInterval(t);
  }, [count, ms, paused, setIndex]);
  return idx;
}

export function Hero() {
  const [i, setI] = useState(0);
  const [paused, setPaused] = useState(false);
  const idxRef = useAutoPlay(SLIDES.length, 6000, paused, (n) => setI(n));
  const go = useCallback((n: number) => {
    idxRef.current = (n + SLIDES.length) % SLIDES.length;
    setI(idxRef.current);
  }, [idxRef]);
  const s = SLIDES[i];
  return (
    <section aria-label="Introduction" className="relative min-h-[100svh] flex items-center overflow-hidden bg-[#0B1626]">
      {SLIDES.map((sl, n) => (
        <div key={sl.img} aria-hidden={n !== i} className={`absolute inset-0 transition-opacity duration-700 ${n === i ? 'opacity-100' : 'opacity-0'}`}>
          <Image src={sl.img} alt="" fill priority={n === 0} sizes="100vw" className="object-cover" />
        </div>
      ))}
      <div className="absolute inset-0" aria-hidden="true"
        style={{ background: 'linear-gradient(100deg, rgba(11,22,38,.92) 0%, rgba(11,22,38,.72) 45%, rgba(11,22,38,.35) 100%)' }} />
      <div className="relative w-full max-w-6xl mx-auto px-4 pt-32 pb-20 text-white"
        onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}
        onFocus={() => setPaused(true)} onBlur={() => setPaused(false)}>
        <div aria-live="off" aria-atomic="true" key={i} className="max-w-2xl">
          <p className="text-xs font-semibold uppercase tracking-[0.2em] text-[#E8F0F7]/80">{s.kicker}</p>
          <h1 className="mt-3 font-bold tracking-tight" style={{ fontSize: 'clamp(2.25rem, 5.5vw, 3.75rem)', lineHeight: 1.08 }}>{s.title}</h1>
          <p className="mt-4 max-w-xl text-white/85 text-lg">{s.sub}</p>
        </div>
        <div className="mt-8 flex flex-wrap gap-3">
          <Link href="/pricing#estimate" className="btn-light !h-12 !px-7 !text-base">Request Quote</Link>
          <Link href="/features" className="btn-ghost !h-12 !px-7 !text-base !bg-transparent !text-white !border-white/50 hover:!bg-white/10">Explore features</Link>
        </div>
        <div className="mt-10 flex items-center gap-3" role="group" aria-roledescription="carousel" aria-label="Product highlights">
          <button onClick={() => go(i - 1)} aria-label="Previous slide" className="btn-light btn-icon !rounded-full !h-11 !w-11">‹</button>
          <div className="flex gap-2">
            {SLIDES.map((sl, n) => (
              <button key={n} onClick={() => go(n)} aria-label={`Go to slide ${n + 1}: ${sl.kicker}`}
                aria-current={n === i ? 'true' : undefined}
                className={`h-1.5 rounded-full transition-all ${n === i ? 'w-8 bg-white' : 'w-3 bg-white/40 hover:bg-white/70'}`} />
            ))}
          </div>
          <button onClick={() => go(i + 1)} aria-label="Next slide" className="btn-light btn-icon !rounded-full !h-11 !w-11">›</button>
        </div>
      </div>
    </section>
  );
}

/* ================= Client marquee ================= */
const CLIENTS = ['NovaGen Labs', 'CurePath Pharma', 'Veritas Biologics', 'MediCore Formulations', 'Axon Life Sciences', 'PureDose Injectables', 'Helix Generics', 'SteriLab Sciences'];

export function Clients() {
  return (
    <section id="clients" aria-labelledby="clients-h" className="py-14" style={{ background: 'var(--surface)' }}>
      <div className="max-w-6xl mx-auto px-4">
        <h2 id="clients-h" className="text-center text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>
          Trusted by quality-driven pharmaceutical teams
        </h2>
        <div className="marquee overflow-hidden mt-6 [mask-image:linear-gradient(90deg,transparent,#000_10%,#000_90%,transparent)]" role="region" aria-label="Client logos">
          <div className="marquee-track gap-10 pr-10" aria-hidden="false">
            {[...CLIENTS, ...CLIENTS].map((c, n) => (
              <span key={n} aria-hidden={n >= CLIENTS.length}
                className="text-lg font-bold tracking-tight whitespace-nowrap opacity-70" style={{ color: 'var(--ink)' }}>{c}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================= Features ================= */
const FEATURES = [
  { t: 'Deviation → CAPA hierarchy', d: 'Auto-numbered DEV-2026-000001 deviations with -S01 CAPAs, assignments, and roll-up completion.' },
  { t: 'Sample testing lifecycle', d: 'Receipt → testing window → team schedules → evidence uploads → expiry tracking.' },
  { t: 'Hour-level escalations', d: 'Critical deviations reach management in hours. L1–L3 routing per priority, per organisation.' },
  { t: 'AI escalation-risk watch', d: 'Transparent risk scoring with explained signals and urgency-tiered alerts to assignees.' },
  { t: 'Recurring work', d: 'Repeating testing schedules and spawn-on-completion recurring actions with series history.' },
  { t: 'Evidence & audit trail', d: 'Malware-scanned uploads, activity timelines, and immutable audit logs for inspections.' },
  { t: 'SaaS isolation & limits', d: 'Per-organisation data, SMTP, holidays, SLA policies, and plan limits with white-label branding.' },
  { t: 'Reports & integrations', d: 'Excel/PDF/CSV exports, SLA breach reports, push notifications, and a Flutter-ready API.' },
  { t: 'Bulk onboarding', d: 'CSV/XLSX import for users, samples, and actions with per-row error reports.' },
];

export function Features() {
  return (
    <section id="features" aria-labelledby="features-h" className="py-20 scroll-mt-16">
      <div className="max-w-6xl mx-auto px-4">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Platform</p>
        <h2 id="features-h" className="page-title mt-2">Everything a pharma QA team needs</h2>
        <p className="hint mt-2 max-w-2xl">One workspace replacing spreadsheets, email threads, and shared drives — with the traceability auditors expect.</p>
        <ul className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-8">
          {FEATURES.map((f) => (
            <li key={f.t} className="card">
              <p className="font-semibold">{f.t}</p>
              <p className="hint mt-1">{f.d}</p>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ================= How it works ================= */
const STEPS = [
  { n: '1', t: 'Register your organisation', d: 'Super-admin creates your tenant with user, deviation and storage limits — or start a pilot in minutes.' },
  { n: '2', t: 'Import masters & teams', d: 'Bulk-import users, departments, categories and testing teams from CSV/Excel templates.' },
  { n: '3', t: 'Run deviations & testing', d: 'Stakeholders raise deviations, assign CAPAs, schedule testing. The engine reminds, escalates and scores risk.' },
  { n: '4', t: 'Prove compliance', d: 'Export SLA reports, pull audit logs, subscribe via iCal — inspection-ready at any moment.' },
];

export function HowItWorks() {
  return (
    <section id="how" aria-labelledby="how-h" className="py-20 scroll-mt-16" style={{ background: 'var(--surface)' }}>
      <div className="max-w-6xl mx-auto px-4 grid lg:grid-cols-2 gap-10 items-center">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>How it works</p>
          <h2 id="how-h" className="page-title mt-2">Live in four steps</h2>
          <ol className="mt-6 space-y-4">
            {STEPS.map((s) => (
              <li key={s.n} className="flex gap-3">
                <span aria-hidden="true" className="flex-none inline-flex h-8 w-8 items-center justify-center rounded-full text-sm font-bold"
                  style={{ background: 'var(--ink)', color: 'var(--bg)' }}>{s.n}</span>
                <div><p className="font-semibold text-sm">{s.t}</p><p className="hint mt-0.5">{s.d}</p></div>
              </li>
            ))}
          </ol>
          <Link href="/contact" className="btn-primary mt-6">Request a Customised Proposal</Link>
        </div>
        <div className="relative rounded overflow-hidden min-h-[320px] hidden lg:block">
          <Image src="/landing/how-1.jpg" alt="Quality-checked pharmaceutical products ready for dispatch" fill sizes="(max-width:1024px) 100vw, 50vw" className="object-cover" />
        </div>
      </div>
    </section>
  );
}

/* ================= Reviews carousel ================= */
const REVIEWS = [
  { q: 'Audit preparation went from three weeks of spreadsheet hunting to a single export. The activity timeline alone paid for the switch.', n: 'Quality Head', r: 'Generics manufacturer', i: 'QH' },
  { q: 'Critical deviations now reach my inbox in hours instead of sitting in a queue. The escalation levels match how our plant actually works.', n: 'Plant Manager', r: 'Formulations unit', i: 'PM' },
  { q: 'Sample expiry tracking caught three at-risk stability batches in our first month. Evidence uploads keep everything inspection-ready.', n: 'QC Lead', r: 'Injectables facility', i: 'QC' },
  { q: 'White-labelling meant each of our sites sees its own brand. Onboarding 200+ users took an afternoon with the CSV import.', n: 'IT Administrator', r: 'Multi-site pharma group', i: 'IT' },
];

export function Reviews() {
  const [i, setI] = useState(0);
  const go = (n: number) => setI((n + REVIEWS.length) % REVIEWS.length);
  const r = REVIEWS[i];
  return (
    <section id="reviews" aria-labelledby="reviews-h" className="py-20 scroll-mt-16">
      <div className="max-w-3xl mx-auto px-4 text-center">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Reviews</p>
        <h2 id="reviews-h" className="page-title mt-2">What quality teams say</h2>
        <div className="card mt-8 text-center" role="region" aria-roledescription="carousel" aria-label="Customer reviews">
          <div aria-live="polite" key={i}>
            <p className="text-lg leading-relaxed">“{r.q}”</p>
            <div className="mt-4 flex flex-col items-center gap-2">
              <span aria-hidden="true" className="inline-flex h-11 w-11 items-center justify-center rounded-full text-sm font-bold"
                style={{ background: 'var(--ink)', color: 'var(--bg)' }}>{r.i}</span>
              <div><p className="text-sm font-semibold">{r.n}</p><p className="hint">{r.r}</p></div>
            </div>
          </div>
          <div className="mt-6 flex items-center justify-between">
            <button onClick={() => go(i - 1)} aria-label="Previous review" className="btn-ghost btn-icon">‹</button>
            <div className="flex gap-2" role="tablist" aria-label="Choose review">
              {REVIEWS.map((_, n) => (
                <button key={n} role="tab" aria-selected={n === i} aria-label={`Review ${n + 1}`}
                  onClick={() => go(n)} className={`h-2 rounded-full transition-all ${n === i ? 'w-6' : 'w-2 opacity-40'}`}
                  style={{ background: 'var(--ink)' }} />
              ))}
            </div>
            <button onClick={() => go(i + 1)} aria-label="Next review" className="btn-ghost btn-icon">›</button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================= Pricing ================= */
const PLANS = [
  { n: 'Starter', d: 'For single-plant teams getting audit-ready.', f: ['Up to 5 stakeholders', 'Up to 25 employees', '500 deviations / year', 'Email + in-app notifications', 'Community support'], hot: false },
  { n: 'Growth', d: 'For multi-department QA with sample testing.', f: ['Up to 15 stakeholders', 'Up to 150 employees', '5,000 deviations / year', 'Push, escalation & AI risk alerts', 'White-label logo + login', 'Priority support (2h response)'], hot: true },
  { n: 'Enterprise', d: 'For groups, validations and integrations.', f: ['Unlimited users & deviations', 'Custom SMTP + SSO assistance', 'Dedicated success manager', 'Audit & migration support', 'Uptime SLA'], hot: false },
];

export function Pricing() {
  return (
    <section id="pricing" aria-labelledby="pricing-h" className="py-16 scroll-mt-16">
      <div className="max-w-6xl mx-auto px-4">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Packages</p>
        <h2 id="pricing-h" className="page-title mt-2">Plans that scale with your plant</h2>
        <p className="hint mt-2 max-w-2xl">Pick the package that fits your team — then get an instant estimate below or talk to us for a tailored proposal.</p>
        <div className="grid md:grid-cols-3 gap-4 mt-8">
          {PLANS.map((p) => (
            <div key={p.n} className="card flex flex-col" style={p.hot ? { borderColor: 'var(--accent)', borderWidth: 2 } : undefined}>
              <div className="flex items-center gap-2">
                <h3 className="font-bold">{p.n}</h3>
                {p.hot && <span className="badge" style={{ background: 'var(--ink)', color: 'var(--bg)' }}>Most popular</span>}
              </div>
              <p className="hint mt-1">{p.d}</p>
              <ul className="mt-4 space-y-2 text-sm flex-1">
                {p.f.map((f) => <li key={f} className="flex gap-2"><span aria-hidden="true">✓</span>{f}</li>)}
              </ul>
              <a href="/contact" className={p.hot ? 'btn-primary w-full mt-5' : 'btn-ghost w-full mt-5'}>Talk to Us</a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================= Estimate calculator ================= */
const PLAN_BASE: Record<string, number> = { Starter: 290, Growth: 790 };
const PLAN_CAPS: Record<string, { st: number; emp: number; tik: number }> = {
  Starter: { st: 5, emp: 25, tik: 500 },
  Growth: { st: 15, emp: 150, tik: 5000 },
};

export function EstimateCalculator() {
  const [st, setSt] = useState('5');
  const [emp, setEmp] = useState('25');
  const [tik, setTik] = useState('500');
  const [whiteLabel, setWhiteLabel] = useState(false);
  const [successMgr, setSuccessMgr] = useState(false);
  const [err, setErr] = useState('');

  const nums = { st: Number(st), emp: Number(emp), tik: Number(tik) };
  const valid = Number.isInteger(nums.st) && nums.st >= 0 && Number.isInteger(nums.emp) && nums.emp >= 0 && Number.isInteger(nums.tik) && nums.tik >= 0;
  const fits = (p: string) => nums.st <= PLAN_CAPS[p].st && nums.emp <= PLAN_CAPS[p].emp && nums.tik <= PLAN_CAPS[p].tik;
  const plan = !valid ? null : fits('Starter') ? 'Starter' : fits('Growth') ? 'Growth' : 'Enterprise';
  const addons = (whiteLabel ? 300 : 0) + (successMgr ? 900 : 0);
  const total = plan === null || plan === 'Enterprise' ? null : PLAN_BASE[plan] + addons;
  const proposalHref = plan
    ? `/contact?plan=${plan}&stakeholders=${nums.st}&employees=${nums.emp}&tickets=${nums.tik}${whiteLabel ? '&whitelabel=1' : ''}${successMgr ? '&success=1' : ''}${total != null ? `&estimate=${total}` : ''}`
    : '/contact';

  return (
    <section id="estimate" aria-labelledby="estimate-h" className="py-16 scroll-mt-16" style={{ background: 'var(--surface)' }}>
      <div className="max-w-6xl mx-auto px-4 grid lg:grid-cols-2 gap-8 items-start">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Request Quote</p>
          <h2 id="estimate-h" className="page-title mt-2">Estimate your annual plan in seconds</h2>
          <p className="hint mt-2">Tell us your team size and deviation volume — we recommend the smallest package that fits, plus optional add-ons.</p>
          <div className="card mt-6 space-y-3">
            <div className="grid sm:grid-cols-3 gap-3">
              <div>
                <label className="label" htmlFor="est-st">Stakeholders</label>
                <input id="est-st" type="number" min={0} className="input" value={st} onChange={(e) => setSt(e.target.value)} />
              </div>
              <div>
                <label className="label" htmlFor="est-emp">Employees</label>
                <input id="est-emp" type="number" min={0} className="input" value={emp} onChange={(e) => setEmp(e.target.value)} />
              </div>
              <div>
                <label className="label" htmlFor="est-tik">Deviations / year</label>
                <input id="est-tik" type="number" min={0} className="input" value={tik} onChange={(e) => setTik(e.target.value)} />
              </div>
            </div>
            <label className="text-sm flex gap-2 items-center">
              <input type="checkbox" checked={whiteLabel} onChange={(e) => setWhiteLabel(e.target.checked)} /> White-label branding (+$300/yr)
            </label>
            <label className="text-sm flex gap-2 items-center">
              <input type="checkbox" checked={successMgr} onChange={(e) => setSuccessMgr(e.target.checked)} /> Dedicated success manager (+$900/yr)
            </label>
            {!valid && <p role="alert" className="field-error">Enter whole numbers 0 or above.</p>}
          </div>
        </div>
        <div className="card lg:sticky lg:top-24" aria-live="polite">
          <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Your estimate</p>
          {!valid ? (
            <p className="hint mt-2">Enter valid numbers to see your recommendation.</p>
          ) : plan === 'Enterprise' ? (
            <div className="mt-2">
              <p className="text-2xl font-bold">Custom</p>
              <p className="hint mt-1">Your scale needs an Enterprise mix — talk to us and we will tailor limits, SSO and support.</p>
            </div>
          ) : (
            <div className="mt-2">
              <p className="text-2xl font-bold">{plan} · ${total?.toLocaleString()}/yr</p>
              <ul className="hint mt-2 space-y-1">
                <li>Base {plan} plan — ${PLAN_BASE[plan as string].toLocaleString()}/yr</li>
                {whiteLabel && <li>White-label branding — $300/yr</li>}
                {successMgr && <li>Dedicated success manager — $900/yr</li>}
              </ul>
            </div>
          )}
          <a href={proposalHref} className="btn-primary w-full mt-4">Request a Customised Proposal</a>
          <p className="hint mt-2 text-center">Prefills the contact form — we revert within 2 business hours.</p>
        </div>
      </div>
    </section>
  );
}

/* ================= FAQ ================= */
const FAQS = [
  { q: 'Is our data isolated from other organisations?', a: 'Yes. Every record carries an organisation boundary enforced in the database layer — departments, categories, deviations, samples, SMTP and holidays are all per-organisation, with plan limits you control.' },
  { q: 'Can we use our own logo and login page?', a: 'Yes. Each organisation gets white-label branding: logo, app name and a dedicated login link (/login?org=your-slug) for auth and dashboard.' },
  { q: 'How do escalations work?', a: 'Level 1 fires on the due date; Levels 2–3 use per-priority hour thresholds (Critical reaches management in hours). Each level notifies once, with in-app, email and push delivery.' },
  { q: 'What is the AI risk watch?', a: 'A transparent scoring model (priority, SLA burn, staleness, progress, workload) flags at-risk deviations hourly with explained urgency alerts — no black box, every score ships its reasons.' },
  { q: 'Can we migrate from spreadsheets?', a: 'Yes — CSV/Excel bulk import for users, samples and actions with per-row error reports, plus one-click exports back out at any time. Your data is never locked in.' },
  { q: 'Do you offer mobile apps?', a: 'The backend API already powers the web app and is Flutter-ready with device-token push support, so a native app can reuse every workflow unchanged.' },
];

export function Faq() {
  return (
    <section id="faq" aria-labelledby="faq-h" className="py-20 scroll-mt-16">
      <div className="max-w-3xl mx-auto px-4">
        <h2 id="faq-h" className="page-title">Frequently asked questions</h2>
        <div className="mt-6 space-y-2">
          {FAQS.map((f) => (
            <details key={f.q} className="card !py-3 group">
              <summary className="font-semibold text-sm cursor-pointer list-none flex justify-between gap-2">
                {f.q}<span aria-hidden="true" className="group-open:rotate-45 transition-transform">+</span>
              </summary>
              <p className="hint mt-2">{f.a}</p>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================= Consultation + contact ================= */
export function Consult() {
  const [form, setForm] = useState({ name: '', organisation: '', email: '', phone: '', message: '' });
  const [state, setState] = useState<'idle' | 'busy' | 'done' | 'error'>('idle');
  const [msg, setMsg] = useState('');
  const [errs, setErrs] = useState<Errors>({});
  const [prefilled, setPrefilled] = useState(false);
  const set = (k: string, v: string) => setForm((f) => ({ ...f, [k]: v }));
  // Prefill from the estimate calculator (?plan=&stakeholders=&…&estimate=)
  useEffect(() => {
    const q = new URLSearchParams(window.location.search);
    const plan = q.get('plan');
    if (!plan || prefilled) return;
    const bits = [
      `Recommended package: ${plan}`,
      q.get('stakeholders') != null && `Stakeholders: ${q.get('stakeholders')}`,
      q.get('employees') != null && `Employees: ${q.get('employees')}`,
      q.get('tickets') != null && `Deviations/year: ${q.get('tickets')}`,
      q.get('whitelabel') === '1' && 'Add-on: white-label branding',
      q.get('success') === '1' && 'Add-on: dedicated success manager',
      q.get('estimate') != null && `Indicative estimate: $${Number(q.get('estimate')).toLocaleString()}/yr`,
    ].filter(Boolean).join('\n');
    setForm((f) => ({ ...f, message: f.message || `Hi, please send us a customised proposal based on this estimate:\n${bits}\n` }));
    setPrefilled(true);
  }, [prefilled]);
  return (
    <section id="consult" aria-labelledby="consult-h" className="py-20 scroll-mt-16" style={{ background: 'var(--surface)' }}>
      <div className="max-w-6xl mx-auto px-4 grid lg:grid-cols-2 gap-10">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Consultation</p>
          <h2 id="consult-h" className="page-title mt-2">Talk to a compliance workflow specialist</h2>
          <p className="hint mt-2">Tell us about your plants, audits and team size. <strong>We revert within 2 business hours</strong> — usually much faster.</p>
          <ul className="mt-6 space-y-3 text-sm">
            <li className="flex gap-2"><span aria-hidden="true">✉</span><a className="link" href="mailto:hello@qtrial.app">hello@qtrial.app</a></li>
            <li className="flex gap-2"><span aria-hidden="true">◷</span>Mon–Fri, 9:00–18:00 · Serving pharmaceutical teams worldwide</li>
            <li className="flex gap-2"><span aria-hidden="true">✓</span>Free 30-minute workflow audit with every consultation</li>
          </ul>
          <div className="relative rounded overflow-hidden mt-6 min-h-[220px] hidden lg:block">
            <Image src="/landing/consult-1.jpg" alt="Quality-assured medicines ready for patients" fill sizes="(max-width:1024px) 100vw, 50vw" className="object-cover" />
          </div>
        </div>
        <form className="card space-y-3 self-start" aria-label="Consultation request form" noValidate onSubmit={async (e) => {
          e.preventDefault();
          const fe = validate({
            name: () => v.minLen(form.name, 2, 'Name'),
            organisation: () => v.minLen(form.organisation, 2, 'Organisation'),
            email: () => v.email(form.email, 'Work email'),
            phone: () => form.phone.trim() && !/^[+()\-.\s\d]{6,40}$/.test(form.phone.trim()) ? 'Enter a valid phone number' : null,
            message: () => v.minLen(form.message, 10, 'Message'),
          });
          setErrs(fe);
          if (Object.keys(fe).length) return;
          setState('busy'); setMsg('');
          try {
            const r = await fetch(`${API}/api/v1/consultations`, {
              method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form),
            });
            const body = await r.json().catch(() => ({}));
            if (!r.ok) throw new Error(body.error || 'Submission failed');
            setState('done'); setMsg(body.message || 'Thanks — our team reverts within 2 business hours.');
            setForm({ name: '', organisation: '', email: '', phone: '', message: '' });
          } catch (ex: any) { setState('error'); setMsg(ex.message); }
        }}>
          <div className="grid sm:grid-cols-2 gap-3">
            <div><label className="label" htmlFor="c-name">Your name *</label>
              <input id="c-name" className="input" value={form.name} onChange={(e) => set('name', capitalizeFirst(e.target.value))} autoComplete="name" aria-invalid={!!errs.name} />
              {errs.name && <p role="alert" className="field-error">{errs.name}</p>}</div>
            <div><label className="label" htmlFor="c-org">Organisation *</label>
              <input id="c-org" className="input" value={form.organisation} onChange={(e) => set('organisation', capitalizeFirst(e.target.value))} autoComplete="organization" aria-invalid={!!errs.organisation} />
              {errs.organisation && <p role="alert" className="field-error">{errs.organisation}</p>}</div>
          </div>
          <div className="grid sm:grid-cols-2 gap-3">
            <div><label className="label" htmlFor="c-email">Work email *</label>
              <input id="c-email" type="email" className="input" value={form.email} onChange={(e) => set('email', e.target.value)} autoComplete="email" aria-invalid={!!errs.email} />
              {errs.email && <p role="alert" className="field-error">{errs.email}</p>}</div>
            <div><label className="label" htmlFor="c-phone">Phone</label>
              <input id="c-phone" type="tel" className="input" value={form.phone} onChange={(e) => set('phone', e.target.value)} autoComplete="tel" aria-invalid={!!errs.phone} />
              {errs.phone && <p role="alert" className="field-error">{errs.phone}</p>}</div>
          </div>
          <div><label className="label" htmlFor="c-msg">What are you trying to solve? *</label>
            <textarea id="c-msg" className="input" rows={4} value={form.message} onChange={(e) => set('message', capitalizeFirst(e.target.value))} aria-invalid={!!errs.message} />
            {errs.message && <p role="alert" className="field-error">{errs.message}</p>}</div>
          {state === 'done' && <p role="status" className="alert-ok">{msg}</p>}
          {state === 'error' && <p role="alert" className="alert-error">{msg}</p>}
          <button className="btn-primary w-full" disabled={state === 'busy'}>
            {state === 'busy' ? 'Sending…' : 'Request consultation'}
          </button>
          <p className="hint text-center">No spam, no lock-in. Your details stay with our sales team.</p>
        </form>
      </div>
    </section>
  );
}

/* ================= Legal page shell ================= */
export function LegalShell({ title, updated, children }: { title: string; updated: string; children: React.ReactNode }) {
  return (
    <div>
      <a href="#legal-main" className="skip-link">Skip to content</a>
      <Navbar />
      <main id="legal-main" tabIndex={-1} className="outline-none" style={{ background: 'var(--bg)' }}>
        <div className="max-w-3xl mx-auto px-4 pt-28 pb-16">
          <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Qtrial · Legal</p>
          <h1 className="page-title mt-2">{title}</h1>
          <p className="hint mt-1">Last updated: {updated}</p>
          <div className="card mt-6 space-y-4 text-sm leading-relaxed">{children}</div>
          <p className="mt-6 text-sm"><Link href="/" className="link">← Back to home</Link></p>
        </div>
      </main>
      <Footer />
    </div>
  );
}

const STATS = [
  { v: '100%', l: 'Deviation traceability, creation to closure' },
  { v: '12h', l: 'Critical deviations reach management' },
  { v: '2h', l: 'First response on consultations' },
  { v: '9+', l: 'Modules, one workspace' },
];

export function StatsBand() {
  return (
    <section aria-label="Platform highlights" className="py-12 border-y" style={{ background: 'var(--surface)', borderColor: 'var(--line)' }}>
      <dl className="max-w-6xl mx-auto px-4 grid grid-cols-2 lg:grid-cols-4 gap-6">
        {STATS.map((s) => (
          <div key={s.l} className="flex flex-col">
            <dd className="font-bold tracking-tight order-1" style={{ fontSize: 'clamp(2rem, 4vw, 3rem)', lineHeight: 1 }}>{s.v}</dd>
            <dt className="hint mt-2 order-2">{s.l}</dt>
          </div>
        ))}
      </dl>
    </section>
  );
}

/* ================= Who we serve (image cards) ================= */
const SEGMENTS = [
  { img: '/landing/how-1.jpg', alt: 'Finished pharmaceutical products ready for quality dispatch', t: 'Generics manufacturers', d: 'High-volume deviation and CAPA tracking across multiple plants.' },
  { img: '/landing/seg-engineer.jpg', alt: 'Engineer reviewing validation data on a laptop in a clean facility', t: 'Injectables & sterile facilities', d: 'Environmental monitoring schedules and sterility test evidence.' },
  { img: '/landing/seg-care.jpg', alt: 'Analyst documenting sample testing results', t: 'Biologics & R&D', d: 'Stability programs and recurring analytical schedules with history.' },
  { img: '/landing/consult-1.jpg', alt: 'Quality-assured medicines ready for patients', t: 'Multi-site groups', d: 'White-label logins per site with consolidated SLA reporting.' },
];

export function Segments() {
  return (
    <section aria-labelledby="segments-h" className="py-16">
      <div className="max-w-6xl mx-auto px-4">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Who we serve</p>
        <h2 id="segments-h" className="page-title mt-2">Teams we empower</h2>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6">
          {SEGMENTS.map((s) => (
            <article key={s.t} className="card !p-0 overflow-hidden flex flex-col">
              <div className="relative h-40">
                <Image src={s.img} alt={s.alt} fill sizes="(max-width:640px) 100vw, (max-width:1024px) 50vw, 25vw" className="object-cover" />
              </div>
              <div className="p-4 flex flex-col flex-1">
                <h3 className="font-semibold text-sm">{s.t}</h3>
                <p className="hint mt-1 flex-1">{s.d}</p>
                <Link href="/clients" className="link text-sm mt-2">Explore →</Link>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================= Why Qtrial (2-col value list) ================= */
const WHY = [
  { t: 'Skilled workflows, zero chaos', d: 'Structured deviations with owners, due dates and proof replace spreadsheet hunting and email threads.' },
  { t: 'Escalations that climb themselves', d: 'Critical deviations reach management in hours through L1–L3 routing tuned per priority.' },
  { t: 'Sample testing, end to end', d: 'Testing windows, team assignments, recurring schedules and expiry control in one lifecycle.' },
  { t: 'Evidence you can defend', d: 'Malware-scanned uploads, activity timelines and immutable audit logs for every inspection.' },
  { t: 'AI risk watch', d: 'Transparent escalation-risk scoring with explained signals and urgency-tiered alerts.' },
  { t: 'Partnership, not lock-in', d: 'White-label branding, bulk import/export, iCal feeds and a Flutter-ready API keep you in control.' },
];

export function WhyQtrial() {
  return (
    <section aria-labelledby="why-h" className="py-16" style={{ background: 'var(--surface)' }}>
      <div className="max-w-6xl mx-auto px-4">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Why Qtrial</p>
        <h2 id="why-h" className="page-title mt-2">Excellence you can depend on</h2>
        <p className="hint mt-2 max-w-2xl">Compliance-grade quality management through disciplined workflows, dependable automation and transparent reporting.</p>
        <ul className="grid md:grid-cols-2 gap-x-10 gap-y-6 mt-8">
          {WHY.map((w) => (
            <li key={w.t} className="flex gap-3">
              <span aria-hidden="true" className="flex-none inline-flex h-7 w-7 items-center justify-center rounded-full text-sm font-bold"
                style={{ background: 'var(--ink)', color: 'var(--bg)' }}>✓</span>
              <div><h3 className="font-semibold text-sm">{w.t}</h3><p className="hint mt-0.5">{w.d}</p></div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ================= Service cards ================= */
const SERVICES = [
  { img: '/landing/hero-2.jpg', alt: 'Microscope analysis driving deviation decisions', t: 'Deviation management', d: 'Deviation → CAPA hierarchy, assignments, reminders and hour-level escalations.', href: '/features' },
  { img: '/landing/hero-3.jpg', alt: 'Prepared laboratory glassware for testing', t: 'Sample testing', d: 'Windows, teams, recurring schedules, evidence uploads and expiry alerts.', href: '/features' },
  { img: '/landing/seg-scope.jpg', alt: 'Detailed analytical review for compliance reporting', t: 'Reports & compliance', d: 'SLA breach reports, audit logs, bulk exports and white-label branding.', href: '/features' },
];

export function ServicesCards() {
  return (
    <section aria-labelledby="services-h" className="py-16">
      <div className="max-w-6xl mx-auto px-4">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>What we do</p>
        <h2 id="services-h" className="page-title mt-2">Comprehensive quality solutions</h2>
        <div className="grid md:grid-cols-3 gap-4 mt-6">
          {SERVICES.map((s) => (
            <article key={s.t} className="card !p-0 overflow-hidden flex flex-col">
              <div className="relative h-48">
                <Image src={s.img} alt={s.alt} fill sizes="(max-width:768px) 100vw, 33vw" className="object-cover" />
              </div>
              <div className="p-5 flex flex-col flex-1">
                <h3 className="font-semibold">{s.t}</h3>
                <p className="hint mt-1 flex-1">{s.d}</p>
                <Link href={s.href} className="link text-sm mt-3">Learn more →</Link>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================= Commitment steps ================= */
const PROMISE = [
  { n: '01', t: 'Rapid response', d: 'Consultations answered within 2 business hours; critical deviations escalate in hours, automatically.' },
  { n: '02', t: 'Clear action', d: 'Every signal assigns an owner, a due date and a plan — nothing sits in a queue.' },
  { n: '03', t: 'Fast resolution', d: 'Recurring work, evidence capture and audit exports close the loop with proof.' },
];

export function Commitment() {
  return (
    <section aria-labelledby="promise-h" className="py-16" style={{ background: 'var(--surface)' }}>
      <div className="max-w-6xl mx-auto px-4">
        <p className="text-xs font-semibold uppercase tracking-[0.2em]" style={{ color: 'var(--muted)' }}>Our commitment</p>
        <h2 id="promise-h" className="page-title mt-2">The Qtrial care promise</h2>
        <p className="hint mt-2 max-w-2xl">Your compliance is our priority. If an issue arises, we respond quickly and resolve it with care.</p>
        <ol className="grid md:grid-cols-3 gap-4 mt-8">
          {PROMISE.map((p) => (
            <li key={p.n} className="card">
              <p aria-hidden="true" className="text-3xl font-bold" style={{ color: 'var(--line)' }}>{p.n}</p>
              <h3 className="font-semibold mt-2">{p.t}</h3>
              <p className="hint mt-1">{p.d}</p>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* ================= Inner page hero + CTA band ================= */export function PageHero({ kicker, title, sub }: { kicker: string; title: string; sub: string }) {
  return (
    <section className="text-white" style={{ background: '#0B1626' }}>
      <div className="max-w-6xl mx-auto px-4 pt-28 pb-14">
        <p className="text-xs font-semibold uppercase tracking-[0.2em] text-white/70">{kicker}</p>
        <h1 className="mt-3 font-bold tracking-tight" style={{ fontSize: 'clamp(1.75rem, 4vw, 2.75rem)', lineHeight: 1.15 }}>{title}</h1>
        <p className="mt-3 max-w-2xl text-white/85">{sub}</p>
      </div>
    </section>
  );
}

export function CtaBand() {
  return (
    <section aria-label="Get started" className="py-16">
      <div className="max-w-6xl mx-auto px-4">
        <div className="card !p-8 text-center" style={{ background: '#0B1626', borderColor: '#0B1626' }}>
          <h2 className="font-bold text-white" style={{ fontSize: 'clamp(1.4rem, 3vw, 2rem)' }}>Ready to modernize your QA workflow?</h2>
          <p className="text-white/75 text-sm mt-2">Get an instant estimate, or ask for a proposal tailored to your plants.</p>
          <div className="mt-5 flex flex-wrap justify-center gap-3">
            <a href="/pricing#estimate" className="btn-light !h-11 !px-6">Request Quote</a>
            <a href="/contact" className="btn-ghost !h-11 !px-6 !bg-transparent !text-white !border-white/50 hover:!bg-white/10">Request a Customised Proposal</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================= Footer ================= */
export function Footer() {
  return (
    <footer className="text-white" style={{ background: '#0B1626' }}>
      <div className="max-w-6xl mx-auto px-4 py-12 grid sm:grid-cols-2 lg:grid-cols-5 gap-8">
        <div>
          <p className="font-bold text-lg">Qtrial</p>
          <p className="text-sm text-white/70 mt-2">Audit-ready action and sample-testing management for pharmaceutical organisations.</p>
        </div>
        <nav aria-label="Product">
          <p className="text-xs font-semibold uppercase tracking-wider text-white/60">Product</p>
          <ul className="mt-3 space-y-2 text-sm">
            <li><Link className="text-white/85 hover:text-white" href="/features">Features</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/pricing">Pricing</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/faq">FAQ</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/login">Login</Link></li>
          </ul>
        </nav>
        <nav aria-label="Company">
          <p className="text-xs font-semibold uppercase tracking-wider text-white/60">Company</p>
          <ul className="mt-3 space-y-2 text-sm">
            <li><Link className="text-white/85 hover:text-white" href="/how-it-works">How it works</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/clients">Clients</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/reviews">Reviews</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/contact">Contact</Link></li>
          </ul>
        </nav>
        <nav aria-label="Legal">
          <p className="text-xs font-semibold uppercase tracking-wider text-white/60">Legal</p>
          <ul className="mt-3 space-y-2 text-sm">
            <li><Link className="text-white/85 hover:text-white" href="/privacy">Privacy policy</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/terms">Terms &amp; conditions</Link></li>
            <li><Link className="text-white/85 hover:text-white" href="/gdpr">GDPR compliance</Link></li>
          </ul>
        </nav>
        <div>
          <p className="text-xs font-semibold uppercase tracking-wider text-white/60">Contact Info</p>
          <ul className="mt-3 space-y-2 text-sm text-white/85">
            <li><a className="hover:text-white" href="mailto:hello@qtrial.app">hello@qtrial.app</a></li>
            <li>Reverts within 2 business hours</li>
            <li>Mon–Fri, 9:00–18:00</li>
          </ul>
        </div>
      </div>
      <div className="border-t border-white/10">
        <p className="max-w-6xl mx-auto px-4 py-4 text-xs text-white/60">© {new Date().getFullYear()} Qtrial by Soulitum Labs. All rights reserved.</p>
      </div>
    </footer>
  );
}
