/* global React */
const { useState: useStateN, useEffect: useEffectN } = React;

/* NewsletterModal — first-visit signup popup.
   Mirrors the splash-page form: single email step → thank-you with OPA gift.
   Suppressed once dismissed/subscribed via localStorage. */
function NewsletterModal() {
  const [open, setOpen] = useStateN(false);
  const [email, setEmail] = useStateN("");
  const [step, setStep] = useStateN("form"); // form | sent

  // Auto-open once per session unless already subscribed
  useEffectN(() => {
    if (typeof localStorage === "undefined") return;
    if (localStorage.getItem("dh-newsletter-subscribed")) return;
    if (typeof sessionStorage !== "undefined" && sessionStorage.getItem("dh-newsletter-shown")) return;
    const t = setTimeout(() => {
      setOpen(true);
      try { sessionStorage.setItem("dh-newsletter-shown", "1"); } catch (err) {}
    }, 30000);
    return () => clearTimeout(t);
  }, []);

  // Listen for explicit open requests (footer "Stay in the know" link)
  useEffectN(() => {
    const onOpen = () => { setStep("form"); setOpen(true); };
    window.addEventListener("dh-open-newsletter", onOpen);
    return () => window.removeEventListener("dh-open-newsletter", onOpen);
  }, []);

  useEffectN(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const close = () => {
    setOpen(false);
  };

  // Send the subscriber to Mailchimp via a hidden form + iframe (no CORS issues).
  // Mailchimp audience: Dimi's Greek House Newsletter (us14).
  const sendToMailchimp = () => {
    const ACTION = "https://dimisgreekhouse.us14.list-manage.com/subscribe/post?u=bfd2eb4ad3c30d4797423a914&id=ca08a24442&f_id=0043b5e5f0";
    const HONEYPOT = "b_bfd2eb4ad3c30d4797423a914_ca08a24442";
    try {
      let iframe = document.getElementById("dh-mc-sink");
      if (!iframe) {
        iframe = document.createElement("iframe");
        iframe.name = "dh-mc-sink";
        iframe.id = "dh-mc-sink";
        iframe.style.display = "none";
        document.body.appendChild(iframe);
      }
      const form = document.createElement("form");
      form.action = ACTION;
      form.method = "post";
      form.target = "dh-mc-sink";
      form.style.display = "none";

      const add = (name, value) => {
        const input = document.createElement("input");
        input.type = "text";
        input.name = name;
        input.value = value;
        form.appendChild(input);
      };
      add("EMAIL", email);
      add(HONEYPOT, ""); // bot honeypot — must stay empty

      document.body.appendChild(form);
      form.submit();
      setTimeout(() => { form.remove(); }, 1000);
    } catch (err) {
      // fail silently — the confirmation still shows so the guest isn't blocked
    }
  };

  const submitEmail = (e) => {
    if (e) e.preventDefault();
    if (!email || !email.includes("@")) return;
    sendToMailchimp();
    setStep("sent");
    try { localStorage.setItem("dh-newsletter-subscribed", "1"); } catch (err) {}
  };

  if (!open) return null;

  return (
    <div className="dh-modal" role="dialog" aria-modal="true" aria-labelledby="dh-news-title">
      <div className="dh-modal-scrim" onClick={close} />
      <div className="dh-modal-panel" style={{ width: "min(460px, 100%)", padding: "32px 36px 28px", textAlign: "center" }}>
        <button className="dh-modal-close" aria-label="Close" onClick={close}>×</button>

        {step === "sent" ? (
          <div className="dh-modal-confirm">
            <div className="dh-plate-spin" aria-hidden="true">
              <svg width="56" height="56" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M14 34 L28 46 L50 20" />
              </svg>
            </div>
            <h3 className="dh-modal-title" id="dh-news-title">Thank you!</h3>
            <p style={{
              fontFamily: "var(--font-body)",
              fontSize: 16,
              lineHeight: 1.55,
              color: "var(--ink-700)",
              margin: "0 auto 8px",
              maxWidth: 360
            }}>
              You’re all set. We’ll be in touch when we have something worth sharing.
            </p>
            <button className="dh-btn dh-btn-ghost" onClick={close} style={{ marginTop: 10 }}>Close</button>
          </div>
        ) : (
          <>
            <span className="dh-eyebrow" style={{ marginBottom: 10 }}>Join our list</span>
            <h3 id="dh-news-title" style={{
              fontFamily: "var(--font-display)",
              fontWeight: 600,
              fontSize: 40,
              lineHeight: 1,
              letterSpacing: ".03em",
              textTransform: "uppercase",
              color: "var(--olive-900)",
              margin: "0 0 14px"
            }}>
              Stay in the Know
            </h3>
            <p style={{
              fontFamily: "var(--font-body)",
              fontStyle: "italic",
              fontSize: 16,
              lineHeight: 1.5,
              color: "var(--ink-700)",
              margin: "0 auto 22px",
              maxWidth: 360
            }}>
              Be the first to hear about seasonal menus, special events, happy hour updates, and exclusive offers from Dimi’s Greek House.
            </p>

            <form onSubmit={submitEmail} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <input
                type="email"
                required
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="dh-input"
                style={{ textAlign: "center" }}
                autoFocus
              />
              <button
                type="submit"
                className="dh-btn dh-btn-primary"
                style={{ justifyContent: "center" }}
                onClick={(e) => {
                  // belt-and-suspenders: if native submit doesn't fire, advance manually
                  if (email && email.includes("@")) {
                    e.preventDefault();
                    submitEmail();
                  }
                }}
              >
                Sign me up
              </button>
              <p style={{
                fontFamily: "var(--font-body)",
                fontSize: 12,
                color: "var(--ink-500)",
                margin: "2px 0 0"
              }}>
                No spam, ever. Unsubscribe any time.
              </p>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

window.NewsletterModal = NewsletterModal;
