// Proof.jsx — S6: Real workflows. Scannable proof cards → drawer / bottom-sheet detail.
const PROOF_TOOL_ICONS = {
  "Framer": "ri-pen-nib-line",
  "Webflow": "ri-flow-chart",
  "Next.js": "ri-code-s-slash-line",
  "Shopify": "ri-shopping-bag-3-line",
  "CMS": "ri-pages-line",
  "Analytics": "ri-line-chart-line",
  "Forms": "ri-survey-line",
  "HubSpot": "ri-stack-line",
  "Figma": "ri-shape-line",
  "Lead routing": "ri-git-branch-line",
  "SEO structure": "ri-search-eye-line",
};

const PROOF_CASES = [
  {
    id: "francine",
    company: "Francine's Travel",
    logo: "assets/logo-francine.png", rid: "logoFrancine",
    tone: "magenta",
    tags: ["Marketing site", "Travel", "Inquiry flow", "Mobile-first", "Editable CMS"],
    headline: "A travel site that turns curiosity into booked consultations.",
    summary: "A premium, mobile-first site that explains the service clearly and guides visitors to a consultation request.",
    metrics: [
      { v: "2.4x", l: "more inquiries" },
      { v: "-46%", l: "mobile bounce" },
      { v: "1.1s", l: "largest paint" },
    ],
    quoteShort: "Our site finally looks like the service we actually deliver — and people arrive ready to book.",
    before: "An outdated, hard-to-update site that buried the offer and gave visitors no clear way to start.",
    handles: [
      "Message and page strategy",
      "Custom, conversion-aware design",
      "Mobile-first responsive build",
      "A clear consultation inquiry flow",
      "An editable CMS the team can run",
      "Analytics wired in from day one",
    ],
    approval: "Visitors understand the service in seconds — and know exactly how to start.",
    path: [
      { l: "Site review" }, { l: "Strategy & message" }, { l: "Design concept", cp: true },
      { l: "Responsive build" }, { l: "Inquiry flow" }, { l: "Launch" },
    ],
    tools: ["Framer", "CMS", "Forms", "Analytics"],
    quoteFull: "We used to apologize for our website. Now it does the explaining for us — the offer is obvious, it's fast on a phone, and the right people reach out already knowing how to book.",
    author: "Francine Demelo",
    authorRole: "Francine's Travel",
  },
  {
    id: "ezraider",
    company: "EZ Raider",
    logo: "assets/logo-ezraider.png", rid: "logoEzraider",
    tone: "violet",
    tags: ["Product site", "Conversion", "Speed", "Lead capture", "Design system"],
    headline: "A product site that makes a technical vehicle easy to understand and buy.",
    summary: "A fast, credible product site that explains a complex vehicle simply and routes serious buyers to the team.",
    metrics: [
      { v: "3.1x", l: "demo requests" },
      { v: "+38%", l: "time on page" },
      { v: "94", l: "Lighthouse perf" },
    ],
    quoteShort: "People used to bounce off the spec sheet. Now they get it — and the right buyers reach out.",
    before: "A cluttered page that overwhelmed visitors with specs and never made the next step obvious.",
    handles: [
      "Narrative and information architecture",
      "Conversion-focused product pages",
      "Speed and mobile hardening",
      "Lead capture and routing",
      "A design system for future pages",
    ],
    approval: "A complex product that finally reads as clear, credible, and worth an inquiry.",
    path: [
      { l: "Site review" }, { l: "Message & IA" }, { l: "Design concept", cp: true },
      { l: "Build & speed" }, { l: "Lead routing" }, { l: "Launch" },
    ],
    tools: ["Next.js", "Webflow", "HubSpot", "Analytics"],
    quoteFull: "Our product is genuinely technical, and the old site made it feel intimidating. Siteworks turned it into something people understand in a scroll — and the demo requests followed.",
    author: "Natalie Goldman",
    authorRole: "EZ Raider",
  },
  {
    id: "cro",
    company: "/cro",
    logo: "assets/logo-cro.png", rid: "logoCro",
    tone: "halo",
    tags: ["B2B site", "Content & SEO", "Design system", "Scale", "Performance"],
    headline: "A content site that turns research into pages that rank and convert.",
    summary: "A scalable, SEO-aware site and design system so the team can publish credible pages fast.",
    metrics: [
      { v: "+71%", l: "organic sessions" },
      { v: "21", l: "templated pages" },
      { v: "-52%", l: "time to publish" },
    ],
    quoteShort: "Publishing went from a blank-page slog to dropping content into a system that already looks the part.",
    before: "A patchwork site where every new page was a one-off — slow to ship and inconsistent in quality.",
    handles: [
      "Information architecture and SEO structure",
      "A reusable, branded design system",
      "Templated page components",
      "A performance and accessibility pass",
      "An editable CMS built to scale",
    ],
    approval: "A site the team can grow on — consistent, fast, and built to rank.",
    path: [
      { l: "Site review" }, { l: "IA & SEO" }, { l: "Design system", cp: true },
      { l: "Component build" }, { l: "Migration" }, { l: "Launch" },
    ],
    tools: ["Next.js", "Webflow", "Figma", "Analytics"],
    quoteFull: "Every new page used to start from scratch. Now we drop content into a system that's already on-brand, fast, and structured to rank — the team ships in a fraction of the time.",
    author: "Content lead",
    authorRole: "/cro",
  },
];

