/* global React */
// =============================================================
// WaitlistDialog: email-capture modal shown in place of a download CTA
// for platforms that have no trusted prebuilt binary yet.
//
// iOS / Android have no binary at all. Linux has an AppImage but it's
// untested, so we gate the prebuilt download and capture interest while
// the source build (Free tier) stays available. The dialog adapts its
// copy: mobile is "the app is ready to install", Linux is "the prebuilt,
// signed AppImage is ready (build from source today)".
//
// One network call on submit · POST /api/lead with a platform field so
// the backend can bucket counts. source is "linux_waitlist" for Linux,
// "mobile_waitlist" for phones. The endpoint is the same one BuyDialog
// and the NewsletterForm post to. If the backend hasn't grown a
// `platform`/`source` column the field is dropped silently and the lead
// still lands.
//
// No public counter, no Stripe, no in-app fallback. The point is the
// promise: "we'll write once when it ships."
// =============================================================
const { useEffect: useWLE, useRef: useWLR, useState: useWLS } = React;

const WAITLIST_BACKEND = "https://license.dimmy.app";

function WaitlistDialog({ open, platform, onClose }) {
  const [email, setEmail] = useWLS("");
  const [status, setStatus] = useWLS("idle"); // idle | submitting | sent | error
  const [errorMsg, setErrorMsg] = useWLS("");
  const inputRef = useWLR(null);

  useWLE(() => {
    if (!open) return;
    setStatus("idle");
    setErrorMsg("");
    try {
      const saved = localStorage.getItem("dimmy-email") || "";
      if (saved && !email) setEmail(saved);
    } catch (_) {}
    requestAnimationFrame(() => inputRef.current && inputRef.current.focus());
  }, [open]);

  useWLE(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;

  const validEmail = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim());
  const locale = (typeof document !== "undefined" && document.documentElement && document.documentElement.lang) || "en";
  const isLinux = platform === "linux";
  const platformLabel = platform === "android" ? "Android" : isLinux ? "Linux" : "iOS";
  const platformColor = platform === "android" ? "#34D399" : isLinux ? "#FBBF24" : "#38BDF8";
  const GITHUB_URL = "https://github.com/KonradDallaOrg/dimmy";

  async function submit(e) {
    e.preventDefault();
    if (!validEmail || status === "submitting") return;
    const clean = email.trim().toLowerCase();
    setStatus("submitting");
    setErrorMsg("");
    try {
      const r = await fetch(`${WAITLIST_BACKEND}/api/lead`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: clean,
          source: isLinux ? "linux_waitlist" : "mobile_waitlist",
          tier: null,
          platform,
          locale,
        }),
      });
      if (!r.ok) throw new Error(`${r.status}`);
      try { localStorage.setItem("dimmy-email", clean); } catch (_) {}
      setStatus("sent");
    } catch (_) {
      setStatus("error");
      setErrorMsg("Couldn't reach the waitlist server. Try again or email hi@dimmy.app.");
    }
  }

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label={`Join ${platformLabel} waitlist`}
      onClick={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}
      style={{
        position: "fixed", inset: 0, zIndex: 1000,
        background: "rgba(0,0,0,0.62)",
        backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 20,
        animation: "fade-up 220ms cubic-bezier(0.2,0.8,0.2,1)",
      }}
    >
      <div style={{
        width: "100%", maxWidth: 440,
        background: "var(--bg)",
        border: "1px solid var(--line-strong)",
        borderRadius: 18,
        padding: 28,
        boxShadow: "0 30px 80px rgba(0,0,0,0.5)",
      }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 11,
          color: platformColor, letterSpacing: "0.14em", textTransform: "uppercase",
          marginBottom: 8,
        }}>Dimmy for {platformLabel} · waitlist</div>

        <h3 style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: 24, letterSpacing: "-0.02em", lineHeight: 1.15,
          margin: 0, color: "var(--fg)",
        }}>{status === "sent"
          ? (isLinux ? "You're on the Linux list." : "We'll write when it ships.")
          : (isLinux ? "A tested Linux build is on the way." : `Dimmy for ${platformLabel} is on the way.`)}</h3>

        <p style={{
          fontSize: 14, color: "var(--fg-muted)", lineHeight: 1.55,
          marginTop: 10, marginBottom: 22, textWrap: "pretty",
        }}>
          {status === "sent"
            ? (isLinux
                ? "One short note the day the prebuilt, signed AppImage is ready. Meanwhile you can build from source on GitHub today."
                : `Your email is in the ${platformLabel} bucket. One short note when the app is ready to install. No marketing in between, unsubscribe with one click.`)
            : (isLinux
                ? "Dimmy already builds from source on Linux. We're polishing a tested, signed AppImage so you don't have to compile. Drop your email for one note the day the prebuilt binary lands. No marketing, unsubscribe with one click."
                : `Drop your email and we'll send exactly one note the day the ${platformLabel} app is ready to install. No marketing, no third parties, unsubscribe with one click.`)}
        </p>

        {status !== "sent" && (
          <form onSubmit={submit}>
            <label htmlFor="wl-email" style={{
              display: "block", fontSize: 12, fontFamily: "var(--font-mono)",
              color: "var(--fg-faint)", letterSpacing: "0.06em",
              textTransform: "uppercase", marginBottom: 8,
            }}>Email</label>

            <input
              ref={inputRef}
              id="wl-email"
              type="email"
              autoComplete="email"
              placeholder="you@domain.com"
              value={email}
              onChange={(e) => { setEmail(e.target.value); if (status === "error") setStatus("idle"); }}
              disabled={status === "submitting"}
              style={{
                width: "100%", padding: "12px 14px", borderRadius: 10,
                background: "var(--bg-elev)",
                border: "1px solid var(--line-strong)",
                color: "var(--fg)", fontSize: 15,
                fontFamily: "var(--font-sans)",
                outline: "none",
                transition: "border-color 160ms",
              }}
            />

            {status === "error" && (
              <div style={{
                marginTop: 12, padding: "10px 12px", borderRadius: 8,
                background: "rgba(239,68,68,0.10)",
                border: "1px solid rgba(239,68,68,0.35)",
                color: "#FCA5A5", fontSize: 13, lineHeight: 1.45,
              }}>{errorMsg}</div>
            )}

            <button
              type="submit"
              disabled={!validEmail || status === "submitting"}
              style={{
                marginTop: 16, width: "100%",
                padding: "13px 16px", borderRadius: 10,
                background: validEmail && status !== "submitting" ? platformColor : "var(--line)",
                color: validEmail && status !== "submitting" ? "var(--bg-deep)" : "var(--fg-faint)",
                border: 0, fontWeight: 600, fontSize: 14,
                fontFamily: "var(--font-sans)",
                cursor: validEmail && status !== "submitting" ? "pointer" : "not-allowed",
                transition: "transform 160ms, background 200ms",
              }}
            >
              {status === "submitting" ? "Adding you..." : `Notify me when ${platformLabel} ships`}
            </button>
          </form>
        )}

        <div style={{
          marginTop: 18, paddingTop: 16,
          borderTop: "1px solid var(--line)",
          display: "flex", justifyContent: "space-between", alignItems: "center",
          gap: 12, flexWrap: "wrap",
        }}>
          {isLinux ? (
            <a href={GITHUB_URL} target="_blank" rel="noopener noreferrer" style={{
              fontSize: 12, fontFamily: "var(--font-mono)",
              color: "var(--fg-muted)", textDecoration: "none",
            }}>Want it now? Build from source on GitHub ↗</a>
          ) : (
            <span style={{
              fontSize: 12, fontFamily: "var(--font-mono)",
              color: "var(--fg-faint)",
            }}>Desktop today? Try macOS or Windows.</span>
          )}

          <button type="button" onClick={() => onClose && onClose()} style={{
            background: "transparent", border: 0,
            color: "var(--fg-faint)", fontSize: 12,
            fontFamily: "var(--font-mono)", cursor: "pointer",
            padding: 0,
          }}>{status === "sent" ? "Close" : "Cancel (Esc)"}</button>
        </div>

        <p style={{
          marginTop: 16, fontSize: 11, color: "var(--fg-faint)",
          lineHeight: 1.55, fontFamily: "var(--font-mono)",
        }}>
          One mail, the day it ships. No tracking, no investors, no third parties.
        </p>
      </div>
    </div>
  );
}

window.WaitlistDialog = WaitlistDialog;
