/* global React, ReactDOM, IconDownload, IconArrowRight, IconLock, IconCheck */

/* =============================================================================
   GATED DOWNLOAD MODAL
   - One reusable modal for all gated PDFs (5 assets, 12+ CTAs).
   - Trigger from anywhere: window.openGatedDownload("architecture-gap", { source: "..." })
   - Reads asset config from window.GATED_ASSETS.
   - Two-column layout: left = asset meta, right = form.
   - Progressive profiling via localStorage("doblier:lead").
   - On submit: PDF downloads, modal switches to thank-you state.
   ============================================================================= */

const { useState, useEffect, useCallback, useRef } = React;

/* ---------- Asset configuration ----------
   Each entry maps to one PDF + one modal configuration.
   Per CTA Destination Map § 1.2.
*/
const GATED_ASSETS = {
  "architecture-gap": {
    tag: "// Whitepaper · 12 pages",
    title: "The Architecture Gap™",
    subtitle: "Why enterprise AI fails in production.",
    description: "12-page research report on the gap between AI capability and enterprise architecture. Market data, the three mistakes vendors make, the AORBIT approach, and a framework for closing it.",
    inside: [
      "The $401B infrastructure problem",
      "Why 5% GPU utilization is the symptom, not the cause",
      "The three architecture failures vendors keep repeating",
      "A framework for closing The Architecture Gap™",
    ],
    cta: "Download the whitepaper",
    requireRole: true,
    file: "site/assets/the-architecture-gap-whitepaper.pdf",
    filename: "the-architecture-gap-whitepaper.pdf",
  },
  "data-sovereignty-brief": {
    tag: "// Executive brief · 2 pages",
    title: "Data Sovereignty",
    subtitle: "Building AI where your data lives.",
    description: "2-page executive brief on zero-exfiltration architecture and regulatory compliance. The compact version of the AORBIT data sovereignty story, for sharing with risk and compliance teams.",
    inside: [
      "Why every external AI API call is a compliance event",
      "Zero-exfiltration architecture, explained in one diagram",
      "Mapping to SAMA, GDPR, PCI DSS, and PDPL",
      "What to ask any AI vendor before they touch your data",
    ],
    cta: "Download the brief",
    requireRole: false,
    file: "site/assets/data-sovereignty-brief.pdf",
    filename: "data-sovereignty-brief.pdf",
  },
  "banking-case-study": {
    tag: "// Case study · 4 pages · Anonymized",
    title: "Private AI for Banking",
    subtitle: "From assessment to production.",
    description: "Anonymized case study of a major Saudi bank. The full story: challenge, AORBIT™ deployment, production outcome. Includes architecture overview and compliance mapping.",
    inside: [
      "Regulatory context and SAMA constraints",
      "AORBIT™ deployment architecture inside the bank",
      "Production outcomes and zero-exfiltration audit trail",
      "What we'd do differently next time",
    ],
    cta: "Download the case study",
    requireRole: true,
    file: "site/assets/banking-case-study.pdf",
    filename: "banking-case-study.pdf",
  },
  "architecture-brief": {
    tag: "// Executive brief · 2 pages",
    title: "AORBIT™ Architecture Brief",
    subtitle: "The five-layer architecture, on two pages.",
    description: "Two-page executive overview of the AORBIT™ five-layer architecture. The \"share with your CTO\" asset.",
    inside: [
      "The five layers, at a glance",
      "Foundation · Intelligence · Frontier",
      "How AORBIT™ maps to an existing stack",
      "Deployment options: on-prem, private cloud, hybrid",
    ],
    cta: "Download the brief",
    requireRole: false,
    file: "site/assets/aorbit-architecture-brief.pdf",
    filename: "aorbit-architecture-brief.pdf",
  },
  "banking-architecture-brief": {
    tag: "// Executive brief · 2 pages",
    title: "AI Architecture for Banking & Finance",
    subtitle: "AORBIT™ mapped to banking infrastructure.",
    description: "How AORBIT™ maps to core banking infrastructure, compliance frameworks, and operations. The architecture brief for banking CTOs and CISOs.",
    inside: [
      "Core banking integration patterns",
      "SAMA, PCI DSS, GDPR compliance mapping",
      "Reference architecture for production banking AI",
      "Field notes from 20+ banking engagements",
    ],
    cta: "Download the brief",
    requireRole: true,
    file: "site/assets/banking-architecture-brief.pdf",
    filename: "banking-architecture-brief.pdf",
  },
};
window.GATED_ASSETS = GATED_ASSETS;

