"use client";

import { useEffect, useRef, useState } from "react";
import Script from "next/script";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import { gaEvent } from "../../../lib/ga";
import { type SupportedLocale } from "../../../lib/locale";

const copy: Record<SupportedLocale, Record<string, string>> = {
  pl: {
    invalidEmail: "Podaj poprawny adres e-mail",
    captchaLoadingError: "reCAPTCHA jeszcze się ładuje. Spróbuj ponownie za chwilę.",
    captchaRequired: "Potwierdź reCAPTCHA",
    signupError: "Błąd zapisu do newslettera",
    sendError: "Błąd wysyłki. Sprawdź połączenie i spróbuj ponownie.",
    success: "Zapisano do newslettera",
    imageAlt: "Tło newslettera",
    title: "Zapisz się do newslettera",
    subtitle: "Otrzymuj informacje o nowościach, promocjach i inspiracjach.",
    placeholder: "Twój adres e-mail",
    loadingSecurity: "Ładowanie zabezpieczenia...",
    sending: "Wysyłanie...",
    submit: "Zapisz się",
    policyPrefix: "Klikając „Zapisz się”, akceptujesz naszą",
    policyLink: "politykę prywatności",
    policySuffix: ". W każdej chwili możesz wypisać się z newslettera.",
  },
  en: {
    invalidEmail: "Enter a valid email address",
    captchaLoadingError: "reCAPTCHA is still loading. Please try again in a moment.",
    captchaRequired: "Please confirm reCAPTCHA",
    signupError: "Newsletter signup failed",
    sendError: "Sending failed. Check your connection and try again.",
    success: "You have been subscribed to the newsletter",
    imageAlt: "Newsletter background",
    title: "Subscribe to the newsletter",
    subtitle: "Receive updates, promotions and inspiration.",
    placeholder: "Your email address",
    loadingSecurity: "Loading security check...",
    sending: "Sending...",
    submit: "Subscribe",
    policyPrefix: "By clicking “Subscribe”, you accept our",
    policyLink: "privacy policy",
    policySuffix: ". You can unsubscribe from the newsletter at any time.",
  },
  de: {
    invalidEmail: "Gib eine gültige E-Mail-Adresse ein",
    captchaLoadingError: "reCAPTCHA wird noch geladen. Bitte versuche es gleich erneut.",
    captchaRequired: "Bitte bestätige reCAPTCHA",
    signupError: "Newsletter-Anmeldung fehlgeschlagen",
    sendError: "Senden fehlgeschlagen. Prüfe deine Verbindung und versuche es erneut.",
    success: "Du wurdest für den Newsletter angemeldet",
    imageAlt: "Newsletter-Hintergrund",
    title: "Newsletter abonnieren",
    subtitle: "Erhalte Neuigkeiten, Aktionen und Inspirationen.",
    placeholder: "Deine E-Mail-Adresse",
    loadingSecurity: "Sicherheitsprüfung wird geladen...",
    sending: "Wird gesendet...",
    submit: "Abonnieren",
    policyPrefix: "Mit Klick auf „Abonnieren“ akzeptierst du unsere",
    policyLink: "Datenschutzerklärung",
    policySuffix: ". Du kannst dich jederzeit vom Newsletter abmelden.",
  },
};

function isValidEmail(value: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}

declare global {
  interface Window {
    grecaptcha: any;
  }
}