function proofLogoSrc(c) {
  return assetUrl(c.logo);
}

function ProofPath({ path }) {
  return (
    <div className="wpath">
      {path.map((n, i) => (
        <React.Fragment key={i}>
          <span className={"wpath-node" + (n.cp ? " cp" : "")}>
            {n.cp && <i className="ri-shield-check-line" />}{n.l}
          </span>
          {i < path.length - 1 && <i className="ri-arrow-right-s-line wpath-sep" />}
        </React.Fragment>
      ))}
    </div>
  );
}

function useCountUp(target, run) {
  const reduce = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!run) return;
    if (reduce) { setN(target); return; }
    let raf, start;
    const tick = (t) => { if (!start) start = t; const p = Math.min(1, (t - start) / 1100); setN(target * (1 - Math.pow(1 - p, 3))); if (p < 1) raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => { if (raf) cancelAnimationFrame(raf); };
  }, [run, target]);
  return run ? n : 0;
}

function CountMetric({ value }) {
  const ref = useRef(null);
  const [run, setRun] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => { es.forEach((e) => { if (e.isIntersecting) { setRun(true); io.disconnect(); } }); }, { threshold: 0.4 });
    io.observe(el);
    const t = setTimeout(() => setRun(true), 1800);
    return () => { io.disconnect(); clearTimeout(t); };
  }, []);
  const m = String(value).match(/^([+-]?)(\d+(?:\.\d+)?)(.*)$/);
  const target = m ? parseFloat(m[2]) : 0;
  const decimals = m ? ((m[2].split(".")[1] || "").length) : 0;
  const n = useCountUp(target, run);
  if (!m) return <span ref={ref}>{value}</span>;
  const shown = decimals ? n.toFixed(decimals) : Math.round(n).toString();
  return <span ref={ref}>{m[1]}{shown}{m[3]}</span>;
}

function ProofMetrics({ metrics, tone }) {
  return (
    <div className="proof-metrics">
      {metrics.map((m) => (
        <div key={m.l} className="proof-metric">
          <span className={"pm-v pm-" + tone}><CountMetric value={m.v} /></span>
          <span className="pm-l">{m.l}</span>
        </div>
      ))}
    </div>
  );
}

function ProofCard({ c, idx, onOpen }) {
  return (
    <div className="proof-card card-mat" style={{ "--bi": idx }}>
      <span className="card-beam" aria-hidden="true" style={{ "--bi": idx }} />
      <div className="proof-card-top">
        <img className="proof-logo" src={proofLogoSrc(c)} alt={c.company} />
        <Pill kind="monitored">Website build</Pill>
      </div>

      <div className="proof-tags">
        {c.tags.map((t) => <span key={t} className="proof-tag">{t}</span>)}
      </div>

      <h3 className="proof-headline">{c.headline}</h3>
      <p className="proof-summary">{c.summary}</p>

      <div className="proof-snap">
        <span className="proof-snap-label">Project snapshot</span>
        <ProofMetrics metrics={c.metrics} tone={c.tone} />
      </div>

      <blockquote className="proof-quote">
        <i className="ri-double-quotes-l" />
        <span>{c.quoteShort}</span>
      </blockquote>

      <button type="button" className="proof-view" onClick={() => onOpen(c.id)}>
        View project <i className="ri-arrow-right-line" />
      </button>
    </div>
  );
}

