// ==========================================
// 🚀 INFINITY MAIN APP (FULL VERSION - NO FEATURE REMOVED)
// ==========================================

window.App = () => {
    // 🔥 1. ROUTING LOGIC
    const path = window.location.pathname;
    const [isDark, setIsDark] = React.useState(true);

    // Static Pages Routing
    if (path === '/about') return <window.AboutPage isDark={isDark} />;
    if (path === '/privacy') return <window.PrivacyPage isDark={isDark} />;
    if (path === '/terms') return <window.TermsPage isDark={isDark} />;
        // Blog Routing (Updated)
    if (path === '/blog' || path.startsWith('/blog/')) {
        return <window.BlogPage isDark={isDark} />;
    }

    // --- 2. STATE MANAGEMENT ---
    const [user, setUser] = React.useState(null);
    const [emailList, setEmailList] = React.useState([]);
    const [activeEmail, setActiveEmail] = React.useState(null);
    
    // 🔥 Token Persistence State (For Guerrilla & Server 3)
    const [activeToken, setActiveToken] = React.useState(null); 
    
    const [messages, setMessages] = React.useState([]);
    const [loading, setLoading] = React.useState(false);
    
    // 🔥 Refresh Timer State
    const [refreshTimer, setRefreshTimer] = React.useState(10);
    
    // UI Visibility States
    const [showCompose, setShowCompose] = React.useState(false);
    const [showProfileModal, setShowProfileModal] = React.useState(false); 
    const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);
    const [toast, setToast] = React.useState({ show: false, msg: '', type: 'success' });

    // Modals & Server Config States
    const [showServerModal, setShowServerModal] = React.useState(false); 
    const [confirmConfig, setConfirmConfig] = React.useState({ show: false, title: '', msg: '', action: null });
    const [serverList, setServerList] = React.useState([]); 
    const [currentServerId, setCurrentServerId] = React.useState('mailtm');

    // --- 3. UTILITIES & HELPER FUNCTIONS ---
    
    const playNotificationSound = () => {
        const audio = new Audio('https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3');
        audio.volume = 0.5;
        audio.play().catch(e => console.log("Audio autoplay blocked"));
    };

    const toggleTheme = () => setIsDark(!isDark);

    const showToast = (msg, type = 'success') => {
        setToast({ show: true, msg, type });
        setTimeout(() => setToast({ show: false, msg: '', type: 'success' }), 3000);
    };

    // Helper for Custom Confirm Modal
    const triggerConfirm = (title, msg, action) => {
        setConfirmConfig({ show: true, title, msg, action });
    };

    // Extract Components
    const { Header, Sidebar, Inbox, ComposeModal, Footer, AdSlot, ProfileModal, ConfirmModal, ServerSelectModal } = window;
    
    // Safety Check: Verify Dependencies
    if (!window.MailEngine || !Header || !ServerSelectModal) {
        return <div className="text-blue-500 p-10 font-mono animate-pulse">Initializing System Core...</div>;
    }

    // --- 4. USE EFFECTS (Life Cycle) ---

    // Effect: Load Server List from Engine
    React.useEffect(() => {
        const list = window.MailEngine.getProviderList();
        setServerList(list);
        setCurrentServerId(window.MailEngine.activeId);
    }, []);

    // Effect: Authentication & Initial Data Load
    React.useEffect(() => {
        if (!window.auth) return;
        const sub = window.auth.onAuthStateChanged(async (u) => {
            if (u) {
                setUser(u);
                if (!u.isAnonymous) {
                    await loadData(u.uid); 
                } else {
                    // Guest Logic
                    const savedEmails = localStorage.getItem('guestEmails');
                    if (savedEmails) {
                        const parsedList = JSON.parse(savedEmails);
                        if (parsedList.length > 0) {
                            setEmailList(parsedList);
                            selectEmail(parsedList[0]);
                        } else {
                            handleGenerateNewId('mailtm', u.uid, [], true);
                        }
                    } else {
                        handleGenerateNewId('mailtm', u.uid, [], true); 
                    }
                }
            } else {
                await window.auth.signInAnonymously();
            }
        });
        return () => sub();
    }, []);

    // Effect: Auto Refresh with Visual Timer
    React.useEffect(() => {
        if (!activeEmail) {
            setRefreshTimer(10); 
            return;
        }

        const interval = setInterval(() => {
            setRefreshTimer((prevTimer) => {
                if (prevTimer <= 1) {
                    // Timer hit 0: Refresh Data
                    fetchMsgs(activeEmail, activeToken, false, true); // Silent refresh
                    return 10; // Reset to 10
                }
                return prevTimer - 1; // Decrement
            });
        }, 1000); 

        return () => clearInterval(interval);
    }, [activeEmail, activeToken, messages]); // Runs when email/token changes

    // --- 5. HANDLERS (Business Logic) ---

    const loadData = async (uid) => {
        setLoading(true);
        try {
            const doc = await window.db.collection('users').doc(uid).get();
            if (doc.exists && doc.data().emails && doc.data().emails.length > 0) {
                setEmailList(doc.data().emails);
                selectEmail(doc.data().emails[0]);
            } else {
                handleGenerateNewId('mailtm', uid, []);
            }
        } catch (e) { console.error(e); }
        setLoading(false);
    };

    const handleLogin = async () => {
        try {
            const provider = new firebase.auth.GoogleAuthProvider();
            if (user && user.isAnonymous) {
                await user.linkWithPopup(provider);
                if (emailList.length > 0) {
                    await window.db.collection('users').doc(user.uid).set({ emails: emailList }, { merge: true });
                }
            } else {
                await window.auth.signInWithPopup(provider);
            }
            showToast("Account Linked Successfully!");
        } catch (error) {
            if (error.code === 'auth/credential-already-in-use') {
                await window.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
            } else {
                showToast("Login Failed", "error");
            }
        }
    };

    const handleProfileUpdate = async (name, photo) => {
        if (user) {
            try {
                await user.updateProfile({ displayName: name, photoURL: photo });
                setUser({...user, displayName: name, photoURL: photo});
                showToast("Profile Updated Successfully!");
            } catch (error) {
                showToast("Failed to update profile", "error");
            }
        }
    };

        // 🔥 CORE: Generate New ID (Updated for Domain Support)
    const handleGenerateNewId = async (serverId, specificDomain, uid, list, isGuest = false) => {
        if (user && user.isAnonymous) isGuest = true;
        setLoading(true);
        
        // 1. Switch Engine to Selected Server
        window.MailEngine.setProvider(serverId);
        setCurrentServerId(serverId);

        // 2. Determine Domain (Specific vs Random)
        let domain = specificDomain;
        if (!domain) {
            // If no domain passed, fetch random one
            const domains = await window.MailEngine.getDomain();
            if (domains && domains.length > 0) {
                domain = domains[Math.floor(Math.random() * domains.length)];
            }
        }

        if (domain) {
            const username = Math.random().toString(36).substring(7);
            
            // 3. Create Account (Pass specific domain)
            const result = await window.MailEngine.createAccount(username, domain);
            
            if (result.success) {
                const finalEmail = result.address || `${username}@${domain}`;
                
                const newItem = { 
                    address: finalEmail, 
                    provider: serverId, 
                    token: result.token || null, 
                    createdAt: new Date().toISOString() 
                };
                
                let newList;
                if (isGuest) {
                    newList = [newItem]; 
                    localStorage.setItem('guestEmails', JSON.stringify(newList));
                } else {
                    newList = [newItem, ...list];
                    if(uid) await window.db.collection('users').doc(uid).set({ emails: newList }, { merge: true });
                }
                
                setEmailList(newList);
                selectEmail(newItem); 
                showToast(`New ${window.MailEngine.getCurrent().name} ID`);
            } else {
                showToast("Server Busy! Try another.", "error");
            }
        } else {
            showToast("Failed to fetch domains.", "error");
        }
        setLoading(false);
    };

    // Modal Handlers
    const openServerSelection = () => setShowServerModal(true);
    
        const onServerSelected = (selectedId, selectedDomain) => {
        // Pass both ID and Domain to the generator
        handleGenerateNewId(selectedId, selectedDomain, user?.uid, emailList);
    };


    // 🗑️ DELETE FUNCTION
    const handleDeleteEmail = (emailToDelete) => {
        if (user && user.isAnonymous && emailList.length === 1) {
            triggerConfirm(
                "Create New Identity?", 
                "Deleting the only address will generate a new one.", 
                () => openServerSelection()
            );
            return;
        }

        if(emailList.length <= 1) {
            showToast("Cannot delete the only address!", "error");
            return;
        }

        triggerConfirm(
            "Delete Address?", 
            `Are you sure you want to delete ${emailToDelete.address}?`, 
            async () => {
                setLoading(true);
                const newList = emailList.filter(item => item.address !== emailToDelete.address);
                
                if (user && user.isAnonymous) {
                    localStorage.setItem('guestEmails', JSON.stringify(newList));
                } else if (user) {
                    await window.db.collection('users').doc(user.uid).set({ emails: newList }, { merge: true });
                }

                setEmailList(newList);
                if (activeEmail === emailToDelete.address) selectEmail(newList[0]);
                
                showToast("Address Deleted Successfully");
                setLoading(false);
            }
        );
    };

    // 🔥 SELECT EMAIL (Handles Token Restoration)
    const selectEmail = (item) => {
        // Switch Engine Context if needed
        if(item.provider && item.provider !== currentServerId) {
            window.MailEngine.setProvider(item.provider);
            setCurrentServerId(item.provider);
        }
        setActiveEmail(item.address);
        setActiveToken(item.token); // Restore token
        setRefreshTimer(10); // Reset timer
        
        fetchMsgs(item.address, item.token, true); 
        setMobileMenuOpen(false);
    };

    // 🔥 FETCH MESSAGES (Uses Saved Token)
    const fetchMsgs = async (addr, tokenData, isFirstLoad = false, isSilent = false) => {
        if (!isSilent) setLoading(true);
        
        // Use Engine with token support
        const finalToken = await window.MailEngine.getToken(addr, tokenData);
        
        if (finalToken) {
            const allMsgs = await window.MailEngine.getMessages(finalToken);
            
            let validMsgs = allMsgs;
            if (user && user.isAnonymous) {
                const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000); 
                // Only filter if createdAt is available
                if(validMsgs.length > 0 && validMsgs[0].createdAt) {
                    validMsgs = allMsgs.filter(msg => new Date(msg.createdAt) > twoHoursAgo);
                }
            }
            
            if (!isFirstLoad && validMsgs.length > messages.length) {
                playNotificationSound();
                showToast("New Email Received!", "success");
            }
            
            // Only update state if different
            if (JSON.stringify(validMsgs) !== JSON.stringify(messages)) {
                setMessages(validMsgs);
            }
        }
        if (!isSilent) setLoading(false);
    };

    // --- 6. RENDER VIEW ---
    return (
        <div className={`flex h-screen w-full overflow-hidden relative z-10 transition-colors duration-500 font-sans selection:bg-blue-500 selection:text-white
            ${isDark ? 'bg-[#020617] text-white' : 'bg-[#f0f4f8] text-slate-800'}
        `}>
            { /* 🔥 SEO Engine Added Here */ } { window.SeoEngine && <window.SeoEngine title="Inbox" /> }
            
            {/* Custom Toast */}
            <div className={`fixed bottom-10 left-1/2 transform -translate-x-1/2 z-[100] transition-all duration-300 ${toast.show ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-10 pointer-events-none'}`}>
                <div className={`px-6 py-3 rounded-full shadow-2xl flex items-center gap-3 border backdrop-blur-md
                    ${isDark ? 'bg-white/10 border-white/20 text-white' : 'bg-slate-900/90 text-white border-slate-700'}
                `}>
                    <i className={`fa-solid ${toast.type === 'success' ? 'fa-check-circle text-green-400' : 'fa-circle-exclamation text-red-400'}`}></i>
                    <span className="font-bold text-sm tracking-wide">{toast.msg}</span>
                </div>
            </div>

            {/* Sidebar (Responsive) */}
            <div className={`fixed md:relative z-50 h-full transition-transform duration-300 ease-out ${mobileMenuOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}`}>
                <Sidebar 
                    user={user} 
                    emailList={emailList} 
                    activeEmail={activeEmail} 
                    onSelect={selectEmail} 
                    onDelete={handleDeleteEmail}
                    onLogin={handleLogin} 
                    onLogout={() => window.auth.signOut()} 
                    onClose={() => setMobileMenuOpen(false)} 
                    isDark={isDark} 
                    showToast={showToast} 
                />
            </div>

            {/* Overlay for Mobile */}
            {mobileMenuOpen && <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-40 md:hidden" onClick={() => setMobileMenuOpen(false)}></div>}
            
            {/* Main Command Center */}
            <main className={`flex-1 flex flex-col h-full relative min-w-0 transition-colors duration-500 ${isDark ? "bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" : "bg-white"}`}>
                
                {/* Background Effects */}
                {isDark && (
                    <div className="absolute inset-0 pointer-events-none">
                        <div className="absolute inset-0 bg-gradient-to-b from-[#020617]/90 to-[#0f172a]/95"></div>
                        <div className="absolute top-[-10%] left-[-10%] w-[500px] h-[500px] bg-blue-600/20 rounded-full blur-[100px] opacity-40 animate-pulse"></div>
                        <div className="absolute bottom-[-10%] right-[-10%] w-[500px] h-[500px] bg-purple-600/20 rounded-full blur-[100px] opacity-40 animate-pulse" style={{animationDelay: '2s'}}></div>
                    </div>
                )}
                
                <div className="relative z-10 flex flex-col h-full">
                    <Header 
                        onMenu={() => setMobileMenuOpen(true)} 
                        loading={loading} 
                        activeEmail={activeEmail} 
                        isDark={isDark} 
                        toggleTheme={toggleTheme}
                        user={user}
                        onProfile={() => setShowProfileModal(true)}
                    />
                    
                    <div className="flex-1 overflow-y-auto glass-scroll p-4 md:p-8 space-y-6">
                        
                        {/* Guest Session Alert */}
                        {user && user.isAnonymous && (
                            <div className="flex items-center justify-between px-4 py-3 rounded-xl bg-yellow-500/10 border border-yellow-500/20 shadow-md">
                                <div className="flex items-center gap-3 text-yellow-600 dark:text-yellow-500">
                                    <i className="fa-solid fa-triangle-exclamation text-lg animate-pulse"></i>
                                    <div className="flex flex-col">
                                        <span className="text-xs font-bold tracking-wide uppercase">Guest Session</span>
                                        <span className="text-[9px] opacity-70">Messages auto-delete after 2 hours</span>
                                    </div>
                                </div>
                                <button onClick={handleLogin} className="text-xs bg-yellow-500 text-black px-3 py-1 rounded font-bold hover:bg-yellow-400 transition shadow-lg shadow-yellow-500/20">
                                    SAVE DATA
                                </button>
                            </div>
                        )}

                        {/* Active Email Display Box */}
                        <div className={`relative rounded-2xl p-6 md:p-8 flex flex-col md:flex-row justify-between items-center gap-6 border transition-all duration-300
                            ${isDark ? 'bg-[#0B1120]/80 border-white/10 backdrop-blur-md' : 'bg-white border-slate-200 shadow-xl'}`}>
                            
                            <div className="w-full text-center md:text-left overflow-hidden">
                                {/* Server Badge */}
                                <div className="flex items-center justify-center md:justify-start gap-2 mb-2">
                                    <span className={`px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-widest border ${isDark ? 'bg-blue-500/10 text-blue-400 border-blue-500/20' : 'bg-blue-50 text-blue-600 border-blue-200'}`}>
                                        {window.MailEngine.getCurrent().name}
                                    </span>
                                </div>
                                <h1 className={`text-2xl md:text-4xl font-mono font-bold tracking-tight truncate select-all
                                    ${isDark ? 'text-white drop-shadow-[0_0_15px_rgba(59,130,246,0.6)]' : 'text-slate-800'}`}>
                                    {activeEmail || 'Initializing...'}
                                </h1>
                            </div>

                            {/* Control Buttons */}
                            <div className="flex flex-wrap justify-center md:justify-end items-center gap-3 shrink-0">
                                {/* Refresh with Timer */}
                                <button 
                                    onClick={() => {fetchMsgs(activeEmail, activeToken, false); showToast("Inbox Refreshed"); setRefreshTimer(10);}}
                                    className={`relative h-12 w-12 rounded-xl border flex items-center justify-center transition-all hover:scale-105 active:scale-95
                                        ${isDark ? 'bg-white/5 hover:bg-white/10 border-white/10 text-gray-300' : 'bg-slate-100 hover:bg-slate-200 border-slate-200 text-slate-600'}
                                    `}
                                    title="Refresh Now"
                                >
                                    <i className={`fa-solid fa-rotate-right ${loading ? 'animate-spin' : ''}`}></i>
                                    {/* Timer Badge */}
                                    <span className={`absolute -top-2 -right-2 w-5 h-5 flex items-center justify-center rounded-full text-[9px] font-bold border-2
                                        ${isDark ? 'bg-blue-600 text-white border-[#0B1120]' : 'bg-blue-500 text-white border-white'}
                                    `}>
                                        {refreshTimer}
                                    </span>
                                </button>

                                {/* New ID Button (Triggers Modal) */}
                                <button 
                                    onClick={openServerSelection}
                                    className={`h-12 px-4 rounded-xl font-bold text-sm shadow-lg hover:scale-105 transition-all flex items-center gap-2
                                        ${isDark ? 'bg-emerald-600 hover:bg-emerald-500 text-white' : 'bg-emerald-500 hover:bg-emerald-600 text-white'}`}
                                >
                                    <i className="fa-solid fa-plus"></i> <span className="hidden sm:inline">NEW</span>
                                </button>

                                {/* Compose (Only if supported) */}
                                {window.MailEngine.getCurrent().type === 'auth' && (
                                    <button onClick={() => setShowCompose(true)} className="h-12 px-4 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-bold text-sm shadow-lg hover:scale-105 transition-all flex items-center gap-2">
                                        <i className="fa-solid fa-pen-fancy"></i> <span className="hidden sm:inline">COMPOSE</span>
                                    </button>
                                )}
                                
                                <button 
                                    onClick={() => { navigator.clipboard.writeText(activeEmail); showToast("Address Copied!"); }}
                                    className={`h-12 w-12 rounded-xl border flex items-center justify-center transition-all hover:scale-105 active:scale-95
                                        ${isDark ? 'bg-white/5 hover:bg-white/10 border-white/10 text-gray-300' : 'bg-slate-100 hover:bg-slate-200 border-slate-200 text-slate-600'}
                                    `}
                                    title="Copy"
                                >
                                    <i className="fa-regular fa-copy text-lg"></i>
                                </button>

                                <button 
                                    onClick={() => handleDeleteEmail({address: activeEmail})}
                                    className={`h-12 w-12 rounded-xl border flex items-center justify-center transition-all hover:scale-105 active:scale-95 hover:bg-red-500 hover:text-white
                                        ${isDark ? 'bg-white/5 border-white/10 text-red-400' : 'bg-slate-100 border-slate-200 text-red-500'}
                                    `}
                                    title="Delete Current"
                                >
                                    <i className="fa-regular fa-trash-can text-lg"></i>
                                </button>
                            </div>
                        </div>

                        {/* Inbox Component */}
                        <Inbox 
                            messages={messages} 
                            loading={loading} 
                            onRefresh={() => { fetchMsgs(activeEmail, activeToken, false); showToast("Inbox Refreshed"); }} 
                            isDark={isDark} 
                            showToast={showToast} 
                        />
                        
                        <AdSlot label="Sponsored Content" isDark={isDark} />
                        {/* SEO Content Section */}
                        <window.InfoSection isDark={isDark} />
                        <Footer isDark={isDark} />
                    </div>
                </div>
            </main>

            {/* --- MODALS --- */}
            
            <ComposeModal isOpen={showCompose} onClose={() => setShowCompose(false)} senderEmail={activeEmail} onSend={async (t, s, b) => {
                const sent = await window.MailEngine.sendEmail(null, activeEmail, t, s, b);
                if(sent) showToast("Message Sent Successfully!");
                else showToast("Failed. Server may restrict sending.", "error");
            }} isDark={isDark} />

            <ProfileModal 
                isOpen={showProfileModal} 
                onClose={() => setShowProfileModal(false)} 
                user={user} 
                onUpdate={handleProfileUpdate} 
                isDark={isDark} 
            />
            
            <ConfirmModal config={confirmConfig} onClose={() => setConfirmConfig({ ...confirmConfig, show: false })} isDark={isDark} />
            
            <ServerSelectModal 
                isOpen={showServerModal} 
                onClose={() => setShowServerModal(false)} 
                servers={serverList} 
                currentServerId={currentServerId}
                onSelect={onServerSelected}
                isDark={isDark}
            />
        </div>
    );
};