export default function NewsletterModalContent({
  locale = "pl",
}: {
  locale?: SupportedLocale;
}) {
  const t = copy[locale];
  const [email, setEmail] = useState("");
  const [alertMessage, setAlertMessage] = useState("");
  const [alertType, setAlertType] = useState<"success" | "error">("success");
  const [loading, setLoading] = useState(false);
  const [captchaLoaded, setCaptchaLoaded] = useState(false);

  const captchaRef = useRef<HTMLDivElement | null>(null);
  const captchaWidgetIdRef = useRef<number | null>(null);
  const hasViewedRef = useRef(false);

  const showAlert = (message: string, type: "success" | "error") => {
    setAlertMessage(message);
    setAlertType(type);

    setTimeout(() => {
      setAlertMessage("");
    }, 4000);
  };

  useEffect(() => {
    if (hasViewedRef.current) return;
    hasViewedRef.current = true;

    gaEvent("newsletter_modal_view", { locale });
  }, [locale]);

  useEffect(() => {
    let interval: ReturnType<typeof setInterval> | null = null;

    const renderCaptcha = () => {
      if (!captchaRef.current) return;
      if (!window.grecaptcha?.render) return;
      if (captchaWidgetIdRef.current !== null) return;

      captchaWidgetIdRef.current = window.grecaptcha.render(captchaRef.current, {
        sitekey: "6Lf1KHQUAAAAAFNKEX1hdSWCS3mRMv4FlFaNslaD",
      });

      setCaptchaLoaded(true);

      if (interval) clearInterval(interval);
    };

    renderCaptcha();
    interval = setInterval(renderCaptcha, 300);

    return () => {
      if (interval) clearInterval(interval);
    };
  }, []);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    gaEvent("newsletter_submit_attempt", {
      filled: Boolean(email),
      length: email.length,
      locale,
    });

    if (!isValidEmail(email)) {
      showAlert(t.invalidEmail, "error");
      return;
    }

    if (captchaWidgetIdRef.current === null) {
      showAlert(t.captchaLoadingError, "error");
      return;
    }

    const captcha = window.grecaptcha?.getResponse?.(captchaWidgetIdRef.current);

    if (!captcha) {
      showAlert(t.captchaRequired, "error");
      return;
    }

    setLoading(true);

    try {
      const formData = new URLSearchParams();

      formData.append("fields[email]", email);
      formData.append("ml-submit", "1");
      formData.append("anticsrf", "true");
      formData.append("g-recaptcha-response", captcha);

      const res = await fetch(
        "https://assets.mailerlite.com/jsonp/1606471/forms/186017179114669245/subscribe",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: formData.toString(),
        }
      );

      const data = await res.json().catch(() => null);

      if (!res.ok) {
        showAlert(`Błąd zapisu: ${res.status}`, "error");
        return;
      }

      if (data?.success !== true) {
        const errorMessage = data?.errors?.email?.[0] || data?.message || t.signupError;
        showAlert(errorMessage, "error");
        return;
      }

      gaEvent("newsletter_submit_success", {
        domain: email.split("@")[1] || "unknown",
        locale,
      });

      setEmail("");
      window.grecaptcha?.reset?.(captchaWidgetIdRef.current);

      showAlert(t.success, "success");
    } catch (err) {
      console.error(err);
      showAlert(t.sendError, "error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Script
        src="https://www.google.com/recaptcha/api.js?render=explicit"
        strategy="afterInteractive"
      />

      <AnimatePresence>
        {alertMessage && (
          <motion.div
            initial={{ opacity: 0, y: -30 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -30 }}
            className={`fixed top-6 left-1/2 transform -translate-x-1/2 z-50 text-white px-6 py-3 rounded-xl shadow-xl backdrop-blur-md ${
              alertType === "success" ? "bg-green-600/90" : "bg-red-600/90"
            }`}
          >
            {alertMessage}
          </motion.div>
        )}
      </AnimatePresence>

      <motion.div
        onClick={(e) => e.stopPropagation()}
        className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl overflow-hidden shadow-2xl w-full max-w-xl mx-auto text-white"
        initial={{ opacity: 0, scale: 0.95, y: 30 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
      >
        <div className="relative w-full h-48">
          <Image
            src="/IMG_0773.JPG"
            alt={t.imageAlt}
            fill
            className="object-cover brightness-75"
          />
          <div className="absolute inset-0 bg-black/50" />
          <div className="absolute inset-0 flex flex-col items-center justify-center text-center px-4">
            <h2 className="text-3xl font-bold">{t.title}</h2>
            <p className="text-white/70 mt-2 text-sm max-w-md">{t.subtitle}</p>
          </div>
        </div>

        <motion.form className="p-6 flex flex-col gap-4" onSubmit={handleSubmit}>
          <input
            type="email"
            name="fields[email]"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            placeholder={t.placeholder}
            autoComplete="email"
            aria-label="email"
            aria-required="true"
            className="bg-white/10 border border-white/20 placeholder-white/50 text-white px-4 py-2 rounded-md focus:outline-none focus:ring-2 focus:ring-[#eea71f]"
          />

          <div className="flex justify-center min-h-[78px]">
            {!captchaLoaded && (
              <span className="text-xs text-white/40">{t.loadingSecurity}</span>
            )}
            <div ref={captchaRef} />
          </div>

          <button
            type="submit"
            disabled={loading || !captchaLoaded}
            className="mt-2 border border-[#eea71f] text-sm font-medium px-6 py-2 rounded-full bg-[#eea71f]/10 hover:bg-[#eea71f]/30 transition disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {loading ? t.sending : !captchaLoaded ? t.loadingSecurity : t.submit}
          </button>

          <p className="text-center text-xs text-white/50 leading-relaxed">
            {t.policyPrefix}{" "}
            <a
              href="/polityka-prywatnosci.html"
              className="text-[#eea71f] underline hover:text-[#f5c05d]"
            >
              {t.policyLink}
            </a>
            {t.policySuffix}
          </p>
        </motion.form>
      </motion.div>
    </>
  );
}
