// Shared catalog + email-gate for the on-site Tools section. Loaded via
// <script type="text/babel" src="/ga-tools.jsx"> on each /resources/tools/<slug>.html page
// and on resources.html. CATALOG holds presentation fields only (no delivery href —
// that lives server-side in functions/api/_products.js and is returned by
// /api/download on unlock). Titles/blurbs/tags are editable placeholders.
(function () {
  const CATALOG = {
    "vc-fund-performance-calculator": { title: "VC Fund Performance Calculator (TVPI, MOIC, DPI)", blurb: "Calculate TVPI, MOIC, and DPI for a venture fund in Google Sheets or Excel.", image: "/assets/product-vc-fund-calculator.png", tags: ["VC", "Performance", "Template"], type: "copy" },
    "vc-fund-structure": { title: "VC Fund Structure Overview and Guide", blurb: "Understand the key entities in a VC fund: the fund, the GP, and the management company.", image: "/assets/product-vc-fund-structure.png", tags: ["VC", "Structure", "Guide"], type: "file" },
    "early-stage-financial-model": { title: "Early Stage Financial Model Template", blurb: "A financial model to answer key operating questions and understand company finances.", image: "/assets/product-early-stage-financial-model.png", tags: ["Founders", "Model", "Template"], type: "copy" },
    "qsbs-eligibility-calculator": { title: "QSBS Eligibility Tracker and Calculator", blurb: "Track and check QSBS eligibility across your investments.", image: "/assets/product-qsbs-calculator.png", tags: ["Tax", "QSBS", "Calculator"], type: "copy" },
    "vc-fundraising-crm": { title: "VC Fund LP Fundraising Pipeline CRM and Tracker", blurb: "An LP fundraising and pipeline tracker for emerging and experienced managers.", image: "/assets/product-vc-lp-crm.png", tags: ["VC", "Fundraising", "CRM"], type: "copy" },
    "fund-health-performance-checklist": { title: "Fund Health and Performance Checklist", blurb: "A checklist to help you wrap up the quarter and review fund health.", image: "/assets/product-health-perf-checklist.png", tags: ["VC", "Operations", "Checklist"], type: "copy" },
    "data-room-checklist": { title: "Data Room Checklist", blurb: "Get your fundraising data room in order for diligence.", image: "/assets/product-data-room-checklist.png", tags: ["Founders", "Diligence", "Checklist"], type: "copy" },
    "vc-deal-crm-pipeline-tracker": { title: "VC Fund Deal CRM and Pipeline Investment Tracker", blurb: "The foundation for a fund's quarterly and annual operating cadence.", image: "/assets/product-vc-deal-crm.png", tags: ["VC", "Operations", "Tracker"], type: "copy" },
  };

  function DownloadGate({ slug, title, type }) {
    const [email, setEmail] = React.useState("");
    const [hp, setHp] = React.useState("");
    const [status, setStatus] = React.useState("idle"); // idle | sending | done | error
    const [error, setError] = React.useState("");
    const [link, setLink] = React.useState(null); // { href, type }

    const submit = async (e) => {
      e.preventDefault();
      if (status === "sending") return;
      const addr = email.trim();
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(addr)) { setError("Please enter a valid email address."); setStatus("error"); return; }
      setStatus("sending"); setError("");
      try {
        const res = await fetch("/api/download", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: addr, slug, hp }) });
        const data = await res.json();
        if (!data.ok) { setError(data.error || "Something went wrong."); setStatus("error"); return; }
        // Analytics: tie the unlock to the email so it shows in PostHog as an
        // identified "tool_unlocked" conversion. Best-effort; never blocks the reveal.
        if (typeof window !== "undefined" && window.posthog) {
          try { window.posthog.identify(addr); window.posthog.capture("tool_unlocked", { slug, title }); } catch (e) {}
        }
        setLink({ href: data.href, type: data.type || type, emailed: data.emailed }); setStatus("done");
      } catch (err) { setError("Could not reach the server. Please try again."); setStatus("error"); }
    };

    if (status === "done" && link) {
      const label = link.type === "copy" ? "Make a copy →" : "Download →";
      return (
        <div className="ga-gate ga-gate-done">
          {link.emailed ? (
            <React.Fragment>
              <p className="ga-gate-success">Thanks. Your {title} is on its way to {email}.</p>
              <p className="ga-gate-note">It should reach your inbox within a minute. Prefer not to wait? Open it now:</p>
            </React.Fragment>
          ) : (
            <p className="ga-gate-success">Your {title} is ready.</p>
          )}
          <a className="ga-btn ga-btn-primary ga-btn-md" href={link.href} target="_blank" rel="noopener">{label}</a>
        </div>
      );
    }
    return (
      <form className="ga-gate" onSubmit={submit}>
        <label className="ga-gate-label" htmlFor={"gate-" + slug}>Enter your email to get {title} free.</label>
        <div className="ga-gate-row">
          <input id={"gate-" + slug} type="email" required placeholder="Email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          <input className="ga-hp" type="text" tabIndex={-1} autoComplete="off" aria-hidden="true" value={hp} onChange={(e) => setHp(e.target.value)} />
          <button type="submit" className="ga-btn ga-btn-primary ga-btn-md" disabled={status === "sending"}>{status === "sending" ? "Sending…" : "Get it free"}</button>
        </div>
        {status === "error" && <p className="ga-gate-error">{error}</p>}
        <p className="ga-gate-fine">We send the file and occasional fund operating notes. Unsubscribe anytime.</p>
      </form>
    );
  }

  // Breadcrumb back to the higher level pages, shown at the top of each tool
  // page. Links stay reachable on mobile, where the nav collapses to a burger.
  function Crumbs({ title }) {
    return (
      <nav className="ga-crumbs" aria-label="Breadcrumb">
        <a href="/">Home</a>
        <span className="sep" aria-hidden="true">/</span>
        <a href="/resources">Resources</a>
        <span className="sep" aria-hidden="true">/</span>
        <span className="cur">{title}</span>
      </nav>
    );
  }

  // "What you get" list, shown right under the gate on each tool page. Uses a
  // clean circled-check icon in a flex row so the icon never overlaps the text.
  function WhatYouGet({ items }) {
    if (!items || !items.length) return null;
    const ACCENT = "#EE5722"; // styles are inline so they never depend on cached CSS
    return (
      <div style={{ marginTop: 28 }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: ACCENT, marginBottom: 14 }}>What you get</div>
        <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 13 }}>
          {items.map((t, i) => (
            <li key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start", fontSize: 15, lineHeight: 1.5 }}>
              <span aria-hidden="true" style={{ flex: "0 0 auto", width: 20, height: 20, color: ACCENT, marginTop: 1 }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{ display: "block", width: "100%", height: "100%" }}><circle cx="12" cy="12" r="9"></circle><path d="M8.4 12.3l2.4 2.4 4.8-5.2"></path></svg>
              </span>
              <span>{t}</span>
            </li>
          ))}
        </ul>
      </div>
    );
  }

  window.GA_TOOLS = { CATALOG, DownloadGate, Crumbs, WhatYouGet };
})();
