const { useState, useEffect } = React;

const CountryWelcomePopup = () => {
    const [isVisible, setIsVisible] = useState(false);
    const [country, setCountry] = useState('');
    const [countryCode, setCountryCode] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        // Check if user has already seen the popup
         const hasSeenPopup = localStorage.getItem('countryPopupSeen');
        
         if (!hasSeenPopup) {
            fetchCountry();
         }
    }, []);

    const fetchCountry = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'get_user_country');
            formData.append('nonce', countryPopupData.nonce);

            const response = await fetch(countryPopupData.ajaxUrl, {
                method: 'POST',
                body: formData
            });

            const data = await response.json();

            if (data.success) {
                setCountry(data.data.country);
                setCountryCode(data.data.countryCode);
                setIsVisible(true);
            }
        } catch (error) {
            console.error('Error fetching country:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleClose = () => {
        setIsVisible(false);
         localStorage.setItem('countryPopupSeen', 'false');
    };

    if (!isVisible || loading) {
        return null;
    }

    return (
        <div className="country-popup-overlay" onClick={handleClose}>
            <div className="country-popup-content" onClick={(e) => e.stopPropagation()}>
                <button className="country-popup-close" onClick={handleClose}>
                    &times;
                </button>
                <div className="country-popup-body">
                    <div className="country-flag">
                        {countryCode !== 'XX' && (
                            <img 
                                src={`https://flagcdn.com/w160/${countryCode.toLowerCase()}.png`}
                                alt={country}
                                className="flag-image"
                            />
                        )}
                    </div>
                 <h2 className="country-popup-title">{countryPopupData.translations.welcomeTitle}</h2>
                <p className="country-popup-text">
                    {countryPopupData.translations.welcomeText} <strong>{country}</strong>!
                </p>
                <button className="country-popup-button" onClick={handleClose}>
                    {countryPopupData.translations.continueButton}
                </button>

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

// Render the component
const rootElement = document.getElementById('country-welcome-popup-root');
if (rootElement) {
    ReactDOM.render(<CountryWelcomePopup />, rootElement);
}