/* ---------- Progressive profiling helpers ---------- */
const LEAD_KEY = "doblier:lead";
function loadLead() {
  try { return JSON.parse(localStorage.getItem(LEAD_KEY) || "{}"); }
  catch { return {}; }
}
function saveLead(d) {
  try {
    const prev = loadLead();
    localStorage.setItem(LEAD_KEY, JSON.stringify({ ...prev, ...d }));
  } catch {}
}

/* ---------- Imperative trigger ---------- */
let _opener = null;
function GatedDownloadHost() {
  const [open, setOpen] = useState(null); // { assetId, source }

  useEffect(() => {
    _opener = (assetId, opts = {}) => {
      if (!GATED_ASSETS[assetId]) {
        console.warn("Unknown gated asset:", assetId);
        return;
      }
      setOpen({ assetId, source: opts.source || null });
    };
    window.openGatedDownload = _opener;
    return () => { delete window.openGatedDownload; };
  }, []);

  // Esc to close
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(null); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);

  if (!open) return null;
  const asset = GATED_ASSETS[open.assetId];
  return <GatedDownloadModal asset={asset} source={open.source} onClose={() => setOpen(null)} />;
}

/* ---------- Modal ---------- */
function GatedDownloadModal({ asset, source, onClose }) {
  const [submitted, setSubmitted] = useState(false);
  const [values, setValues] = useState(() => {
    const prev = loadLead();
    return {
      name: prev.name || "",
      email: prev.email || "",
      company: prev.company || "",
      role: prev.role || "",
      marketing: false,
    };
  });

  const overlayRef = useRef(null);
  const onOverlay = (e) => { if (e.target === overlayRef.current) onClose(); };

  const submit = async (e) => {
    e.preventDefault();
    if (!values.name.trim() || !values.email.trim() || !values.company.trim()) return;
    if (asset.requireRole && !values.role.trim()) return;

    // Persist progressive profile (no marketing flag stored).
    saveLead({
      name: values.name.trim(),
      email: values.email.trim(),
      company: values.company.trim(),
      role: values.role.trim(),
    });

    // Fetch the PDF and trigger a Blob download — the most reliable path
    // across browsers, sandboxed iframes, and file:// origins. If fetch
    // fails (e.g. file:// in some browsers), fall back to a direct <a>.
    try {
      const res = await fetch(asset.file);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const blob = await res.blob();
      const typed = new Blob([blob], { type: "application/pdf" });
      const url = URL.createObjectURL(typed);
      const a = document.createElement("a");
      a.href = url;
      a.download = asset.filename;
      a.rel = "noopener";
      document.body.appendChild(a);
      a.click();
      a.remove();
      // Hold the URL long enough for the download to start, then revoke.
      setTimeout(() => URL.revokeObjectURL(url), 4000);
    } catch (err) {
      // Last-resort fallback: open the file directly in a new tab so the
      // visitor can save it manually.
      console.warn("Gated download fetch failed, falling back to new-tab open:", err);
      try { window.open(asset.file, "_blank", "noopener"); } catch {}
    }

    // Fire analytics event (consumer wires CRM in production).
    try {
      window.dispatchEvent(new CustomEvent("doblier:gated-download", {
        detail: { asset: asset.filename, source: source || null, role: values.role || null, marketingConsent: !!values.marketing },
      }));
    } catch {}

    setSubmitted(true);
  };

  // Reusable input styling (matches existing forms).
  const inputBase = {
    background: "var(--bg)",
    border: "1px solid var(--border-bright)",
    borderRadius: 2,
    padding: "11px 13px",
    color: "var(--text)",
    fontFamily: "var(--font-sans)",
    fontSize: 14,
    outline: "none",
    width: "100%",
  };
  const labelMono = {
    fontFamily: "var(--font-mono)",
    fontSize: 10,
    letterSpacing: "0.08em",
    textTransform: "uppercase",
    color: "var(--text-mute)",
  };
  const onF = (k) => (e) => setValues((v) => ({ ...v, [k]: e.target.value }));

  return (
    <div className="gd-overlay" ref={overlayRef} onMouseDown={onOverlay} role="dialog" aria-modal="true" aria-label={asset.title}>
      <div className="gd-modal">
        <button className="gd-close" onClick={onClose} aria-label="Close">×</button>

        {!submitted ? (
          <div className="gd-grid">
            {/* LEFT · ASSET META */}
            <aside className="gd-meta">
              <div className="eyebrow" style={{ fontSize: 10 }}>{asset.tag}</div>
              <h3 className="gd-title">{asset.title}</h3>
              <p className="gd-subtitle">{asset.subtitle}</p>
              <p className="gd-desc">{asset.description}</p>
              <div className="gd-inside-label">// Inside</div>
              <ul className="gd-inside">
                {asset.inside.map((x, i) => (
                  <li key={i}>
                    <span className="gd-bullet">→</span> {x}
                  </li>
                ))}
              </ul>
              <div className="gd-trust">
                <IconLock size={14} />
                <span>One submission. No spam. Privacy Policy applies.</span>
              </div>
            </aside>

            {/* RIGHT · FORM */}
            <form className="gd-form" onSubmit={submit}>
              <div className="eyebrow" style={{ fontSize: 10 }}>Request</div>
              <h4 className="gd-form-h">Get the {asset.title.replace("™", "")}.</h4>

              <label className="gd-field">
                <span style={labelMono}>Full name *</span>
                <input type="text" required value={values.name} onChange={onF("name")} placeholder="—" data-hj-suppress data-clarity-mask style={inputBase} />
              </label>

              <label className="gd-field">
                <span style={labelMono}>Work email *</span>
                <input type="email" required value={values.email} onChange={onF("email")} placeholder="you@enterprise.com" data-hj-suppress data-clarity-mask style={inputBase} />
              </label>

              <label className="gd-field">
                <span style={labelMono}>Company *</span>
                <input type="text" required value={values.company} onChange={onF("company")} placeholder="—" data-hj-suppress data-clarity-mask style={inputBase} />
              </label>

              <label className="gd-field">
                <span style={labelMono}>Role {asset.requireRole ? "*" : <span style={{ textTransform: "none", color: "var(--text-mute)" }}>(optional)</span>}</span>
                <input type="text" required={asset.requireRole} value={values.role} onChange={onF("role")} placeholder="CTO · CISO · VP Eng" data-hj-suppress data-clarity-mask style={inputBase} />
              </label>

              <label className="consent-row" style={{ marginTop: 4 }}>
                <input
                  type="checkbox"
                  checked={values.marketing}
                  onChange={(e) => setValues((v) => ({ ...v, marketing: e.target.checked }))}
                />
                <span>
                  I agree to receive marketing communications from Doblier. You can unsubscribe at any time.
                </span>
              </label>

              <button type="submit" className="btn btn-primary" style={{ marginTop: 4, justifyContent: "center" }}>
                {asset.cta} <IconDownload size={14} />
              </button>

              <p className="form-privacy-note" style={{ marginTop: 0 }}>
                By submitting, you agree to our{" "}
                <a href="#/privacy" onClick={onClose}>Privacy Policy</a>{" "}and{" "}
                <a href="#/terms" onClick={onClose}>Terms of Use</a>.
              </p>
            </form>
          </div>
        ) : (
          /* THANK-YOU STATE */
          <div className="gd-thanks">
            <div className="gd-check"><IconCheck size={28} /></div>
            <div className="eyebrow" style={{ fontSize: 10, justifyContent: "center", display: "inline-flex" }}>Sent</div>
            <h3 className="gd-title" style={{ textAlign: "center", marginTop: 12 }}>Downloaded. We'll be in touch.</h3>
            <p className="gd-desc" style={{ textAlign: "center", maxWidth: 480, margin: "16px auto 0" }}>
              The PDF is in your downloads. An architect will follow up within one business day if your role suggests we should.
            </p>
            <p className="gd-desc" style={{ textAlign: "center", maxWidth: 480, margin: "8px auto 0", fontSize: 13 }}>
              Didn't see it? <a href={asset.file} download={asset.filename} target="_blank" rel="noopener noreferrer" style={{ color: "var(--teal)", borderBottom: "1px solid currentColor" }}>Open the PDF in a new tab.</a>
            </p>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 32, flexWrap: "wrap" }}>
              <a
                href="#/talk-to-an-architect"
                className="btn btn-primary"
                onClick={onClose}
              >
                Talk to an architect <IconArrowRight size={14} className="arrow" />
              </a>
              <button className="btn btn-ghost" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.GatedDownloadHost = GatedDownloadHost;
