"use client";

import { useEffect, useState } from "react";
import { X, Mail } from "lucide-react";

const STORAGE_KEY = "mawidi_early_email_prompt_dismissed";

// Helper to get CSRF token from cookie (set by /api/csrf)
function getCSRFToken(): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(/csrf-token=([^;]+)/);
  return match ? decodeURIComponent(match[1]) : null;
}

interface EarlyEmailCaptureProps {
  language: "en" | "ar";
  variant?: "newsletter" | "demo";
}

export default function EarlyEmailCapture({
  language,
  variant = "newsletter",
}: EarlyEmailCaptureProps) {
  const [open, setOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState({ name: "", email: "" });
  const [csrfReady, setCsrfReady] = useState(false);

  // Initialize CSRF token when component mounts
  useEffect(() => {
    fetch("/api/csrf")
      .then(() => setCsrfReady(true))
      .catch(() => setCsrfReady(true)); // Continue anyway, will fail gracefully
  }, []);

  useEffect(() => {
    if (
      typeof navigator !== "undefined" &&
      (navigator as { doNotTrack?: string }).doNotTrack === "1"
    ) {
      return;
    }

    const dismissed =
      typeof localStorage !== "undefined" && localStorage.getItem(STORAGE_KEY);
    if (dismissed) return;

    const timer = setTimeout(() => setOpen(true), 15000);
    const onScroll = () => {
      if (window.scrollY > 200) {
        setOpen(true);
        window.removeEventListener("scroll", onScroll);
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      clearTimeout(timer);
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  const handleClose = () => {
    setOpen(false);
    setError(null);
    try {
      localStorage.setItem(STORAGE_KEY, "1");
    } catch {
      // ignore
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const csrfToken = getCSRFToken();
      if (!csrfToken) {
        // Try to fetch CSRF token again
        await fetch("/api/csrf");
      }
      const token = getCSRFToken();

      const response = await fetch("/api/leads/capture", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(token && { "x-csrf-token": token }),
        },
        body: JSON.stringify({
          name: form.name || "Website visitor",
          email: form.email,
          company: "",
          variant,
          language,
        }),
      });

      if (!response.ok) {
        const body = await response.json().catch(() => ({}));
        throw new Error(body?.error || "Unable to save your email right now");
      }

      setSuccess(true);
      localStorage.setItem(STORAGE_KEY, "1");
    } catch (err) {
      const message =
        err instanceof Error ? err.message : "Something went wrong";
      setError(message);
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  const isRTL = language === "ar";

  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center sm:items-center">
      <div
        className="absolute inset-0 bg-black/40 backdrop-blur-sm"
        onClick={handleClose}
      />
      <div
        className="relative w-full max-w-md mx-3 rounded-2xl bg-white p-6 shadow-2xl ring-1 ring-gray-200"
        dir={isRTL ? "rtl" : "ltr"}
      >
        <button
          onClick={handleClose}
          className="absolute right-3 top-3 rounded-full p-2 text-gray-400 hover:bg-gray-100"
          aria-label="Close"
        >
          <X className="h-4 w-4" />
        </button>

        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-emerald-50 text-emerald-600">
            <Mail className="h-5 w-5" />
          </div>
          <div>
            <p className="text-sm font-semibold text-gray-900">
              {isRTL ? "ابقَ على اطلاع" : "Stay in the loop"}
            </p>
            <p className="text-xs text-gray-500">
              {isRTL
                ? "سنرسل لك أبرز الميزات وتحديثات الأسعار (يمكنك الإلغاء بأي وقت)."
                : "We’ll send you key product updates and pricing changes (unsubscribe anytime)."}
            </p>
          </div>
        </div>

        <form className="mt-4 space-y-3" onSubmit={handleSubmit}>
          {!success && (
            <>
              <div className="grid gap-2">
                <label className="text-sm font-medium text-gray-700">
                  {isRTL ? "البريد الإلكتروني" : "Email"}
                </label>
                <input
                  type="email"
                  name="email"
                  required
                  autoComplete="email"
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-100"
                  placeholder={isRTL ? "you@example.com" : "you@example.com"}
                />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium text-gray-700">
                  {isRTL ? "الاسم (اختياري)" : "Name (optional)"}
                </label>
                <input
                  type="text"
                  name="name"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-100"
                  placeholder={isRTL ? "اسمك" : "Your name"}
                />
              </div>

              {error && <p className="text-sm text-red-600">{error}</p>}

              <div className="flex items-start gap-2 text-xs text-gray-500">
                <span className="mt-1 inline-block h-2 w-2 rounded-full bg-emerald-500" />
                <p>
                  {isRTL
                    ? "نحترم الخصوصية. بالمتابعة، توافق على تلقي البريد وتأكيد الخصوصية."
                    : "We respect privacy. By continuing, you agree to receive email and acknowledge our privacy notice."}
                </p>
              </div>

              <button
                type="submit"
                disabled={submitting}
                className="w-full rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-emerald-700 disabled:opacity-60"
              >
                {submitting
                  ? isRTL
                    ? "جارٍ الإرسال..."
                    : "Sending..."
                  : isRTL
                    ? "أرسل لي التحديثات"
                    : "Send me updates"}
              </button>
            </>
          )}

          {success && (
            <div className="space-y-2 text-sm text-gray-700">
              <p className="font-semibold text-emerald-700">
                {isRTL ? "تم الحفظ" : "You’re on the list"}
              </p>
              <p>
                {isRTL
                  ? "سنخبرك بالميزات والعروض الجديدة. يمكنك الإلغاء في أي وقت."
                  : "We’ll email you product updates and offers. You can unsubscribe anytime."}
              </p>
              <button
                type="button"
                onClick={handleClose}
                className="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                {isRTL ? "إغلاق" : "Close"}
              </button>
            </div>
          )}
        </form>
      </div>
    </div>
  );
}
