// Canaisay Landing v2 — base module.
// Shared atoms (Logo, Brand, AppleMark), hooks, Topbar, Waitlist modal.
// Wrapped in an IIFE so top-level consts don't collide across babel scripts.
(function () {
  const { useState, useEffect, useRef } = React;

  // —————————————————————————————————————————————
  // Analytics helpers — PostHog + Meta Pixel, safe before SDKs finish loading
  // —————————————————————————————————————————————
  const phCapture = (event, props) => {
    try { window.posthog && window.posthog.capture && window.posthog.capture(event, props || {}); } catch (e) {}
  };
  const phIdentify = (id, props) => {
    try { window.posthog && window.posthog.identify && window.posthog.identify(id, props || {}); } catch (e) {}
  };
  const fbTrack = (event, props) => {
    try { window.fbq && window.fbq("track", event, props || {}); } catch (e) {}
  };
  const getUtm = () => {
    try {
      const p = new URLSearchParams(window.location.search);
      const out = {};
      ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "fbclid", "gclid"].forEach((k) => {
        const v = p.get(k);
        if (v) out[k] = v;
      });
      return out;
    } catch (e) {
      return {};
    }
  };
  const saveWaitlistEmail = async (email, utm) => {
    const response = await fetch("/api/waitlist", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email,
        utm,
        page: window.location.href,
        referrer: document.referrer || "",
      }),
    });
    if (!response.ok) {
      throw new Error(`Waitlist save failed: ${response.status}`);
    }
    return response.json().catch(() => ({}));
  };
  const rememberPendingWaitlistEmail = (email, utm) => {
    try {
      window.localStorage.setItem("canaisay_waitlist_pending", JSON.stringify({
        email,
        utm,
        savedAt: new Date().toISOString(),
      }));
    } catch (e) {}
  };

  // —————————————————————————————————————————————
  // Apple glyph for "Download for Mac" buttons
  // —————————————————————————————————————————————
  function AppleMark() {
    return (
      <svg width="14" height="16" viewBox="0 0 14 16" aria-hidden="true" style={{ display: "block" }}>
        <path fill="currentColor" d="M11.19 8.47c-.02-2.07 1.69-3.06 1.77-3.11-.97-1.41-2.47-1.6-3-1.62-1.27-.13-2.49.75-3.13.75-.65 0-1.65-.73-2.71-.71-1.39.02-2.68.81-3.4 2.06-1.45 2.52-.37 6.24 1.04 8.29.69 1 1.51 2.13 2.58 2.09 1.04-.04 1.43-.67 2.68-.67 1.25 0 1.6.67 2.7.65 1.11-.02 1.82-1.02 2.5-2.03.79-1.16 1.12-2.29 1.14-2.35-.03-.01-2.18-.84-2.2-3.33zM9.26 2.47c.57-.7.96-1.66.85-2.63-.82.03-1.83.55-2.42 1.24-.53.61-1 1.6-.87 2.55.92.07 1.85-.47 2.44-1.16z"/>
      </svg>
    );
  }

  function Brand() {
    return <span className="brand-inline">CANAISAY</span>;
  }

  function Logo({ size = 48 }) {
    const uid = React.useId().replace(/:/g, "");
    return (
      <svg width={size} height={size} viewBox="0 0 64 64" style={{ display: "block" }} aria-hidden="true">
        <defs>
          <linearGradient id={`eb-${uid}`} x1="0" y1="0" x2="0.5" y2="1">
            <stop offset="0%" stopColor="#8dcfff" stopOpacity="0.92" />
            <stop offset="100%" stopColor="#c2f0e7" stopOpacity="0.95" />
          </linearGradient>
          <radialGradient id={`eg-${uid}`} cx="35%" cy="35%" r="38%">
            <stop offset="0%" stopColor="#fff" stopOpacity="0.98" />
            <stop offset="60%" stopColor="#fff" stopOpacity="0.3" />
            <stop offset="100%" stopColor="#fff" stopOpacity="0" />
          </radialGradient>
          <linearGradient id={`pb-${uid}`} x1="0.5" y1="0" x2="0.5" y2="1">
            <stop offset="0%" stopColor="#0e4d8c" />
            <stop offset="100%" stopColor="#3b88f6" />
          </linearGradient>
          <radialGradient id={`pg-${uid}`} cx="35%" cy="35%" r="30%">
            <stop offset="0%" stopColor="#fff" stopOpacity="0.9" />
            <stop offset="50%" stopColor="#fff" stopOpacity="0.2" />
            <stop offset="100%" stopColor="#fff" stopOpacity="0" />
          </radialGradient>
          <clipPath id={`clip-${uid}`}>
            <rect x="4" y="4" width="56" height="56" rx="21" />
          </clipPath>
        </defs>
        <rect width="64" height="64" rx="24" fill={`url(#eb-${uid})`} />
        <rect width="64" height="64" rx="24" fill={`url(#eg-${uid})`} />
        <rect x="0.5" y="0.5" width="63" height="63" rx="23.5" fill="none" stroke="white" strokeOpacity="0.9" />
        <g clipPath={`url(#clip-${uid})`}>
          <g className="canaisay-pupil">
            <rect x="18" y="18" width="28" height="28" rx="14" fill={`url(#pb-${uid})`} />
            <rect x="18" y="18" width="28" height="28" rx="14" fill={`url(#pg-${uid})`} />
          </g>
        </g>
      </svg>
    );
  }

  // —————————————————————————————————————————————
  // Hooks
  // —————————————————————————————————————————————
  function useReveal() {
    const ref = useRef(null);
    const [shown, setShown] = useState(false);
    useEffect(() => {
      if (!ref.current) return;
      const io = new IntersectionObserver(
        (entries) => entries.forEach((e) => e.isIntersecting && setShown(true)),
        { threshold: 0.15 }
      );
      io.observe(ref.current);
      return () => io.disconnect();
    }, []);
    return [ref, shown];
  }

  function Reveal({ children, delay = 0, className = "" }) {
    const [ref, shown] = useReveal();
    return (
      <div
        ref={ref}
        className={`reveal ${shown ? "is-in" : ""} ${className}`}
        style={{ transitionDelay: `${delay}ms` }}
      >
        {children}
      </div>
    );
  }

  // Preserve any preview token (?t=...) when linking to the demo
  const demoHref = () =>
    typeof window !== "undefined"
      ? `live-demo.html${window.location.search || ""}`
      : "live-demo.html";

  // —————————————————————————————————————————————
  // Waitlist modal — opened by every "Download for Mac"
  // —————————————————————————————————————————————
  function WaitlistModal() {
    const [open, setOpen] = useState(false);
    const [email, setEmail] = useState("");
    const [submitted, setSubmitted] = useState(false);
    const [saving, setSaving] = useState(false);
    const [saveError, setSaveError] = useState("");
    const inputRef = useRef(null);

    useEffect(() => {
      window.openWaitlist = () => {
        setSubmitted(false);
        setEmail("");
        setSaving(false);
        setSaveError("");
        setOpen(true);
      };
      const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, []);

    useEffect(() => {
      if (open && !submitted) {
        phCapture("waitlist_modal_opened", getUtm());
        const id = setTimeout(() => inputRef.current?.focus(), 80);
        return () => clearTimeout(id);
      }
    }, [open, submitted]);

    if (!open) return null;

    const submit = async (e) => {
      e.preventDefault();
      if (saving) return;
      const cleanEmail = email.trim();
      if (!/^\S+@\S+\.\S+$/.test(cleanEmail)) return;
      const utm = getUtm();
      setSaving(true);
      setSaveError("");
      try {
        await saveWaitlistEmail(cleanEmail, utm);
        phIdentify(cleanEmail, { email: cleanEmail, signup_source: "landing", ...utm });
        phCapture("waitlist_signup_success", { email: cleanEmail, ...utm });
        fbTrack("Lead", { content_name: "canaisay_waitlist" });
        setSubmitted(true);
      } catch (err) {
        rememberPendingWaitlistEmail(cleanEmail, utm);
        phCapture("waitlist_signup_save_failed", {
          email: cleanEmail,
          reason: err?.message || "unknown",
          ...utm,
        });
        setSaveError("Couldn’t save that email. Please try again.");
      } finally {
        setSaving(false);
      }
    };

    return (
      <div className="wl-backdrop" onClick={() => setOpen(false)}>
        <div className="wl-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Private beta waitlist">
          <button className="wl-close" onClick={() => setOpen(false)} aria-label="Close">×</button>
          <div className="wl-eye" aria-hidden="true"><Logo size={56} /></div>
          {!submitted ? (
            <>
              <h3 className="wl-title">A couple of weeks early.</h3>
              <p className="wl-body">
                The <Brand /> desktop app ships in <strong>14 days</strong>. Leave your
                email and we'll ping you the moment it's downloadable.
              </p>
              <form className="wl-form" onSubmit={submit}>
                <input ref={inputRef} type="email" className="wl-input" placeholder="you@work.com"
                  value={email} onChange={(e) => { setEmail(e.target.value); setSaveError(""); }} required disabled={saving} />
                <button type="submit" className="wl-submit" disabled={saving}>
                  {saving ? "Saving..." : "Notify me"}
                </button>
              </form>
              {saveError && <div className="wl-error" role="status">{saveError}</div>}
              <div className="wl-fine">
                <span className="wl-dot" /> Mac-first · private beta · no spam, ever
              </div>
            </>
          ) : (
            <>
              <div className="wl-check" aria-hidden="true">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M4 12.5 10 18 20 6" />
                </svg>
              </div>
              <h3 className="wl-title">You're on the list.</h3>
              <p className="wl-body">
                Thanks — we'll email <strong>{email}</strong> the moment <Brand /> is
                ready to download. See you in ~2 weeks.
              </p>
              <button className="wl-submit wl-close-cta" onClick={() => setOpen(false)}>Close</button>
            </>
          )}
        </div>
      </div>
    );
  }

  function openWaitlist(e, location) {
    if (e) e.preventDefault();
    phCapture("cta_clicked", { label: "download_for_mac", location: location || "unknown", ...getUtm() });
    if (typeof window !== "undefined" && typeof window.openWaitlist === "function") {
      window.openWaitlist();
    }
  }

  function trackSalesClick(location) {
    phCapture("cta_clicked", { label: "talk_to_sales", location: location || "unknown", ...getUtm() });
  }

  // —————————————————————————————————————————————
  // Topbar
  // —————————————————————————————————————————————
  function Topbar() {
    return (
      <header className="topbar">
        <a href="#top" className="brand">
          <Logo size={40} />
          <div className="brand-text">
            <div className="brand-wordmark">CANAISAY</div>
            <div className="brand-tag">Live context for calls and videos</div>
          </div>
        </a>
        <nav className="nav">
          <a href="#why">Why</a>
          <a href="#how">What it does</a>
          <a href="#cases">Where it works</a>
          <a href="#roadmap">Roadmap</a>
        </nav>
        <a href="#cta" className="cta-sm" onClick={(e) => openWaitlist(e, "topbar")}>
          <AppleMark />
          Download for Mac
        </a>
      </header>
    );
  }

  // Export to window for the other babel scripts
  Object.assign(window, {
    AppleMark, Brand, Logo, useReveal, Reveal, demoHref,
    WaitlistModal, openWaitlist, trackSalesClick, Topbar,
  });
})();
