// Waitlist form + success state + onboarding preview modal

const _supabase = supabase.createClient(
  "https://slurczuvkhvsivuwxqjw.supabase.co",
  "sb_publishable_MDZVD1YqS3F9PebjrjdvEw_KjK43FrJ",
);

function Waitlist({ open, onClose }) {
  const [step, setStep] = React.useState("form"); // form, loading, success, onboard1, onboard2, onboard3
  const [email, setEmail] = React.useState("");
  const [name, setName] = React.useState("");
  const [error, setError] = React.useState("");
  const [honeypot, setHoneypot] = React.useState("");
  const [queuePosition, setQueuePosition] = React.useState(null);

  React.useEffect(() => {
    if (open) {
      setStep("form");
      setEmail("");
      setName("");
      setError("");
      setHoneypot("");
      _supabase.rpc("get_waitlist_count").then(({ data }) => {
        if (data !== null) setQueuePosition(Number(data) + 1);
      });
    }
  }, [open]);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape" && open) onClose();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const validateEmail = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

  const submit = async (e) => {
    e.preventDefault();
    if (!email) return setError("Email required");
    if (!validateEmail(email))
      return setError("That doesn't look like a valid email");
    if (honeypot) {
      setStep("success");
      return;
    }
    setError("");
    setStep("loading");
    try {
      window.dispatchEvent(
        new CustomEvent("analytics", {
          detail: {
            event: "waitlist_signup",
            email_domain: email.split("@")[1],
          },
        }),
      );
    } catch (_) {}
    const params = new URLSearchParams(window.location.search);
    const { error: dbError } = await _supabase.from("waitlist_signups").insert({
      email,
      name: name || null,
      source: params.get("utm_source") || "direct",
      utm_medium: params.get("utm_medium") || null,
      utm_campaign: params.get("utm_campaign") || null,
    });
    if (dbError?.code === "23505") {
      setStep("success");
    } else if (dbError) {
      setError("Something went wrong. Please try again.");
      setStep("form");
    } else {
      setStep("success");
    }
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 100,
        background: "rgba(15, 20, 16, 0.55)",
        backdropFilter: "blur(8px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 20,
        animation: "fadeIn 0.2s ease",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          maxWidth: 480,
          background: "var(--bg-elev)",
          borderRadius: "var(--radius-lg)",
          border: "1px solid var(--line)",
          boxShadow: "var(--shadow-lg)",
          padding: 32,
          position: "relative",
          animation: "modalIn 0.3s cubic-bezier(0.2, 0.8, 0.2, 1)",
        }}
      >
        <button
          onClick={onClose}
          style={{
            position: "absolute",
            top: 14,
            right: 14,
            width: 32,
            height: 32,
            borderRadius: 8,
            color: "var(--muted)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <IClose size={16} />
        </button>

        {step === "form" && (
          <form onSubmit={submit}>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "4px 10px",
                borderRadius: 999,
                background: "var(--accent-soft)",
                color: "var(--accent-ink)",
                fontSize: 12,
                marginBottom: 16,
                fontWeight: 500,
              }}
            >
              <span
                style={{
                  width: 6,
                  height: 6,
                  borderRadius: 999,
                  background: "var(--accent)",
                }}
              />
              Private beta
            </div>
            <h3
              style={{
                fontSize: 24,
                marginBottom: 8,
                letterSpacing: "-0.02em",
              }}
            >
              Save your spot
            </h3>
            <p
              style={{
                fontSize: 14,
                color: "var(--muted)",
                marginBottom: 24,
                lineHeight: 1.5,
              }}
            >
              We're inviting people in waves. Founding members get a free
              lifetime plan.
            </p>
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 12,
                marginBottom: 16,
              }}
            >
              <Field
                label="Your name (optional)"
                value={name}
                onChange={setName}
                placeholder="Jane Doe"
              />
              <Field
                label="Email"
                value={email}
                onChange={(v) => {
                  setEmail(v);
                  setError("");
                }}
                placeholder="you@example.com"
                type="email"
                required
                error={error}
              />
            </div>
            <input
              style={{ display: "none" }}
              tabIndex={-1}
              autoComplete="off"
              name="website"
              value={honeypot}
              onChange={(e) => setHoneypot(e.target.value)}
            />
            <button
              type="submit"
              className="btn btn-primary"
              style={{ width: "100%", padding: "14px 20px", fontSize: 15 }}
            >
              Reserve my spot <IArrow size={16} />
            </button>
            <p
              style={{
                fontSize: 12,
                color: "var(--muted)",
                marginTop: 14,
                textAlign: "center",
              }}
            >
              No spam. We'll email you when you're up.
            </p>
          </form>
        )}

        {step === "loading" && (
          <div style={{ padding: "40px 0", textAlign: "center" }}>
            <div
              style={{
                width: 40,
                height: 40,
                margin: "0 auto 20px",
                border: "2px solid var(--line)",
                borderTopColor: "var(--accent)",
                borderRadius: 999,
                animation: "spin 0.8s linear infinite",
              }}
            />
            <div style={{ fontSize: 14, color: "var(--muted)" }}>
              Reserving your spot…
            </div>
          </div>
        )}

        {step === "success" && (
          <div>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "4px 10px",
                borderRadius: 999,
                background: "var(--accent-soft)",
                color: "var(--accent-ink)",
                fontSize: 12,
                marginBottom: 16,
                fontWeight: 500,
              }}
            >
              <span
                style={{
                  width: 6,
                  height: 6,
                  borderRadius: 999,
                  background: "var(--accent)",
                }}
              />
              Spot reserved
            </div>
            <h3
              style={{
                fontSize: 24,
                marginBottom: 8,
                letterSpacing: "-0.02em",
              }}
            >
              You're in.
            </h3>
            <p
              style={{
                fontSize: 14,
                color: "var(--muted)",
                marginBottom: 24,
                lineHeight: 1.5,
              }}
            >
              <span className="mono" style={{ color: "var(--ink-2)" }}>
                {email}
              </span>{" "}
              is on the early access list. We'll reach out the moment your spot
              opens.
            </p>
            <button
              onClick={onClose}
              className="btn btn-primary"
              style={{ width: "100%", padding: "14px 20px", fontSize: 15 }}
            >
              Done
            </button>
          </div>
        )}

        {step === "onboard1" && (
          <OnboardStep
            n={1}
            of={3}
            title="Connect Gmail"
            desc="Read-only OAuth. We can't send, delete, or modify anything in your inbox."
            onNext={() => setStep("onboard2")}
            onBack={() => setStep("success")}
            render={() => <ConnectMock />}
          />
        )}
        {step === "onboard2" && (
          <OnboardStep
            n={2}
            of={3}
            title="What matters to you?"
            desc="Pick the categories you want surfaced. Everything else stays quiet."
            onNext={() => setStep("onboard3")}
            onBack={() => setStep("onboard1")}
            render={() => <CategoryMock />}
          />
        )}
        {step === "onboard3" && (
          <OnboardStep
            n={3}
            of={3}
            title="That's it."
            desc="We'll start watching now. Your first daily digest arrives tomorrow morning."
            onNext={onClose}
            onBack={() => setStep("onboard2")}
            finalLabel="Got it"
            render={() => <FinishedMock />}
          />
        )}
      </div>
    </div>
  );
}

