import React, { useState, useEffect } from 'react';
import { X, Gift } from 'lucide-react';
import { Language } from '../types';
import { TRANSLATIONS } from '../constants/translations';

interface ExitIntentModalProps {
  language: Language;
  onClose: () => void;
}

export const ExitIntentModal: React.FC<ExitIntentModalProps> = ({ language, onClose }) => {
  const [isVisible, setIsVisible] = useState(false);
  const t = TRANSLATIONS[language];

  useEffect(() => {
    // Only run on desktop where mouse leaves viewport
    if (window.innerWidth < 768) return;

    const handleMouseLeave = (e: MouseEvent) => {
      if (e.clientY <= 0) {
        // User moved mouse to top of browser (tabs/close button)
        const hasShown = localStorage.getItem('exit_intent_shown');
        if (!hasShown) {
          setIsVisible(true);
          localStorage.setItem('exit_intent_shown', 'true');
        }
      }
    };

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

  if (!isVisible) return null;

  const handleClose = () => {
    setIsVisible(false);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm animate-fade-in">
      <div className="bg-white rounded-2xl shadow-2xl max-w-sm w-full overflow-hidden relative text-center p-8">
        <button 
          onClick={handleClose} 
          className="absolute top-2 right-2 p-1.5 hover:bg-gray-100 rounded-full text-gray-400"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4 text-red-500 animate-bounce">
           <Gift className="w-8 h-8" />
        </div>

        <h3 className="text-2xl font-bold text-gray-900 mb-2">等一下！</h3>
        <p className="text-gray-600 mb-6 text-sm">
           现在离开就错过了 <strong>500元</strong> 现金抵用券！<br/>
           仅限今日，留下联系方式即可领取。
        </p>

        <div className="space-y-3">
           <button 
             onClick={handleClose} // In real app, open consult modal
             className="w-full py-3 bg-red-600 hover:bg-red-700 text-white font-bold rounded-xl shadow-lg shadow-red-200 transition-all"
           >
             领取优惠
           </button>
           <button 
             onClick={handleClose}
             className="w-full py-2 text-gray-400 text-xs hover:text-gray-600 font-medium"
           >
             忍痛放弃
           </button>
        </div>
      </div>
    </div>
  );
};