'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Mail, Send, CheckCircle, Loader2, Sparkles } from 'lucide-react';
import { VOCAB } from '@/lib/white-label/constants';

interface NewsletterSignupProps {
  variant?: 'footer' | 'inline' | 'hero';
  source?: string;
}

export function NewsletterSignup({ variant = 'footer', source = 'footer' }: NewsletterSignupProps) {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [message, setMessage] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || status === 'loading') return;

    setStatus('loading');
    try {
      const res = await fetch('/api/newsletter', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, source })
      });
      const data = await res.json();
      
      if (data.success) {
        setStatus('success');
        setMessage(data.message);
        setEmail('');
      } else {
        setStatus('error');
        setMessage(data.error || 'Something went wrong');
      }
    } catch {
      setStatus('error');
      setMessage('Connection failed. Try again.');
    }

    // Reset after 4 seconds
    setTimeout(() => {
      setStatus('idle');
      setMessage('');
    }, 4000);
  };

  if (variant === 'footer') {
    return (
      <div className="w-full max-w-md">
        <div className="flex items-center gap-2 mb-3">
          <Sparkles className="w-4 h-4 text-brand" />
          <span className="text-sm font-semibold text-white">Get the {VOCAB.brief}</span>
        </div>
        <p className="text-xs text-gray-400 mb-3">
          Weekly AI-generated intel: market moves, ops metrics, and what the Ghosts caught.
        </p>
        <form onSubmit={handleSubmit} className="flex gap-2">
          <div className="relative flex-1">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="your@email.com"
              disabled={status === 'loading' || status === 'success'}
              className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50 focus:ring-1 focus:ring-brand-deep/25 transition-all disabled:opacity-50"
            />
          </div>
          <button
            type="submit"
            disabled={status === 'loading' || status === 'success' || !email}
            className="px-4 py-2 bg-brand-deep/20 hover:bg-brand-deep/30 border border-brand-deep/30 rounded-lg text-brand text-sm font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {status === 'loading' ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : status === 'success' ? (
              <CheckCircle className="w-4 h-4" />
            ) : (
              <Send className="w-4 h-4" />
            )}
          </button>
        </form>
        <AnimatePresence>
          {message && (
            <motion.p
              initial={{ opacity: 0, y: -5 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              className={`text-xs mt-2 ${
                status === 'success' ? 'text-green-400' : 'text-red-400'
              }`}
            >
              {message}
            </motion.p>
          )}
        </AnimatePresence>
      </div>
    );
  }

  // Hero/inline variant - more prominent
  return (
    <div className="w-full max-w-lg mx-auto">
      <div className="glass-card p-6 rounded-xl border border-brand-deep/20">
        <div className="flex items-center justify-center gap-2 mb-2">
          <Sparkles className="w-5 h-5 text-brand" />
          <span className="text-lg font-bold text-white">The {VOCAB.brief}</span>
        </div>
        <p className="text-sm text-gray-300 text-center mb-4">
          Weekly AI-generated executive intel — market signals, ops health, and proactive insights delivered every Monday.
        </p>
        <form onSubmit={handleSubmit} className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="your@email.com"
              disabled={status === 'loading' || status === 'success'}
              className="w-full pl-12 pr-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50 focus:ring-2 focus:ring-brand-deep/25 transition-all disabled:opacity-50"
            />
          </div>
          <button
            type="submit"
            disabled={status === 'loading' || status === 'success' || !email}
            className="px-6 py-3 bg-gradient-to-r from-brand-deep to-brand-secondary-deep hover:from-brand hover:to-brand-secondary rounded-lg text-white font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
          >
            {status === 'loading' ? (
              <><Loader2 className="w-5 h-5 animate-spin" /> Subscribing...</>
            ) : status === 'success' ? (
              <><CheckCircle className="w-5 h-5" /> You&apos;re In!</>
            ) : (
              <><Send className="w-5 h-5" /> Subscribe</>
            )}
          </button>
        </form>
        <AnimatePresence>
          {message && (
            <motion.p
              initial={{ opacity: 0, y: -5 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              className={`text-sm text-center mt-3 ${
                status === 'success' ? 'text-green-400' : 'text-red-400'
              }`}
            >
              {message}
            </motion.p>
          )}
        </AnimatePresence>
        <p className="text-xs text-gray-500 text-center mt-3">
          No spam. Unsubscribe anytime. We respect your inbox.
        </p>
      </div>
    </div>
  );
}