function Field({
  label,
  value,
  onChange,
  placeholder,
  type = "text",
  required,
  error,
}) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span style={{ fontSize: 12, color: "var(--muted)", fontWeight: 500 }}>
        {label}
      </span>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        required={required}
        style={{
          padding: "12px 14px",
          borderRadius: 8,
          border: "1px solid",
          borderColor: error ? "var(--danger)" : "var(--line-strong)",
          background: "var(--bg)",
          color: "var(--ink)",
          fontSize: 15,
          outline: "none",
          transition: "border-color 0.15s ease, box-shadow 0.15s ease",
        }}
        onFocus={(e) => {
          e.target.style.borderColor = "var(--accent-ink)";
          e.target.style.boxShadow = "0 0 0 3px var(--accent-soft)";
        }}
        onBlur={(e) => {
          e.target.style.borderColor = error
            ? "var(--danger)"
            : "var(--line-strong)";
          e.target.style.boxShadow = "none";
        }}
      />
      {error && (
        <span style={{ fontSize: 12, color: "var(--danger)" }}>{error}</span>
      )}
    </label>
  );
}

function OnboardStep({
  n,
  of,
  title,
  desc,
  onNext,
  onBack,
  render,
  finalLabel,
}) {
  return (
    <div>
      <div style={{ display: "flex", gap: 4, marginBottom: 20 }}>
        {Array.from({ length: of }).map((_, i) => (
          <div
            key={i}
            style={{
              flex: 1,
              height: 3,
              borderRadius: 999,
              background: i < n ? "var(--accent)" : "var(--line)",
              transition: "background 0.3s ease",
            }}
          />
        ))}
      </div>
      <div
        className="mono"
        style={{
          fontSize: 11,
          color: "var(--muted)",
          textTransform: "uppercase",
          letterSpacing: "0.1em",
          marginBottom: 8,
        }}
      >
        Step {n} of {of}
      </div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>{title}</h3>
      <p
        style={{
          fontSize: 14,
          color: "var(--muted)",
          marginBottom: 20,
          lineHeight: 1.5,
        }}
      >
        {desc}
      </p>
      <div style={{ marginBottom: 20 }}>{render()}</div>
      <div style={{ display: "flex", gap: 8 }}>
        <button onClick={onBack} className="btn btn-secondary">
          Back
        </button>
        <button
          onClick={onNext}
          className="btn btn-primary"
          style={{ flex: 1 }}
        >
          {finalLabel || "Continue"} <IArrow size={14} />
        </button>
      </div>
    </div>
  );
}

