const MainApp = ({ currentUser, onLogout }) => {
    const [currentView, setCurrentView]           = React.useState('tasks'); // accounts | dashboard | tasks | quotes | invoices | inventory
    const [showGlobalSearch, setShowGlobalSearch] = React.useState(false);
    const [searchTerm, setSearchTerm]             = React.useState('');
    const [selectedAccount, setSelectedAccount]   = React.useState(null);
    const [data, setData]                 = React.useState({ accounts: [], contacts: [], followUpTasks: [], users: [], tags: [] });
    const [loadingData, setLoadingData]   = React.useState(true);
    const [showNewAccount, setShowNewAccount] = React.useState(false);
    const [showAdmin, setShowAdmin]           = React.useState(false);
    // Open Email Settings automatically when returning from the OAuth redirect
    // (/api/email/callback bounces back to /?email=connected|declined|error).
    // Keep the flag's *value* too — the modal uses it to tell the user whether
    // the connect actually worked (a silent bounce back to "Connect" reads as
    // success-then-amnesia when the server side actually failed).
    const [emailOAuthResult] = React.useState(() => {
        const flag = new URLSearchParams(window.location.search).get('email');
        if (flag) window.history.replaceState({}, '', '/'); // clean the URL so refresh doesn't re-trigger
        return flag; // 'connected' | 'declined' | 'error' | null
    });
    const [showEmailSettings, setShowEmailSettings] = React.useState(Boolean(emailOAuthResult));
    const [myAccountsOnly, setMyAccountsOnly] = React.useState(false);
    const [tagFilter, setTagFilter]           = React.useState([]); // selected tag ids — OR-match (account shows if it has ANY selected tag)
    const [showSettings, setShowSettings]     = React.useState(false);
    const [isFullscreen, setIsFullscreen]     = React.useState(Boolean(document.fullscreenElement));

    // ── Theme: the account's saved theme wins over the local cache ───
    // (localStorage is just a pre-paint hint; the DB value is the truth,
    // so signing in on a new machine brings your theme with you.)
    React.useEffect(() => {
        if (currentUser.settings?.theme) applyTheme(currentUser.settings.theme);
    }, []);

    // ── Fullscreen ────────────────────────────────────────────────
    // Track via the browser event, not our own flag — Esc exits fullscreen
    // without ever touching our button, and the icon must follow reality.
    React.useEffect(() => {
        const handler = () => setIsFullscreen(Boolean(document.fullscreenElement));
        document.addEventListener('fullscreenchange', handler);
        return () => document.removeEventListener('fullscreenchange', handler);
    }, []);

    const toggleFullscreen = () => {
        if (document.fullscreenElement) document.exitFullscreen();
        else document.documentElement.requestFullscreen().catch(err => console.error('Fullscreen refused:', err));
    };

    // ── Ctrl+K global search shortcut ─────────────────────────────
    React.useEffect(() => {
        const handler = (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); setShowGlobalSearch(s => !s); } };
        document.addEventListener('keydown', handler);
        return () => document.removeEventListener('keydown', handler);
    }, []);

    // ── Load on mount ──────────────────────────────────────────────
    React.useEffect(() => { loadAll(); }, []);

    // ── Reload accounts when my/all toggle changes ────────────────
    React.useEffect(() => {
        if (!loadingData) loadAccounts();
    }, [myAccountsOnly]);

    const loadAccounts = async () => {
        const params = {};
        if (myAccountsOnly) params.mine = 'true';
        const accounts = await api.getAccounts(params);
        setData(p => ({ ...p, accounts }));
    };

    const loadAll = async () => {
        setLoadingData(true);
        try {
            const accountParams = myAccountsOnly ? { mine: 'true' } : {};
            const isManager = currentUser.role === 'admin' || currentUser.role === 'manager';
            const [accounts, tasks, users, tags] = await Promise.all([
                api.getAccounts(accountParams),
                api.getTasks({ completed: false }),
                isManager ? api.getUsers() : Promise.resolve([]),
                api.getTags(),
            ]);
            setData(p => ({ ...p, accounts, followUpTasks: tasks, users, tags }));
        } catch (err) {
            console.error('Failed to load data:', err);
            if (err.message.includes('token') || err.message.includes('401')) onLogout();
        } finally {
            setLoadingData(false);
        }
    };

    // ── Handlers ──────────────────────────────────────────────────

    const handleCreateAccount = async (formData) => {
        const account = await api.createAccount(formData);
        setData(p => ({ ...p, accounts: [...p.accounts, account] }));
        setShowNewAccount(false);
    };


    const handleCompleteTask = async (taskId) => {
        await api.completeTask(taskId);
        setData(p => ({ ...p, followUpTasks: p.followUpTasks.filter(t => t.id !== taskId) }));
    };

    const handleDeleteTask = async (taskId) => {
        if (!window.confirm('Delete this task?')) return;
        await api.deleteTask(taskId);
        setData(p => ({ ...p, followUpTasks: p.followUpTasks.filter(t => t.id !== taskId) }));
    };

    const handleMergeAccount = async (sourceId, targetId) => {
        await api.mergeAccounts(sourceId, targetId);
        setSelectedAccount(null);
        await loadAll();
    };

    const handleSelectAccountFromSearch = async (accountStub) => {
        setCurrentView('accounts');
        setShowGlobalSearch(false);
        try {
            const full = await api.getAccount(accountStub.id);
            setSelectedAccount(full);
        } catch(e) { console.error(e); }
    };

    // ── Derived ───────────────────────────────────────────────────

    const filteredAccounts = data.accounts.filter(a => {
        // Tag chips filter first — cheap check, and it composes with text search (both must pass)
        if (tagFilter.length > 0 && !(a.tags || []).some(t => tagFilter.includes(t.id))) return false;
        if (!searchTerm) return true;
        const s = searchTerm.toLowerCase();
        return a.name.toLowerCase().includes(s) ||
               (a.main_email && a.main_email.toLowerCase().includes(s)) ||
               (a.main_phone && a.main_phone.includes(s)) ||
               (a.tags || []).some(t => t.name.toLowerCase().includes(s));
    });

    const overdueTasks = data.followUpTasks.filter(t => t.due_date && new Date(t.due_date) < new Date(new Date().toDateString()));

    // ══════════════════════════════════════════════════════════════
    return (
        <div className="crm-container">

            {/* ── Top Nav ── */}
            <div className="top-nav">
                <div className="top-nav-brand">
                    <img className="nav-logo-mark" src="assets/logo.svg" alt="CRM" />
                </div>

                <div className="top-nav-center">
                    <nav className="view-nav">
                        {[
                            { id: 'dashboard', icon: 'fa-tachometer-alt',      label: 'Dashboard' },
                            { id: 'accounts',  icon: 'fa-building',            label: 'Accounts'  },
                            { id: 'tasks',     icon: 'fa-tasks',               label: 'Tasks'     },
                            { id: 'quotes',    icon: 'fa-file-alt',            label: 'Quotes'    },
                            { id: 'invoices',  icon: 'fa-file-invoice-dollar', label: 'Invoices'  },
                            { id: 'inventory', icon: 'fa-boxes',               label: 'Inventory' },
                        ].map(v => (
                            <button key={v.id} className={`view-nav-btn ${currentView === v.id ? 'active' : ''}`} onClick={() => setCurrentView(v.id)}>
                                <i className={`fas ${v.icon}`}></i><span> {v.label}</span>
                            </button>
                        ))}
                    </nav>
                </div>

                <div className="top-nav-right">
                    <button className="nav-icon-btn" onClick={() => setShowGlobalSearch(true)} title="Search (Ctrl+K)">
                        <i className="fas fa-search"></i>
                    </button>
                    {(currentUser.role === 'admin' || currentUser.role === 'manager') && (
                        <button className="nav-icon-btn" onClick={() => setShowAdmin(true)} title="Admin Panel">
                            <i className="fas fa-shield-alt"></i>
                        </button>
                    )}
                    <div className="nav-user-chip" title={`${currentUser.first_name} ${currentUser.last_name} (${currentUser.role})`}>
                        <span className="nav-avatar">{currentUser.first_name[0]}{currentUser.last_name?.[0] || ''}</span>
                        <span className="nav-user-name">{currentUser.first_name}</span>
                        <span className="nav-role-tag">{currentUser.role}</span>
                    </div>
                    <button className="nav-icon-btn" onClick={() => setShowEmailSettings(true)} title="Email Settings">
                        <i className="fas fa-envelope"></i>
                    </button>
                    <button className="nav-icon-btn" onClick={() => setShowSettings(true)} title="Settings">
                        <i className="fas fa-cog"></i>
                    </button>
                    <button className="nav-icon-btn" onClick={toggleFullscreen} title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
                        <i className={`fas ${isFullscreen ? 'fa-compress' : 'fa-expand'}`}></i>
                    </button>
                    <button className="nav-icon-btn" onClick={onLogout} title="Sign out">
                        <i className="fas fa-sign-out-alt"></i>
                    </button>
                </div>
            </div>

            {/* ── Non-CRM views ── */}
            {currentView === 'dashboard' && <DashboardView onSelectAccount={handleSelectAccountFromSearch} />}
            {currentView === 'tasks'     && (
                <TasksView
                    tasks={data.followUpTasks}
                    accounts={data.accounts}
                    currentUser={currentUser}
                    onSelectAccount={(account) => { setSelectedAccount(account); setCurrentView('accounts'); }}
                    onComplete={handleCompleteTask}
                    onDelete={handleDeleteTask}
                    onCreateTask={async (fd) => {
                        const task = await api.createTask(fd);
                        setData(p => ({ ...p, followUpTasks: [...p.followUpTasks, task] }));
                    }}
                />
            )}
            {currentView === 'inventory' && <ProductsView  currentUser={currentUser} />}
            {currentView === 'quotes'    && <QuotesView    accounts={data.accounts} currentUser={currentUser} />}
            {currentView === 'invoices'  && <InvoicesView  accounts={data.accounts} currentUser={currentUser} />}

            <div className="main-content" style={{ display: currentView === 'accounts' ? 'flex' : 'none' }}>

                {/* ── Sidebar ── */}
                <div className="sidebar">
                    <div className="sidebar-header">
                        <button className="sidebar-new-btn" onClick={() => setShowNewAccount(true)}>
                            <i className="fas fa-plus"></i> New Account
                        </button>
                        <input
                            type="text"
                            className="search-box"
                            placeholder="Search accounts…"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            style={{ marginBottom: (data.tags.length > 0 || currentUser.role !== 'rep') ? '0.75rem' : 0 }}
                        />
                        {data.tags.length > 0 && (
                            <div className="tag-filter-row">
                                {data.tags.map(t => {
                                    const active = tagFilter.includes(t.id);
                                    return (
                                        <button
                                            key={t.id}
                                            className={`tag-pill tag-filter-chip ${active ? 'active' : ''}`}
                                            style={active
                                                ? { background: t.color, color: '#fff', border: `1px solid ${t.color}` }
                                                : { background: t.color + '22', color: t.color, border: `1px solid ${t.color}44` }}
                                            onClick={() => setTagFilter(p => active ? p.filter(id => id !== t.id) : [...p, t.id])}
                                            title={active ? `Stop filtering by ${t.name}` : `Show ${t.name} accounts`}
                                        >
                                            {t.name}
                                        </button>
                                    );
                                })}
                                {tagFilter.length > 0 && (
                                    <button className="tag-filter-clear" onClick={() => setTagFilter([])}>clear</button>
                                )}
                            </div>
                        )}
                        {currentUser.role !== 'rep' && (
                            <div className="my-accounts-toggle">
                                <button className={`toggle-btn ${myAccountsOnly ? 'active' : ''}`} onClick={() => setMyAccountsOnly(true)}>
                                    <i className="fas fa-user" style={{ marginRight: '0.25rem' }}></i>My
                                </button>
                                <button className={`toggle-btn ${!myAccountsOnly ? 'active' : ''}`} onClick={() => setMyAccountsOnly(false)}>
                                    <i className="fas fa-users" style={{ marginRight: '0.25rem' }}></i>All
                                </button>
                            </div>
                        )}
                    </div>

                    <div className="sidebar-content">
                        {loadingData ? (
                            <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
                        ) : filteredAccounts.length === 0 ? (
                            <div className="empty-state">
                                <i className="fas fa-building empty-state-icon"></i>
                                <p className="empty-state-message">{searchTerm ? `No results for "${searchTerm}"` : tagFilter.length > 0 ? 'No accounts match the selected tags.' : 'No accounts yet.'}</p>
                            </div>
                        ) : (
                            <div className="sidebar-account-list">
                                {filteredAccounts.map(account => (
                                    <div
                                        key={account.id}
                                        className={`sidebar-account-item ${selectedAccount?.id === account.id ? 'selected' : ''}`}
                                        onClick={() => setSelectedAccount(account)}
                                    >
                                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: '0.5rem' }}>
                                            <div className="sidebar-account-name">{account.name}</div>
                                            {account.customer_number && <span className="customer-number-badge">{account.customer_number}</span>}
                                        </div>
                                        <div className="sidebar-account-meta">
                                            <span className={`badge ${account.reference_only ? 'secondary' : 'success'}`} style={{ fontSize: '0.65rem' }}>
                                                {account.reference_only ? 'Ref' : 'Active'}
                                            </span>
                                            <span>{account.type}</span>
                                            {account.main_phone && <span><i className="fas fa-phone" style={{ marginRight: '0.2rem' }}></i>{account.main_phone}</span>}
                                            {account.main_email && !account.main_phone && <span><i className="fas fa-envelope" style={{ marginRight: '0.2rem' }}></i>{account.main_email}</span>}
                                        </div>
                                        {(account.tags || []).length > 0 && (
                                            <div className="account-tags-row" style={{ marginTop: '0.375rem' }}>
                                                {account.tags.map(t => (
                                                    <span key={t.id} className="tag-pill" style={{ background: t.color + '22', color: t.color, border: `1px solid ${t.color}44` }}>{t.name}</span>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* ── Workspace ── */}
                <div className="workspace">
                    {selectedAccount ? (
                        <AccountDetailView
                            account={selectedAccount}
                            currentUser={currentUser}
                            allTags={data.tags}
                            allUsers={data.users}
                            onBack={() => setSelectedAccount(null)}
                            onAccountUpdate={(updated) => {
                                setData(p => ({ ...p, accounts: p.accounts.map(a => a.id === updated.id ? updated : a) }));
                                setSelectedAccount(updated);
                            }}
                            onAccountDelete={(id) => {
                                setData(p => ({ ...p, accounts: p.accounts.filter(a => a.id !== id) }));
                                setSelectedAccount(null);
                            }}
                            onMerge={handleMergeAccount}
                            onTagsChange={(tags) => setData(p => ({ ...p, tags }))}
                        />
                    ) : (
                        <div className="crm-empty-workspace">
                            <i className="fas fa-building crm-empty-icon"></i>
                            <h2 className="crm-empty-title">Select an Account</h2>
                            <p className="crm-empty-message">Choose an account from the list to view contacts, communications, quotes, and more.</p>
                            {data.followUpTasks.length > 0 && (
                                <button className="btn btn-secondary" style={{ marginTop: '1rem' }} onClick={() => setCurrentView('tasks')}>
                                    <i className="fas fa-tasks"></i> View {data.followUpTasks.length} Open Task{data.followUpTasks.length !== 1 ? 's' : ''}
                                </button>
                            )}
                        </div>
                    )}
                </div>
            </div>

            {/* ── Modals ── */}
            <Modal isOpen={showNewAccount} onClose={() => setShowNewAccount(false)} title="Create New Account">
                <AccountForm onSubmit={handleCreateAccount} onCancel={() => setShowNewAccount(false)} />
            </Modal>

            {showAdmin && (
                <AdminPanel currentUser={currentUser} onClose={() => setShowAdmin(false)} allTags={data.tags} onTagsChange={() => api.getTags().then(tags => setData(p => ({ ...p, tags })))} />
            )}

            {showSettings && (
                <SettingsModal currentUser={currentUser} onClose={() => setShowSettings(false)} />
            )}

            {showEmailSettings && (
                <EmailSettingsModal currentUser={currentUser} oauthResult={emailOAuthResult} onClose={() => setShowEmailSettings(false)} />
            )}

            {showGlobalSearch && (
                <GlobalSearch onClose={() => setShowGlobalSearch(false)} onSelectAccount={handleSelectAccountFromSearch} />
            )}
        </div>
    );
};
