function Dashboard({ user: initialUser, token, onLogout }) {
    const [user, setUser] = useState(initialUser);
    const [activeTab, setActiveTab] = useState('home');
    const [showProfileMenu, setShowProfileMenu] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const [showProfile, setShowProfile] = useState(false);
    const [showFeedbackModal, setShowFeedbackModal] = useState(false);
    const [actionParams, setActionParams] = useState(null); // For passing actions between tabs
    const [settings, setSettings] = useState(() => {
        const saved = localStorage.getItem('appSettings');
        const defaults = {
            appearance: 'light',
            fontSize: 'medium',
            dailyWord: true,  // ON by default
            dailyQuote: true, // ON by default
            fileStorage: false
        };
        return saved ? { ...defaults, ...JSON.parse(saved) } : defaults;
    });

    const { t, language, setLanguage } = useTranslation();


    const tabs = [
        { id: 'home', label: t('navigation.home'), icon: '🏠' },
        { id: 'notes', label: t('navigation.notes'), icon: '📝' },
        { id: 'ask', label: t('navigation.ask'), icon: '❓' },
        { id: 'share', label: 'Share Notes', icon: '🔗' },
        { id: 'tools', label: t('navigation.tools'), icon: '🔧' },
    ];

    const languages = [
        { code: 'en', name: 'English', flag: '🇺🇸' },
        { code: 'pa', name: 'ਪੰਜਾਬੀ (Punjabi)', flag: '🇮🇳' },
        { code: 'hi', name: 'हिन्दी (Hindi)', flag: '🇮🇳' },
        { code: 'bn', name: 'বাংলা (Bengali)', flag: '🇧🇩' },
        { code: 'de', name: 'Deutsch (German)', flag: '🇩🇪' },
        { code: 'fr', name: 'Français (French)', flag: '🇫🇷' },
        { code: 'nl', name: 'Nederlands (Dutch)', flag: '🇳🇱' },
        { code: 'zh', name: '中文 (Chinese)', flag: '🇨🇳' },
        { code: 'ru', name: 'Русский (Russian)', flag: '🇷🇺' },
        { code: 'ar', name: 'العربية (Arabic)', flag: '🇸🇦' },
        { code: 'es', name: 'Español (Spanish)', flag: '🇪🇸' }
    ];

    const updateSettings = (key, value) => {
        const newSettings = { ...settings, [key]: value };
        setSettings(newSettings);
        localStorage.setItem('appSettings', JSON.stringify(newSettings));
    };

    const updateMultipleSettings = (updates) => {
        const newSettings = { ...settings, ...updates };
        setSettings(newSettings);
        localStorage.setItem('appSettings', JSON.stringify(newSettings));
    };

    const handleUserUpdate = (updatedUser) => {
        setUser(updatedUser);
        // Update user in localStorage
        const storedUser = JSON.parse(localStorage.getItem('user') || '{}');
        const mergedUser = { ...storedUser, ...updatedUser };
        localStorage.setItem('user', JSON.stringify(mergedUser));
    };

    // Apply settings on mount and when they change
    useEffect(() => {
        const fontSize = settings.fontSize === 'small' ? '0.875rem' : settings.fontSize === 'large' ? '1.125rem' : '1rem';
        document.documentElement.style.fontSize = fontSize;

        let theme = settings.appearance;
        if (theme === 'auto') {
            theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
        }
        document.body.setAttribute('data-theme', theme);
    }, [settings]);

    // Close profile dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showProfileMenu) {
                const profileButton = event.target.closest('[data-profile-button]');
                const profileMenu = event.target.closest('[data-profile-menu]');
                if (!profileButton && !profileMenu) {
                    setShowProfileMenu(false);
                }
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [showProfileMenu]);

    return (
        <div className="main-layout fade-in">
            {/* Sidebar for Desktop */}
            <aside className="sidebar">
                <div className="sidebar-header">
                    <div className="logo">📚 NoteVerse</div>
                </div>
                <div className="sidebar-content">
                    {tabs.map(tab => (
                        <div
                            key={tab.id}
                            className={`sidebar-nav-item ${activeTab === tab.id ? 'active' : ''}`}
                            onClick={() => setActiveTab(tab.id)}
                        >
                            <span>{tab.label}</span>
                        </div>
                    ))}
                </div>
            </aside>

            <div className="main-content">
                <div className="header">
                    <div className="header-content">
                        <div className="logo hide-desktop">📚 NoteVerse</div>
                        <div className="flex items-center gap-4" style={{ marginLeft: 'auto' }}>
                            <div className="hide-mobile">
                                <ProfilePhoto
                                    photoUrl={user.photo_url || user.profile_photo}
                                    userName={user.name}
                                    size="small"
                                    showStatus={false}
                                />
                            </div>
                            <div style={{ position: 'relative' }}>
                                <button
                                    data-profile-button
                                    onClick={() => setShowProfileMenu(!showProfileMenu)}
                                    className="btn btn-secondary"
                                    style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
                                >
                                    <span>☰</span>
                                    <span>Menu</span>
                                    <span style={{ fontSize: '12px' }}>▼</span>
                                </button>

                                {showProfileMenu && (
                                    <div
                                        data-profile-menu
                                        style={{
                                            position: 'absolute',
                                            top: '100%',
                                            right: 0,
                                            marginTop: '8px',
                                            background: 'var(--bg-primary)',
                                            border: '1px solid var(--border-color)',
                                            borderRadius: '8px',
                                            boxShadow: 'var(--shadow-lg)',
                                            minWidth: '220px',
                                            zIndex: 1000
                                        }}>
                                        {/* Mobile Navigation Links */}
                                        <div className="hide-desktop" style={{ borderBottom: '1px solid var(--border-color)', paddingBottom: '4px', marginBottom: '4px' }}>
                                            {tabs.map(tab => (
                                                <button
                                                    key={tab.id}
                                                    onClick={() => { setActiveTab(tab.id); setShowProfileMenu(false); }}
                                                    style={{
                                                        width: '100%',
                                                        padding: '10px 16px',
                                                        border: 'none',
                                                        background: activeTab === tab.id ? 'var(--primary-light)' : 'none',
                                                        textAlign: 'left',
                                                        cursor: 'pointer',
                                                        fontSize: '14px',
                                                        color: activeTab === tab.id ? 'var(--primary)' : 'var(--text-primary)',
                                                        fontWeight: activeTab === tab.id ? '600' : '400'
                                                    }}
                                                >
                                                    {tab.label}
                                                </button>
                                            ))}
                                        </div>

                                        <button
                                            onClick={() => { setShowProfileMenu(false); setShowProfile(true); }}
                                            style={{
                                                width: '100%',
                                                padding: '12px 16px',
                                                border: 'none',
                                                background: 'none',
                                                textAlign: 'left',
                                                cursor: 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '12px',
                                                fontSize: '14px',
                                                color: 'var(--text-primary)',
                                                borderBottom: '1px solid var(--border-color)'
                                            }}
                                            onMouseEnter={(e) => e.target.style.background = 'var(--bg-secondary)'}
                                            onMouseLeave={(e) => e.target.style.background = 'none'}
                                        >
                                            <span>👤 {t('common.profile')}</span>
                                        </button>
                                        <button
                                            onClick={() => { setActiveTab('archive'); setShowProfileMenu(false); }}
                                            style={{
                                                width: '100%',
                                                padding: '12px 16px',
                                                border: 'none',
                                                background: 'none',
                                                textAlign: 'left',
                                                cursor: 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '12px',
                                                fontSize: '14px',
                                                color: 'var(--text-primary)',
                                                borderBottom: '1px solid var(--border-color)'
                                            }}
                                            onMouseEnter={(e) => e.target.style.background = 'var(--bg-secondary)'}
                                            onMouseLeave={(e) => e.target.style.background = 'none'}
                                        >
                                            <span>📦 Archive</span>
                                        </button>
                                        <button
                                            onClick={() => { setShowProfileMenu(false); setShowFeedbackModal(true); }}
                                            style={{
                                                width: 'calc(100% - 16px)',
                                                padding: '10px 14px',
                                                border: '2px solid rgba(255, 255, 255, 0.3)',
                                                background: 'linear-gradient(135deg, #17C9C9 0%, #1E90FF 100%)',
                                                textAlign: 'left',
                                                cursor: 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '12px',
                                                fontSize: '13px',
                                                color: 'white',
                                                fontWeight: '600',
                                                borderRadius: '8px',
                                                margin: '8px'
                                            }}
                                            onMouseEnter={(e) => e.target.style.background = 'linear-gradient(135deg, #15B5B5 0%, #1A7FE0 100%)'}
                                            onMouseLeave={(e) => e.target.style.background = 'linear-gradient(135deg, #17C9C9 0%, #1E90FF 100%)'}
                                        >
                                            <span>💬 Feedback</span>
                                        </button>
                                        <button
                                            onClick={() => { setShowProfileMenu(false); setShowSettings(true); }}
                                            style={{
                                                width: '100%',
                                                padding: '12px 16px',
                                                border: 'none',
                                                background: 'none',
                                                textAlign: 'left',
                                                cursor: 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '12px',
                                                fontSize: '14px',
                                                color: 'var(--text-primary)',
                                                borderBottom: '1px solid var(--border-color)'
                                            }}
                                            onMouseEnter={(e) => e.target.style.background = 'var(--bg-secondary)'}
                                            onMouseLeave={(e) => e.target.style.background = 'none'}
                                        >
                                            <span>⚙️ {t('common.settings')}</span>
                                        </button>
                                        <button
                                            onClick={() => { setShowProfileMenu(false); onLogout(); }}
                                            style={{
                                                width: '100%',
                                                padding: '12px 16px',
                                                border: 'none',
                                                background: 'none',
                                                textAlign: 'left',
                                                cursor: 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '12px',
                                                fontSize: '14px',
                                                color: 'var(--danger)'
                                            }}
                                            onMouseEnter={(e) => e.target.style.background = 'var(--bg-secondary)'}
                                            onMouseLeave={(e) => e.target.style.background = 'none'}
                                        >
                                            <span>🚪 {t('common.logout')}</span>
                                        </button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                <div className="content-area">
                    {activeTab === 'home' && <DashboardView token={token} t={t} settings={settings} updateSettings={updateSettings} updateMultipleSettings={updateMultipleSettings} setActiveTab={setActiveTab} setActionParams={setActionParams} />}
                    {activeTab === 'dashboard' && <DashboardView token={token} t={t} settings={settings} updateSettings={updateSettings} updateMultipleSettings={updateMultipleSettings} setActiveTab={setActiveTab} setActionParams={setActionParams} />}
                    {activeTab === 'notes' && <AdvancedNotes user={user} token={token} actionParams={actionParams} setActionParams={setActionParams} />}
                    {activeTab === 'archive' && <ArchiveView user={user} token={token} settings={settings} />}
                    {activeTab === 'share' && < ShareView token={token} t={t} setActiveTab={setActiveTab} setActionParams={setActionParams} />}
                    {activeTab === 'ask' && <AskView token={token} t={t} />}
                    {activeTab === 'tools' && <ToolsView token={token} t={t} />}
                </div>
            </div>

            {/* Settings Modal */}
            {showSettings && (
                <div
                    onClick={(e) => {
                        // Close if clicking on backdrop
                        if (e.target === e.currentTarget) {
                            setShowSettings(false);
                        }
                    }}
                    style={{
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        background: 'rgba(0, 0, 0, 0.5)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        zIndex: 2000,
                        padding: '20px'
                    }}>
                    <div style={{
                        background: 'var(--bg-primary)',
                        borderRadius: '12px',
                        maxWidth: '700px',
                        width: '100%',
                        maxHeight: '80vh',
                        overflow: 'auto',
                        boxShadow: 'var(--shadow-lg)'
                    }}>
                        <div style={{ padding: '24px', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h2 style={{ fontSize: '20px', fontWeight: '700', margin: 0 }}>{t('common.settings')}</h2>
                            <button onClick={() => setShowSettings(false)} style={{ background: 'none', border: 'none', fontSize: '24px', cursor: 'pointer', color: 'var(--text-secondary)' }}>×</button>
                        </div>

                        <div style={{ padding: '24px' }}>
                            {/* Appearance Mode */}
                            <div style={{ marginBottom: '24px' }}>
                                <label style={{ display: 'block', fontWeight: '600', marginBottom: '12px', fontSize: '14px' }}>{t('common.appearance')}</label>
                                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
                                    {['light', 'dark', 'auto'].map(mode => (
                                        <button
                                            key={mode}
                                            onClick={() => updateSettings('appearance', mode)}
                                            style={{
                                                padding: '12px',
                                                border: `2px solid ${settings.appearance === mode ? 'var(--primary)' : 'var(--border-color)'}`,
                                                background: settings.appearance === mode ? 'var(--primary-light)' : 'var(--bg-secondary)',
                                                borderRadius: '8px',
                                                cursor: 'pointer',
                                                fontSize: '14px',
                                                fontWeight: settings.appearance === mode ? '600' : '400',
                                                textTransform: 'capitalize',
                                                color: 'var(--text-primary)'
                                            }}
                                        >
                                            {mode === 'light' ? '☀️' : mode === 'dark' ? '🌙' : '🔄'} {mode}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Font Size */}
                            <div style={{ marginBottom: '24px' }}>
                                <label style={{ display: 'block', fontWeight: '600', marginBottom: '12px', fontSize: '14px' }}>{t('common.fontSize')}</label>
                                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
                                    {['small', 'medium', 'large'].map(size => (
                                        <button
                                            key={size}
                                            onClick={() => updateSettings('fontSize', size)}
                                            style={{
                                                padding: '12px',
                                                border: `2px solid ${settings.fontSize === size ? 'var(--primary)' : 'var(--border-color)'}`,
                                                background: settings.fontSize === size ? 'var(--primary-light)' : 'var(--bg-secondary)',
                                                borderRadius: '8px',
                                                cursor: 'pointer',
                                                fontSize: size === 'small' ? '12px' : size === 'large' ? '16px' : '14px',
                                                fontWeight: settings.fontSize === size ? '600' : '400',
                                                textTransform: 'capitalize',
                                                color: 'var(--text-primary)'
                                            }}
                                        >
                                            {size}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Language */}
                            <div>
                                <label style={{ display: 'block', fontWeight: '600', marginBottom: '12px', fontSize: '14px' }}>{t('common.language')}</label>
                                <select
                                    value={language}
                                    onChange={(e) => setLanguage(e.target.value)}
                                    className="form-input"
                                    style={{ width: '100%', background: 'var(--bg-secondary)', color: 'var(--text-primary)' }}
                                >
                                    {languages.map(lang => (
                                        <option key={lang.code} value={lang.code}>
                                            {lang.flag} {lang.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            {/* Toggles Section */}
                            <div style={{ marginTop: '24px', paddingTop: '24px', borderTop: '1px solid var(--border-color)' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                                    <div><div style={{ fontWeight: '600', fontSize: '14px' }}>📁 File Storage</div><div style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>Store original files</div></div>
                                    <input type="checkbox" checked={settings.fileStorage || false} onChange={(e) => updateSettings('fileStorage', e.target.checked)} style={{ width: '20px', height: '20px', cursor: 'pointer' }} />
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                                    <div><div style={{ fontWeight: '600', fontSize: '14px' }}>📖 Daily Word</div><div style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>Show vocabulary</div></div>
                                    <input type="checkbox" checked={settings.dailyWord || false} onChange={(e) => updateSettings('dailyWord', e.target.checked)} style={{ width: '20px', height: '20px', cursor: 'pointer' }} />
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <div><div style={{ fontWeight: '600', fontSize: '14px' }}>💭 Daily Quote</div><div style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>Show inspiration</div></div>
                                    <input type="checkbox" checked={settings.dailyQuote || false} onChange={(e) => updateSettings('dailyQuote', e.target.checked)} style={{ width: '20px', height: '20px', cursor: 'pointer' }} />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )
            }

            {/* Profile Modal */}
            {showProfile && (
                <div
                    onClick={(e) => {
                        // Close if clicking on backdrop
                        if (e.target === e.currentTarget) {
                            setShowProfile(false);
                        }
                    }}
                    style={{
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        background: 'rgba(0, 0, 0, 0.5)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        zIndex: 2000,
                        padding: '20px'
                    }}>
                    <div style={{
                        background: 'var(--bg-primary)',
                        borderRadius: '12px',
                        maxWidth: '700px',
                        width: '100%',
                        maxHeight: '80vh',
                        overflow: 'auto',
                        boxShadow: 'var(--shadow-lg)'
                    }}>
                        <div style={{ padding: '24px', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h2 style={{ fontSize: '20px', fontWeight: '700', margin: 0 }}>{t('common.profile')}</h2>
                            <button onClick={() => setShowProfile(false)} style={{ background: 'none', border: 'none', fontSize: '24px', cursor: 'pointer', color: 'var(--text-secondary)' }}>×</button>
                        </div>

                        <div style={{ padding: '24px' }}>
                            <ProfileView user={user} token={token} t={t} onUserUpdate={handleUserUpdate} />
                        </div>
                    </div>
                </div>
            )
            }

            {/* Feedback Modal */}
            {showFeedbackModal && <FeedbackModal t={t} onClose={() => setShowFeedbackModal(false)} />}
        </div >
    );
}

// Export to global scope
window.Dashboard = Dashboard;
