import { useState, useEffect, useRef } from 'react';

export default function ExitIntentPopup() {
  const [show, setShow] = useState(false);
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [message, setMessage] = useState('');
  const shownRef = useRef(false);

  useEffect(() => {
    // Don't show if user already registered or dismissed
    if (localStorage.getItem('sp_exit_dismissed') || localStorage.getItem('sp_user')) return;

    // Desktop: mouse leaves viewport at top
    const handleMouseLeave = (e: MouseEvent) => {
      if (e.clientY <= 0 && !shownRef.current) {
        shownRef.current = true;
        setShow(true);
      }
    };

    // Mobile: show after 45 seconds of browsing
    const mobileTimer = setTimeout(() => {
      if (window.innerWidth < 768 && !shownRef.current) {
        shownRef.current = true;
        setShow(true);
      }
    }, 45000);

    document.addEventListener('mouseleave', handleMouseLeave);
    return () => {
      document.removeEventListener('mouseleave', handleMouseLeave);
      clearTimeout(mobileTimer);
    };
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setStatus('loading');
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (data.ok || data.error?.includes('al geregistreerd')) {
        setStatus('success');
        setMessage('Check je inbox voor de bevestiging!');
        localStorage.setItem('sp_exit_dismissed', '1');
      } else {
        setStatus('error');
        setMessage(data.error || 'Er ging iets mis');
      }
    } catch {
      setStatus('error');
      setMessage('Er ging iets mis, probeer het later opnieuw');
    }
  };

  const dismiss = () => {
    setShow(false);
    localStorage.setItem('sp_exit_dismissed', '1');
  };

  if (!show) return null;

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/90 p-4"
      onClick={(e) => { if (e.target === e.currentTarget) dismiss(); }}
    >
      <div className="relative w-full max-w-md rounded-2xl border border-[var(--border)] bg-[var(--bg-card)] p-5 sm:p-8 shadow-2xl animate-fade-in" onClick={e => e.stopPropagation()}>
        {/* Close button */}
        <button
          onClick={dismiss}
          data-modal-close
          className="absolute right-3 top-3 sm:right-4 sm:top-4 text-[var(--text-muted)] hover:text-[var(--text)] transition-colors"
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>

        {status === 'success' ? (
          <div className="text-center py-4">
            <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-[var(--accent)]/10 text-[var(--accent)]">
              <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" /><polyline points="22 4 12 14.01 9 11.01" /></svg>
            </div>
            <h3 className="text-xl font-bold text-[var(--text)] mb-2">Je bent aangemeld!</h3>
            <p className="text-sm text-[var(--text-secondary)]">{message}</p>
          </div>
        ) : (
          <>
            <div className="text-center mb-6">
              <div className="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-[var(--accent)]/10 text-[var(--accent)]">
                <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M2 18h20v1a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-1Z" />
                  <path d="M2 18l1.2-4.8A2 2 0 0 1 5.1 12h1.4l1 2h4l.8-2.4a2 2 0 0 1 1.9-1.4l5.6-.2a2 2 0 0 1 2 1.7L22 18" />
                  <path d="M6 12V8a2 2 0 0 1 2-2h1" />
                </svg>
              </div>
              <h3 className="text-xl font-black text-[var(--text)]">Mis geen prijsdalingen!</h3>
              <p className="mt-2 text-sm text-[var(--text-secondary)]">
                Ontvang alerts wanneer je favoriete sneakers in prijs dalen. Gratis, geen spam.
              </p>
            </div>

            <form onSubmit={handleSubmit}>
              <div className="flex gap-2">
                <input
                  type="email"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  placeholder="je@email.nl"
                  required
                  className="flex-1 rounded-xl border border-[var(--border)]/50 bg-[var(--bg-elevated)] px-4 py-3 text-[var(--text)] placeholder-[var(--text-muted)] focus:border-[var(--accent)]/50 focus:outline-none"
                />
                <button
                  type="submit"
                  disabled={status === 'loading'}
                  className="rounded-xl bg-[var(--accent)] px-5 py-3 font-bold text-[var(--bg)] transition-colors hover:opacity-90 disabled:opacity-50 whitespace-nowrap"
                >
                  {status === 'loading' ? '...' : 'Aanmelden'}
                </button>
              </div>
              {status === 'error' && (
                <p className="mt-2 text-xs text-red-400">{message}</p>
              )}
            </form>

            <p className="mt-4 text-center text-xs text-[var(--text-muted)]">
              Je kunt je altijd uitschrijven. We sturen max 2 mails per week.
            </p>
          </>
        )}
      </div>
    </div>
  );
}