function ProofDrawer({ c, onClose }) {
  // mount/visible state for slide-in + slide-out
  const [show, setShow] = useState(false);
  useEffect(() => {
    const r = requestAnimationFrame(() => setShow(true));
    const onKey = (e) => { if (e.key === "Escape") close(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { cancelAnimationFrame(r); document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);
  const close = () => { setShow(false); setTimeout(onClose, 360); };
  if (!c) return null;

  return (
    <div className={"proof-drawer-root" + (show ? " show" : "")} role="dialog" aria-modal="true" aria-label={c.company + " workflow"}>
      <div className="proof-scrim" onClick={close} />
      <aside className="proof-drawer">
        <header className="proof-drawer-head">
          <div className="proof-drawer-id">
            <img className="proof-logo proof-logo--lg" src={proofLogoSrc(c)} alt={c.company} />
            <span className="proof-drawer-badges">
              <Pill kind="monitored">Website build</Pill>
              <Pill kind="pending">Conversion-aware</Pill>
            </span>
          </div>
          <button type="button" className="proof-close" onClick={close} aria-label="Close"><i className="ri-close-line" /></button>
        </header>

        <div className="proof-drawer-body">
          <h3 className="proof-drawer-headline">{c.headline}</h3>

          <section className="pd-block">
            <span className="pd-label">Before</span>
            <p className="pd-text">{c.before}</p>
          </section>

          <section className="pd-block">
            <span className="pd-label">What we built</span>
            <ul className="pd-list">
              {c.handles.map((h) => (
                <li key={h}><i className="ri-checkbox-circle-fill" />{h}</li>
              ))}
            </ul>
          </section>

          <section className="pd-block pd-approval">
            <span className="pd-label"><i className="ri-focus-2-line" />Designed for</span>
            <p className="pd-text">{c.approval}</p>
          </section>

          <section className="pd-block">
            <span className="pd-label">Build path</span>
            <ProofPath path={c.path} />
          </section>

          <section className="pd-block">
            <span className="pd-label">Built on</span>
            <div className="pd-tools">
              {c.tools.map((t) => <ToolChip key={t} icon={PROOF_TOOL_ICONS[t] || "ri-apps-line"}>{t}</ToolChip>)}
            </div>
          </section>

          <section className="pd-block">
            <blockquote className="pd-quote">
              <i className="ri-double-quotes-l" />
              <p>{c.quoteFull}</p>
              <footer><span className="pd-author">{c.author}</span><span className="pd-role">{c.authorRole}</span></footer>
            </blockquote>
          </section>

          <section className="pd-block">
            <span className="pd-label">Project snapshot</span>
            <ProofMetrics metrics={c.metrics} tone={c.tone} />
          </section>
        </div>
      </aside>
    </div>
  );
}

function Proof() {
  const ref = useReveal();
  const [openId, setOpenId] = useState(null);
  const openCase = PROOF_CASES.find((c) => c.id === openId) || null;
  return (
    <section id="proof" className="section">
      <div className="wrap">
        <SectionHead eyebrow="Selected work" maxWidth={720}
          lead="These are illustrative builds, not stock screenshots. Each one started the same way: a focused review, a sharper message, and a site engineered to turn visitors into inquiries.">
          Built around the way <span className="gradient-text">real businesses sell.</span>
        </SectionHead>

        <div ref={ref} className="reveal proof-grid">
          {PROOF_CASES.map((c, i) => (
            <ProofCard key={c.id} c={c} idx={i} onOpen={setOpenId} />
          ))}
        </div>
      </div>

      {openCase && <ProofDrawer c={openCase} onClose={() => setOpenId(null)} />}
    </section>
  );
}
Object.assign(window, { Proof });
