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

const languages = [
    { code: 'en', name: 'English', flag: '🇬🇧' },
    { code: 'fr', name: 'Français', flag: '🇫🇷' },
    { code: 'de', name: 'Deutsch', flag: '🇩🇪' },
    { code: 'it', name: 'Italiano', flag: '🇮🇹' },
    { code: 'es', name: 'Español', flag: '🇪🇸' },
];

export default function LanguageSwitcher() {
    const [currentLang, setCurrentLang] = useState('en');
    const [mounted, setMounted] = useState(false);
    const [isOpen, setIsOpen] = useState(false);

    // Simple cookie clearing - just clear googtrans cookie
    const clearTranslateCookie = () => {
        if (typeof window === 'undefined') return;
        const expireDate = 'Thu, 01 Jan 1970 00:00:00 UTC';
        const hostname = window.location.hostname;
        const rootDomain = hostname.split('.').slice(-2).join('.');
        
        // Clear for current domain and root domain (handles subdomains)
        [hostname, rootDomain, '.' + rootDomain].forEach(domain => {
            document.cookie = `googtrans=; expires=${expireDate}; path=/; domain=${domain}`;
            document.cookie = `googtrans=; expires=${expireDate}; path=/`;
        });
    };

    // Function to trigger Google Translate
    const triggerGoogleTranslate = (langCode) => {
        if (typeof window === 'undefined') return;
        
        const isOriginal = langCode === 'en';
        
        const tryTranslate = () => {
            const select = document.querySelector('.goog-te-combo');
            if (!select) return false;
            
            if (isOriginal) {
                clearTranslateCookie();
                window.location.reload();
            } else {
                // CRITICAL FIX: Set cookie BEFORE changing select value to prevent English flash
                // This ensures Google Translate knows the target language immediately
                const cookieValue = `/en/${langCode}`;
                const hostname = window.location.hostname;
                const rootDomain = hostname.split('.').slice(-2).join('.');
                
                // Set cookie on multiple domains to ensure it's recognized
                [hostname, rootDomain, '.' + rootDomain].forEach(domain => {
                    try {
                        document.cookie = `googtrans=${cookieValue}; path=/; max-age=31536000; domain=${domain}`;
                    } catch (e) {
                        // Ignore domain errors (e.g., localhost)
                    }
                });
                // Also set without domain (for localhost and exact domain matches)
                document.cookie = `googtrans=${cookieValue}; path=/; max-age=31536000`;
                
                // Small delay to ensure cookie is set and recognized before triggering change
                // This prevents the English flash preview
                setTimeout(() => {
                    if (select.value !== langCode) {
                        select.value = langCode;
                        // Trigger change event - Google Translate will read the cookie we just set
                        const changeEvent = new Event('change', { bubbles: true, cancelable: true });
                        select.dispatchEvent(changeEvent);
                    }
                }, 50); // 50ms delay ensures cookie is set before Google Translate processes
            }
            return true;
        };

        if (!tryTranslate()) {
            setTimeout(() => tryTranslate() || setTimeout(tryTranslate, 500), 200);
        }
    };

    useEffect(() => {
        setMounted(true);
        
        if (typeof window === 'undefined') return;
        
        const savedLang = localStorage.getItem('preferredLanguage') || 'en';
        setCurrentLang(savedLang);
        
        // Handle language initialization
        if (savedLang === 'en') {
            // Clear cookie immediately
            clearTranslateCookie();
            
            // If page is already translated, reload once
            const isTranslated = document.documentElement.classList.contains('translated-ltr') || 
                               document.documentElement.classList.contains('translated-rtl');
            
            if (isTranslated && !sessionStorage.getItem('langResetInProgress')) {
                sessionStorage.setItem('langResetInProgress', 'true');
                clearTranslateCookie();
                window.location.reload();
                return;
            }
            
            // Clean up flag
            if (sessionStorage.getItem('langResetInProgress')) {
                setTimeout(() => sessionStorage.removeItem('langResetInProgress'), 1000);
            }
            
            // Ensure Google Translate is set to English when it loads (one-time check)
            const ensureEnglish = () => {
                const select = document.querySelector('.goog-te-combo');
                if (select && select.value !== 'en') {
                    select.value = 'en';
                    clearTranslateCookie();
                }
                
                // Remove translation classes if they appear
                if (document.documentElement.classList.contains('translated-ltr') || 
                    document.documentElement.classList.contains('translated-rtl')) {
                    document.documentElement.classList.remove('translated-ltr', 'translated-rtl');
                    document.body.classList.remove('translated-ltr', 'translated-rtl');
                    clearTranslateCookie();
                }
            };
            
            // Check when Google Translate loads
            if (window.google?.translate) {
                ensureEnglish();
            } else {
                // Wait for Google Translate to load, then check once
                const checkOnLoad = () => {
                    if (window.google?.translate) {
                        ensureEnglish();
                    } else {
                        setTimeout(checkOnLoad, 100);
                    }
                };
                setTimeout(checkOnLoad, 300);
            }
            
            // One final check after 2 seconds to catch any late initialization
            setTimeout(ensureEnglish, 2000);
        } else {
            // Trigger translation for saved language
            const checkAndTrigger = () => {
                if (window.google?.translate) {
                    triggerGoogleTranslate(savedLang);
                } else {
                    setTimeout(checkAndTrigger, 100);
                }
            };
            setTimeout(checkAndTrigger, 300);
        }
        
        // Close dropdown when clicking outside
        const handleClickOutside = (event) => {
            if (isOpen && !event.target.closest('.language-switcher-container')) {
                setIsOpen(false);
            }
        };
        
        document.addEventListener('click', handleClickOutside);
        return () => document.removeEventListener('click', handleClickOutside);
    }, [isOpen]);

    const changeLanguage = (langCode) => {
        if (typeof window === 'undefined') return;
        
        // Update UI state immediately
        setCurrentLang(langCode);
        localStorage.setItem('preferredLanguage', langCode);
        setIsOpen(false);
        
        // Dispatch custom event for same-window listeners (like the reservation form)
        window.dispatchEvent(new CustomEvent('languageChanged', { detail: { language: langCode } }));
        
        // Trigger translation immediately (cookie is set inside triggerGoogleTranslate)
        triggerGoogleTranslate(langCode);
    };

    const currentLanguage = languages.find(lang => lang.code === currentLang) || languages[0];

    // Render placeholder during SSR to avoid hydration mismatch
    if (!mounted) {
        return (
            <div className="language-switcher-container" style={{ visibility: 'hidden' }}>
                <button
                    className="language-switcher notranslate"
                    translate="no"
                    aria-label="Language switcher"
                >
                    <span className="language-flag">🇬🇧</span>
                    <span className="language-name">English</span>
                </button>
            </div>
        );
    }

    return (
        <div className="language-switcher-container" style={{ position: 'relative', display: 'inline-block' }}>
            <button
                onClick={(e) => {
                    e.stopPropagation();
                    setIsOpen(!isOpen);
                }}
                className="language-switcher notranslate"
                translate="no"
                aria-label="Switch language"
                aria-expanded={isOpen}
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    padding: '8px 12px',
                    border: 'none',
                    background: 'transparent',
                    cursor: 'pointer',
                    color: 'inherit'
                }}
            >
                <span className="language-flag" style={{ fontSize: '1.2rem' }}>
                    {currentLanguage.flag}
                </span>
                <span className="language-name">
                    {currentLanguage.name}
                </span>
                <span style={{ marginLeft: '4px', fontSize: '0.75rem' }}>
                    {isOpen ? '▲' : '▼'}
                </span>
            </button>
            
            {isOpen && (
                <div
                    className="language-dropdown"
                    style={{
                        position: 'absolute',
                        top: '100%',
                        right: 0,
                        backgroundColor: '#fff',
                        border: '1px solid #ddd',
                        borderRadius: '4px',
                        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                        zIndex: 1000,
                        minWidth: '150px',
                        marginTop: '4px'
                    }}
                    onClick={(e) => e.stopPropagation()}
                >
                    {languages.map((lang) => (
                        <button
                            key={lang.code}
                            onClick={() => changeLanguage(lang.code)}
                            className={`language-option notranslate ${lang.code === currentLang ? 'active' : ''}`}
                            translate="no"
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '10px',
                                width: '100%',
                                padding: '10px 15px',
                                border: 'none',
                                background: lang.code === currentLang ? '#f0f0f0' : 'transparent',
                                cursor: 'pointer',
                                textAlign: 'left',
                                fontSize: '14px',
                                transition: 'background-color 0.2s'
                            }}
                            onMouseEnter={(e) => {
                                if (lang.code !== currentLang) {
                                    e.currentTarget.style.backgroundColor = '#f8f8f8';
                                }
                            }}
                            onMouseLeave={(e) => {
                                if (lang.code !== currentLang) {
                                    e.currentTarget.style.backgroundColor = 'transparent';
                                }
                            }}
                        >
                            <span style={{ fontSize: '1.2rem' }}>{lang.flag}</span>
                            <span>{lang.name}</span>
                            {lang.code === currentLang && (
                                <span style={{ marginLeft: 'auto', color: '#2196F3' }}>✓</span>
                            )}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
}

