/* MCA — Newsletter subscription popup
   Shows once, 50s after the visitor lands. Saves name + email to a
   Google Sheet via a Google Apps Script web app endpoint.

   SETUP (one time):
   1. Open the target Google Sheet.
   2. Extensions ▸ Apps Script. Paste the script from README-newsletter.md.
   3. Deploy ▸ New deployment ▸ Web app ▸ Execute as "Me",
      Access "Anyone". Copy the /exec URL.
   4. Paste that URL into SHEET_ENDPOINT below. */

const SHEET_ENDPOINT = ""; // ← paste your Apps Script /exec URL here

const {
  useState: useStateNL,
  useEffect: useEffectNL,
  useRef: useRefNL,
} = React;

const NL_DELAY_MS = 30000;       // 30 seconds
const NL_STORAGE_KEY = "mca-newsletter-v1"; // "subscribed" | "dismissed"

function NewsletterIcon({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <rect x="3" y="5" width="18" height="14" rx="2.5" stroke="currentColor" strokeWidth="1.6" />
      <path d="M4 7l8 6 8-6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function CheckIcon({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function NewsletterPopup() {
  const [open, setOpen] = useStateNL(false);
  const [name, setName] = useStateNL("");
  const [email, setEmail] = useStateNL("");
  const [status, setStatus] = useStateNL("idle"); // idle | sending | done | error
  const [errorMsg, setErrorMsg] = useStateNL("");
  const emailRef = useRefNL(null);

  // Schedule the popup once per visitor.
  useEffectNL(() => {
    let seen = null;
    try { seen = localStorage.getItem(NL_STORAGE_KEY); } catch (e) {}
    if (seen) return;
    const t = setTimeout(() => setOpen(true), NL_DELAY_MS);
    return () => clearTimeout(t);
  }, []);

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

  const dismiss = () => {
    setOpen(false);
    try { localStorage.setItem(NL_STORAGE_KEY, "dismissed"); } catch (e) {}
  };

  const validEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());

  async function submit(e) {
    if (e) e.preventDefault();
    if (status === "sending") return;
    if (!name.trim()) { setErrorMsg("Please enter your name."); return; }
    if (!validEmail(email)) { setErrorMsg("Please enter a valid email."); return; }
    setErrorMsg("");
    setStatus("sending");

    const payload = new FormData();
    payload.append("name", name.trim());
    payload.append("email", email.trim());
    payload.append("source", "website-popup");
    payload.append("page", window.location.href);
    payload.append("ts", new Date().toISOString());

    try {
      if (SHEET_ENDPOINT) {
        // no-cors: Apps Script accepts the POST; we can't read the response,
        // but the row is written. Treat a completed request as success.
        await fetch(SHEET_ENDPOINT, { method: "POST", mode: "no-cors", body: payload });
      }
      setStatus("done");
      try { localStorage.setItem(NL_STORAGE_KEY, "subscribed"); } catch (err) {}
      setTimeout(() => setOpen(false), 2600);
    } catch (err) {
      setStatus("error");
      setErrorMsg("Something went wrong. Please try again.");
    }
  }

  if (!open) return null;

  return (
    <div className="nl-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) dismiss(); }}>
      <div className="nl-card" role="dialog" aria-modal="true" aria-label="Subscribe to MCA insights">
        <button className="nl-close" onClick={dismiss} aria-label="Close">
          <svg width="15" height="15" viewBox="0 0 15 15" fill="none">
            <path d="M2 2L13 13M13 2L2 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
          </svg>
        </button>

        {status === "done" ? (
          <div className="nl-success">
            <span className="nl-mark"><CheckIcon /></span>
            <h2 className="nl-title">You're on the list.</h2>
            <p className="nl-sub" style={{ marginBottom: 0 }}>
              Thanks, {name.trim().split(" ")[0] || "there"}. We'll be in touch with MCA insights soon.
            </p>
          </div>
        ) : (
          <React.Fragment>
            <span className="nl-mark"><NewsletterIcon /></span>
            <p className="nl-eyebrow">MCA Newsletter</p>
            <h2 className="nl-title">Join the MCA Community</h2>
            <p className="nl-sub">
              Explore the latest insights and market updates on AI, Blockchain, and emerging technologies.
            </p>

            <form onSubmit={submit} noValidate>
              <div className="nl-field">
                <input
                  className={`nl-input ${errorMsg && !name.trim() ? "nl-input--error" : ""}`}
                  type="text"
                  placeholder="Your name"
                  value={name}
                  autoComplete="name"
                  onChange={(e) => setName(e.target.value)}
                />
              </div>
              <div className="nl-field">
                <input
                  ref={emailRef}
                  className={`nl-input ${errorMsg && !validEmail(email) ? "nl-input--error" : ""}`}
                  type="email"
                  placeholder="Email address"
                  value={email}
                  autoComplete="email"
                  onChange={(e) => setEmail(e.target.value)}
                />
              </div>

              <button className="nl-submit" type="submit" disabled={status === "sending"}>
                {status === "sending"
                  ? <React.Fragment><span className="nl-spinner"></span> Subscribing…</React.Fragment>
                  : "Subscribe"}
              </button>

              {errorMsg && <p className="nl-error">{errorMsg}</p>}
            </form>

            <p className="nl-fineprint">We respect your inbox. Unsubscribe anytime.</p>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

window.NewsletterPopup = NewsletterPopup;
