import { useState, type FormEvent } from 'react';
import { Check, ShieldCheck, Gift, ArrowRight, Loader2 } from 'lucide-react';
import { cn } from '../lib/utils';
import { useT, getLang } from '../i18n';
import { trackLead } from '../utils/trackLead';

export default function Offer() {
  const t = useT();
  const benefits = t.offer.benefits;

  const [email, setEmail] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const getCookie = (name: string) => {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    return match ? match[2] : '';
  };

  const handleCheckout = async (e: FormEvent) => {
    e.preventDefault();
    if (!email) { setError(t.offer.errEmpty); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setError(t.offer.errInvalid); return; }

    if (typeof window !== 'undefined' && 'fbq' in window) {
      (window as any).fbq('track', 'InitiateCheckout');
    }

    setIsLoading(true);
    setError('');

    const isBR = getLang() === 'pt';
    trackLead(email, isBR ? 'landing' : 'landing-international', 'Starter');

    if (!isBR) {
      // Internacional: Starter USD $6.99 → Stripe direto
      try {
        const res = await fetch('https://n8n.seureview.com.br/webhook/festa-magica-stripe', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            action: 'create-checkout',
            source: 'landing-international',
            userEmail: email,
            priceId: 'price_1TkZWrLjQo8Mvvq1wmXQOFFq',
            credits: 10,
            planName: 'Starter',
            fbp: getCookie('_fbp'),
            fbc: getCookie('_fbc'),
            successUrl: 'https://festamagicaia.com.br?payment=success',
            cancelUrl: window.location.href,
          }),
        });
        const data = await res.json();
        if (data.url) {
          window.location.href = data.url;
        } else {
          setError(t.offer.errCheckout);
          setIsLoading(false);
        }
      } catch {
        setError(t.offer.errConnection);
        setIsLoading(false);
      }
      return;
    }

    // PT-BR: checkout transparente com Pix + Cartão
    window.location.href = `https://festamagicaia.com.br/checkout?plan=starter&source=landing&email=${encodeURIComponent(email)}`;
  };

  return (
    <section className="py-24 bg-indigo-950 relative overflow-hidden" id="oferta">
      <div className="absolute top-0 right-0 w-full h-full bg-[url('https://s3.seureview.com.br/festamagica/6a591904-cf2a-4a51-8581-1891373eea29/805441e0-925e-4674-b7b3-ba640431eeb1/adesivos-redondos.webp')] bg-cover bg-center opacity-5 mix-blend-overlay" />
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] bg-pink-500/20 blur-[130px] rounded-full pointer-events-none mix-blend-screen" />

      <div className="container mx-auto px-6 max-w-5xl relative z-10">
        <div className="text-center mb-16">
          <h2 className="text-4xl md:text-5xl font-display font-bold mb-4 text-white">
            {t.offer.title1} <br className="hidden md:block"/><span className="text-pink-400">{t.offer.titleHighlight}</span>
          </h2>
          <p className="text-indigo-200 text-lg" dangerouslySetInnerHTML={{ __html: t.offer.subtitle }} />
        </div>

        <div className="bg-white rounded-[2.5rem] p-8 md:p-12 shadow-[0_30px_60px_-15px_rgba(236,72,153,0.3)] relative overflow-hidden flex flex-col md:flex-row items-center gap-12 max-w-4xl mx-auto border border-pink-100">

          <div className="flex-1 w-full">
            <h3 className="text-3xl font-display font-bold text-indigo-950 mb-6">
              {t.offer.kitName}
            </h3>
            <div className="space-y-4 mb-8">
              {benefits.map((benefit, i) => (
                <div key={i} className="flex items-center gap-4">
                  <div className="w-6 h-6 rounded-full bg-pink-100 flex items-center justify-center shrink-0">
                    <Check className="w-4 h-4 text-pink-600" strokeWidth={3} />
                  </div>
                  <span className="text-indigo-900 font-medium text-lg leading-relaxed">{benefit}</span>
                </div>
              ))}
            </div>

            <div className="pt-6 border-t border-indigo-100 flex items-center gap-3">
              <Gift className="w-6 h-6 text-pink-500" />
              <p className="text-indigo-800 font-bold">{t.offer.surprise}</p>
            </div>
          </div>

          <div className="w-full md:w-[360px] rounded-3xl p-6 md:p-8 text-center flex flex-col justify-center relative bg-gradient-to-b from-indigo-50 to-white border border-indigo-100 shadow-inner">
            <div className="mb-3 text-pink-600 font-bold text-sm tracking-[0.2em] uppercase">{t.offer.packLabel}</div>

            <p className="text-xs text-indigo-400 font-medium mb-2">{t.offer.anchor}</p>

            <div className="flex items-start justify-center mb-1">
              <span className="text-2xl font-bold text-indigo-950 mt-2 mr-1">{t.offer.priceCurrency}</span>
              <span className="text-8xl font-display font-black tracking-tight text-indigo-950">{t.offer.priceInteger}</span>
              <span className="text-2xl font-bold mb-1 text-indigo-950 mt-2">{t.offer.priceDecimals}</span>
            </div>
            <p className="text-sm text-indigo-500 font-medium mb-4">{t.offer.priceNote}</p>

            <div className="mb-6 px-4 py-3 rounded-2xl bg-emerald-50 border border-emerald-100 flex items-start gap-2.5 text-left">
              <Gift className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
              <p className="text-sm text-emerald-800 font-semibold leading-snug">
                {t.offer.freeImage}
              </p>
            </div>

            <form onSubmit={handleCheckout} className="flex flex-col gap-3 w-full mb-4">
              <div className="flex flex-col gap-1 text-left">
                <input
                  type="email"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    if (error) setError('');
                  }}
                  placeholder={t.offer.emailPlaceholder}
                  className={cn(
                    "w-full h-14 px-5 rounded-full border-2 bg-white outline-none transition-all placeholder:text-gray-400 font-medium",
                    error ? "border-red-400 focus:border-red-500" : "border-indigo-100 focus:border-pink-500/50"
                  )}
                  disabled={isLoading}
                />
                {error && <span className="text-red-500 text-xs px-2 font-medium">{error}</span>}
              </div>
              <button
                type="submit"
                disabled={isLoading}
                className="w-full h-16 rounded-full bg-gradient-to-r from-pink-500 to-violet-500 text-white font-bold text-lg hover:shadow-[0_0_30px_rgba(236,72,153,0.5)] hover:scale-105 transition-all flex items-center justify-center gap-2 disabled:opacity-70 disabled:hover:scale-100 disabled:hover:shadow-none"
              >
                {isLoading ? (
                  <>{t.offer.buttonLoading} <Loader2 className="w-5 h-5 animate-spin" /></>
                ) : (
                  <>{t.offer.buttonIdle} <ArrowRight className="w-5 h-5" /></>
                )}
              </button>
            </form>

            <div className="flex items-center justify-center gap-2 text-sm text-indigo-400 font-medium">
              <ShieldCheck className="w-5 h-5 text-emerald-500" />
              <span>{t.offer.secure}</span>
            </div>
          </div>

        </div>
      </div>
    </section>
  );
}
