/* global React */
// Mailing-list sign-up (modal) + unsubscribe (SPA page).
// Both talk to the Firebase callable functions exposed on
// window.__mailingListReady (resolves to { signUp, unsubscribe }).

const MailingList = (function () {
  const { Button, Input } = window.CueDesignSystem_89ac8b;
  const { useState, useEffect } = React;

  // Public mailing-list REST endpoints.
  const ENDPOINTS = {
    signUp: "https://cue-api.qaecy.com/commands/public/mailing-list",
    unsubscribe: "https://cue-api.qaecy.com/commands/public/mailing-list/unsubscribe",
  };

  // POST a payload and surface a human-readable error from the JSON body
  // (falling back to a friendly message per HTTP status).
  async function call(fn, payload) {
    let res;
    try {
      res = await fetch(ENDPOINTS[fn], {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
    } catch (e) {
      throw new Error("Couldn't reach the server. Please check your connection and try again.");
    }
    if (!res.ok) {
      let msg = "";
      try { const j = await res.json(); msg = j && j.message; } catch (e) {}
      if (!msg) {
        if (res.status === 409) msg = "This email is already on the list.";
        else if (res.status === 404) msg = "That email isn't on our mailing list.";
        else if (res.status === 400) msg = "Please check the details and try again.";
        else msg = "Something went wrong. Please try again.";
      }
      throw new Error(msg);
    }
    try { return await res.json(); } catch (e) { return null; }
  }

  const HOW_OPTIONS = [
    "", "Search engine", "Social media", "Word of mouth",
    "Event or conference", "Press or article", "Other",
  ];

  /* ---------- Waitlist sign-up form (used inside the modal) ---------- */
  function WaitlistForm({ onDone }) {
    const [f, setF] = useState({ email: "", name: "", organization: "", role: "", howIFoundYou: "" });
    const [status, setStatus] = useState("idle"); // idle | sending | done | error
    const [err, setErr] = useState("");
    const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

    const submit = async (e) => {
      e.preventDefault();
      if (status === "sending") return;
      if (!f.email.trim() || !f.name.trim()) {
        setErr("Please enter your name and email.");
        setStatus("error");
        return;
      }
      setStatus("sending");
      setErr("");
      try {
        await call("signUp", {
          email: f.email.trim(),
          name: f.name.trim(),
          organization: f.organization.trim() || undefined,
          role: f.role.trim() || undefined,
          howIFoundYou: f.howIFoundYou || undefined,
        });
        setStatus("done");
      } catch (e2) {
        setErr((e2 && e2.message) || "Something went wrong. Please try again.");
        setStatus("error");
      }
    };

    if (status === "done") {
      return (
        <div className="wl-done">
          <div className="wl-done__ico"><span className="cue-icon">mark_email_read</span></div>
          <h3 className="wl-done__title">You're on the list.</h3>
          <p className="wl-done__sub">Thanks, {f.name.split(" ")[0] || "there"}. We'll be in touch at <b>{f.email}</b>.</p>
          <Button variant="secondary" size="m" onClick={onDone}>Close</Button>
        </div>
      );
    }

    return (
      <form className="wl-form" onSubmit={submit} noValidate>
        <div className="wl-form__row">
          <Input label="Full name" required value={f.name} onChange={set("name")} />
          <Input label="Email" type="email" required value={f.email} onChange={set("email")} />
        </div>
        <div className="wl-form__row">
          <Input label="Organization" value={f.organization} onChange={set("organization")} />
          <Input label="Role" placeholder="e.g. engineer, architect" value={f.role} onChange={set("role")} />
        </div>
        <div className="wl-field">
          <label className="wl-field__label">How did you find us?</label>
          <select className="wl-select" value={f.howIFoundYou} onChange={set("howIFoundYou")}>
            {HOW_OPTIONS.map((o) => <option key={o} value={o}>{o || "Select an option (optional)"}</option>)}
          </select>
        </div>

        {status === "error" ? <p className="wl-error">{err}</p> : null}

        <div className="wl-form__actions">
          <Button type="submit" variant="primary" size="l" trailingIcon={status === "sending" ? undefined : "arrow_forward"} disabled={status === "sending"}>
            {status === "sending"
              ? <span className="wl-sending"><span className="cue-icon wl-spin">progress_activity</span>Signing you up…</span>
              : "Join the waiting list"}
          </Button>
        </div>
        <p className="wl-fineprint">We'll only email you about Cue. Unsubscribe anytime.</p>
      </form>
    );
  }

  /* ---------- Modal shell ---------- */
  function WaitlistModal() {
    const [open, setOpen] = useState(false);
    useEffect(() => {
      const onOpen = () => setOpen(true);
      window.addEventListener("cue:open-waitlist", onOpen);
      return () => window.removeEventListener("cue:open-waitlist", onOpen);
    }, []);
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
      window.addEventListener("keydown", onKey);
      document.body.style.overflow = "hidden";
      return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
    }, [open]);
    if (!open) return null;
    return (
      <div className="wl-overlay" onClick={() => setOpen(false)}>
        <div className="wl-card" onClick={(e) => e.stopPropagation()}>
          <button className="wl-close" onClick={() => setOpen(false)} aria-label="Close">
            <span className="cue-icon">close</span>
          </button>
          <p className="eyebrow">Join the waiting list</p>
          <h2 className="wl-title">Be first to know.</h2>
          <p className="wl-lead">Get early access and product news. No spam — just Cue.</p>
          <WaitlistForm onDone={() => setOpen(false)} />
        </div>
      </div>
    );
  }

  /* ---------- Unsubscribe page (SPA route) ---------- */
  const REASONS = [
    "", "Too many emails", "No longer relevant", "I never signed up",
    "Content not useful", "Other",
  ];

  function Unsubscribe() {
    const [email, setEmail] = useState("");
    const [reason, setReason] = useState("");
    const [status, setStatus] = useState("idle");
    const [err, setErr] = useState("");
    useEffect(() => { window.scrollTo(0, 0); }, []);

    const submit = async (e) => {
      e.preventDefault();
      if (status === "sending") return;
      if (!email.trim()) { setErr("Please enter your email address."); setStatus("error"); return; }
      setStatus("sending"); setErr("");
      try {
        await call("unsubscribe", { email: email.trim(), deleteReason: reason || undefined });
        setStatus("done");
      } catch (e2) {
        setErr((e2 && e2.message) || "Something went wrong. Please try again.");
        setStatus("error");
      }
    };

    return (
      <main className="doc section section--canvas" data-screen-label="Unsubscribe">
        <div className="container">
          <div className="doc__wrap" style={{ maxWidth: 620 }}>
            <a className="doc__back" href="#top">
              <span className="cue-icon">arrow_back</span> Back to home
            </a>
            <h1 className="h1 doc__title">Unsubscribe</h1>

            {status === "done" ? (
              <div className="wl-done" style={{ alignItems: "flex-start", textAlign: "left" }}>
                <div className="wl-done__ico"><span className="cue-icon">unsubscribe</span></div>
                <h3 className="wl-done__title">You're unsubscribed.</h3>
                <p className="wl-done__sub"><b>{email}</b> has been removed from our mailing list. Sorry to see you go.</p>
                <a href="#top"><Button variant="secondary" size="m" leadingIcon="arrow_back">Back to home</Button></a>
              </div>
            ) : (
              <React.Fragment>
                <p className="lead doc__lead">
                  Enter your email below to remove yourself from the Cue mailing list. You can
                  rejoin at any time.
                </p>
                <form className="wl-form" onSubmit={submit} noValidate style={{ marginTop: 28 }}>
                  <Input label="Email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
                  <div className="wl-field">
                    <label className="wl-field__label">Reason (optional)</label>
                    <select className="wl-select" value={reason} onChange={(e) => setReason(e.target.value)}>
                      {REASONS.map((o) => <option key={o} value={o}>{o || "Select a reason (optional)"}</option>)}
                    </select>
                  </div>
                  {status === "error" ? <p className="wl-error">{err}</p> : null}
                  <div className="wl-form__actions">
                    <Button type="submit" variant="primary" size="l" disabled={status === "sending"}>
                      {status === "sending"
                        ? <span className="wl-sending"><span className="cue-icon wl-spin">progress_activity</span>Unsubscribing…</span>
                        : "Unsubscribe"}
                    </Button>
                  </div>
                </form>
              </React.Fragment>
            )}

            <div className="doc__divider" />
            <div className="doc__footer-row">
              <span className="doc__updated">QAECY AG · Regensdorf, Switzerland</span>
              <a href="#top"><Button variant="secondary" size="m" leadingIcon="arrow_back">Back to home</Button></a>
            </div>
          </div>
        </div>
      </main>
    );
  }

  return { WaitlistModal, Unsubscribe };
})();

window.WaitlistModal = MailingList.WaitlistModal;
window.Unsubscribe = MailingList.Unsubscribe;
