"use client";

import React, { useEffect, useState } from "react";

/**
 * NewsletterModal — site-wide popup, shown on first visit per 7-day window.
 *
 * Behavior:
 * - Renders nothing during SSR.
 * - On mount: checks localStorage["bb_newsletter_dismissed"]; if the stored
 *   timestamp is < 7 days old, stays hidden. Same for
 *   ["bb_newsletter_subscribed"] (no expiry — never re-prompt subscribers).
 * - First show is delayed ~5s so it doesn't slam the user the instant the
 *   page paints; the modal animates from a small pill into the full card
 *   via the .bb-modal-enter keyframe (defined in tailwind.css).
 * - Submit POSTs to /api/newsletter/subscribe (existing native endpoint —
 *   we already have newsletter_subscribers + an SMTP welcome flow there;
 *   if you decide to swap to Listmonk later, only this fetch URL changes).
 */

const STORAGE_DISMISS_KEY = "bb_newsletter_dismissed";
const STORAGE_SUB_KEY = "bb_newsletter_subscribed";
const DISMISS_DAYS = 7;
const INITIAL_DELAY_MS = 5000;

function shouldShow(): boolean {
  if (typeof window === "undefined") return false;
  try {
    if (window.localStorage.getItem(STORAGE_SUB_KEY)) return false;
    const raw = window.localStorage.getItem(STORAGE_DISMISS_KEY);
    if (!raw) return true;
    const expires = parseInt(raw, 10);
    if (Number.isFinite(expires) && Date.now() < expires) return false;
    return true;
  } catch {
    return true;
  }
}

export default function NewsletterModal() {
  const [open, setOpen] = useState(false);
  const [phase, setPhase] = useState<"form" | "submitting" | "success" | "error">("form");
  const [email, setEmail] = useState("");
  const [errMsg, setErrMsg] = useState<string | null>(null);

  useEffect(() => {
    if (!shouldShow()) return;
    const t = setTimeout(() => setOpen(true), INITIAL_DELAY_MS);
    return () => clearTimeout(t);
  }, []);

  // Escape closes (treat as dismiss-for-7d)
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") dismiss();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  function dismiss() {
    try {
      const exp = Date.now() + DISMISS_DAYS * 24 * 60 * 60 * 1000;
      window.localStorage.setItem(STORAGE_DISMISS_KEY, String(exp));
    } catch {}
    setOpen(false);
  }

  function markSubscribed() {
    try {
      window.localStorage.setItem(STORAGE_SUB_KEY, String(Date.now()));
    } catch {}
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErrMsg(null);
    const trimmed = email.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
      setErrMsg("Please enter a valid email address.");
      return;
    }
    setPhase("submitting");
    try {
      const r = await fetch("/api/newsletter/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: trimmed, source: "site_modal" }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok || data?.error) {
        setErrMsg(data?.error || "Something went wrong. Please try again.");
        setPhase("error");
        return;
      }
      markSubscribed();
      setPhase("success");
      // auto-close after 4s on success
      setTimeout(() => setOpen(false), 4000);
    } catch {
      setErrMsg("Network error — please try again.");
      setPhase("error");
    }
  }

  if (!open) return null;

  return (
    <div
      className="bb-modal-backdrop"
      role="dialog"
      aria-modal="true"
      aria-labelledby="bb-newsletter-heading"
      onMouseDown={(e) => {
        // backdrop click = dismiss (only if clicking the backdrop, not the card)
        if (e.target === e.currentTarget) dismiss();
      }}
    >
      <div className="bb-modal-card bb-modal-enter">
        <button
          type="button"
          aria-label="Close"
          className="bb-modal-close"
          onClick={dismiss}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        </button>

        {/* Header — accent rule + small label */}
        <div className="bb-modal-eyebrow">
          <span className="bb-modal-eyebrow-dot" aria-hidden="true" />
          <span>AV Beat Newsletter</span>
        </div>

        <h2 id="bb-newsletter-heading" className="bb-modal-heading">
          Get the latest in pro AV &amp; live production
        </h2>

        {phase !== "success" && (
          <p className="bb-modal-sub">
            Pro AV news, gear reviews, and deep-dives from InfoComm to ISE — direct to your inbox.
            One email a week, no spam.
          </p>
        )}

        {phase === "success" ? (
          <div className="bb-modal-success">
            <div className="bb-modal-success-icon" aria-hidden="true">
              <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12" />
              </svg>
            </div>
            <h3 className="bb-modal-success-title">Check your email</h3>
            <p className="bb-modal-success-msg">
              We&rsquo;ve sent a confirmation to <strong>{email}</strong>. Click the link to
              start receiving the newsletter.
            </p>
          </div>
        ) : (
          <form className="bb-modal-form" onSubmit={handleSubmit}>
            <label className="bb-modal-label" htmlFor="bb-newsletter-email">Work email</label>
            <input
              id="bb-newsletter-email"
              type="email"
              autoComplete="email"
              required
              placeholder="you@broadcaster.com"
              value={email}
              onChange={(e) => { setEmail(e.target.value); setErrMsg(null); }}
              disabled={phase === "submitting"}
              className="bb-modal-input"
              autoFocus
            />
            {errMsg && <div className="bb-modal-err">{errMsg}</div>}

            <div className="bb-modal-actions">
              <button
                type="button"
                onClick={dismiss}
                className="bb-modal-btn-secondary"
                disabled={phase === "submitting"}
              >
                Not now
              </button>
              <button
                type="submit"
                className="bb-modal-btn-primary"
                disabled={phase === "submitting"}
              >
                {phase === "submitting" ? "Subscribing…" : "Subscribe"}
              </button>
            </div>

            <p className="bb-modal-fineprint">
              By subscribing you&apos;ll also be added to the daily newsletters for our
              sister publications — Broadcast Beat, BroadcastEngineering.com, Sports
              Media Beat, and The Crew Grid. Unsubscribe from any one (or all) anytime.
            </p>
          </form>
        )}
      </div>
    </div>
  );
}