function ConnectMock() {
  return (
    <div
      style={{
        padding: 18,
        borderRadius: 10,
        background: "var(--bg-soft)",
        border: "1px solid var(--line)",
        display: "flex",
        alignItems: "center",
        gap: 14,
      }}
    >
      <div
        style={{
          width: 40,
          height: 40,
          borderRadius: 10,
          background: "#74473B",
          color: "white",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          fontWeight: 600,
        }}
      >
        G
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>Sign in with Google</div>
        <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
          gmail.readonly · calendar.events
        </div>
      </div>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 6,
          color: "var(--accent-ink)",
          fontSize: 12,
          fontWeight: 500,
        }}
      >
        <ICheck size={14} /> Secure
      </div>
    </div>
  );
}

function CategoryMock() {
  const cats = [
    { name: "School", on: true },
    { name: "Medical", on: true },
    { name: "Activities", on: true },
    { name: "Co-parent", on: true },
    { name: "Financial", on: false },
    { name: "Promotions", on: false },
  ];
  return (
    <div
      style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8 }}
    >
      {cats.map((c, i) => (
        <div
          key={i}
          style={{
            padding: "10px 14px",
            borderRadius: 8,
            border: "1px solid",
            borderColor: c.on ? "var(--accent-ink)" : "var(--line)",
            background: c.on ? "var(--accent-soft)" : "var(--bg-soft)",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: 13,
            color: c.on ? "var(--accent-ink)" : "var(--ink-2)",
            fontWeight: c.on ? 500 : 400,
          }}
        >
          <span>{c.name}</span>
          {c.on && <ICheck size={14} />}
        </div>
      ))}
    </div>
  );
}

function FinishedMock() {
  return (
    <div
      style={{
        padding: 24,
        borderRadius: 10,
        background: "var(--bg-soft)",
        border: "1px solid var(--line)",
        textAlign: "center",
      }}
    >
      <div
        style={{
          fontSize: 32,
          fontWeight: 500,
          letterSpacing: "-0.02em",
          color: "var(--accent-ink)",
          marginBottom: 6,
        }}
      >
        ✓ All set
      </div>
      <div style={{ fontSize: 13, color: "var(--muted)" }}>
        Watching 1 inbox · 1 calendar · 0 chat groups
      </div>
    </div>
  );
}

Object.assign(window, { Waitlist });
