// Hide page content immediately to prevent flashing of unauthorized dashboards
document.documentElement.style.display = 'none';

(async function () {
    const token = localStorage.getItem('auth_token');

    // Helper to log out and redirect
    function redirectToLogin() {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_user');
        const currentPath = window.location.pathname;
        const currentPage = currentPath.split('/').pop() || 'index.html';
        const currentQuery = window.location.search;
        
        // Conserva sia la pagina corrente che i parametri di query (es. kiosk=1)
        if (currentPage && currentPage !== 'login.html') {
            const redirectTarget = currentPage + currentQuery;
            window.location.href = `/login.html?redirect=${encodeURIComponent(redirectTarget)}`;
        } else {
            window.location.href = '/login.html';
        }
    }

    function runOnDOMReady(callback) {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', callback);
        } else {
            callback();
        }
    }

    function showAccessDenied(user, message) {
        document.documentElement.style.display = '';
        runOnDOMReady(() => {
            document.body.innerHTML = `
                <div style="min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #0a0e17; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #f8fafc; padding: 20px; box-sizing: border-box;">
                    <div style="max-width: 480px; width: 100%; background: #131b2e; border: 1px solid rgba(239, 68, 68, 0.4); border-radius: 16px; padding: 32px; text-align: center; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.5);">
                        <div style="font-size: 3.5rem; margin-bottom: 15px;">🚫</div>
                        <h1 style="font-size: 1.5rem; font-weight: 700; margin: 0 0 10px 0; color: #ef4444;">Accesso Negato (403)</h1>
                        <p style="font-size: 0.92rem; color: #94a3b8; line-height: 1.5; margin-bottom: 20px;">
                            ${message || 'Il tuo ruolo non dispone dei permessi necessari per visualizzare questa pagina.'}
                        </p>
                        <div style="background: rgba(255, 255, 255, 0.04); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 8px; padding: 12px; margin-bottom: 25px; font-size: 0.85rem; color: #cbd5e1; text-align: left;">
                            <div>👤 Utente: <strong>${user.username || 'Sconosciuto'}</strong></div>
                            <div style="margin-top: 4px;">🏷️ Ruolo: <span style="display: inline-block; padding: 2px 8px; border-radius: 4px; background: rgba(239, 68, 68, 0.2); color: #fca5a5; font-weight: 600; font-size: 0.78rem;">${user.role}</span></div>
                        </div>
                        <div style="display: flex; gap: 10px; justify-content: center;">
                            <a href="/dashboard.html" style="flex: 1; display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 10px 16px; background: #2563eb; color: white; border-radius: 8px; font-size: 0.88rem; font-weight: 600; text-decoration: none;">
                                🏠 Torna alla Dashboard
                            </a>
                            <button onclick="localStorage.removeItem('auth_token'); localStorage.removeItem('auth_user'); window.location.href='/login.html';" style="display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 10px 16px; background: rgba(255, 255, 255, 0.08); color: #cbd5e1; border: 1px solid rgba(255, 255, 255, 0.15); border-radius: 8px; font-size: 0.88rem; font-weight: 500; cursor: pointer;">
                                🚪 Cambia Account
                            </button>
                        </div>
                    </div>
                </div>
            `;
        });
    }

    if (!token) {
        redirectToLogin();
        return;
    }

    // Intercept all future fetch requests globally to inject token header
    const originalFetch = window.fetch;
    window.fetch = async function (resource, options = {}) {
        options.headers = options.headers || {};
        if (options.headers instanceof Headers) {
            options.headers.set('X-Auth-Token', token);
        } else {
            options.headers['X-Auth-Token'] = token;
        }

        try {
            const response = await originalFetch(resource, options);
            if (response.status === 401) {
                redirectToLogin();
            }
            return response;
        } catch (error) {
            console.error("Fetch request failed:", error);
            throw error;
        }
    };

    // Verify authentication against backend
    try {
        const response = await originalFetch('/api/me', {
            headers: { 'X-Auth-Token': token }
        });

        if (!response.ok) {
            redirectToLogin();
            return;
        }

        const user = await response.json();
        localStorage.setItem('auth_user', JSON.stringify(user));

        // Enforce page constraints
        const currentPath = window.location.pathname;
        const currentPage = currentPath.split('/').pop() || 'index.html';

        if (currentPage === 'login.html') {
            const urlParams = new URLSearchParams(window.location.search);
            const redirectUrl = urlParams.get('redirect');
            if (redirectUrl) {
                window.location.href = '/' + redirectUrl;
                return;
            }
            // If logged in, redirect to respective landing page
            if (user.role === 'ADMIN' || user.role === 'SUPER_ADMIN') {
                window.location.href = '/settings.html';
            } else if (user.role === 'CASSIERE') {
                window.location.href = '/cashier.html';
            } else if (user.role === 'CUCINA') {
                if (user.sector === 'PIZZERIA') {
                    window.location.href = '/pizzeria.html';
                } else {
                    window.location.href = '/kitchen_matrix.html';
                }
            } else if (user.role === 'F&B_MANAGER') {
                window.location.href = '/pricing_optimizer.html';
            }
            return;
        }

        if (user.role === 'F&B_MANAGER') {
            if (currentPage !== 'pricing_optimizer.html') {
                showAccessDenied(user, "L'account F&B Manager è abilitato esclusivamente all'Ottimizzazione Prezzi.");
                return;
            }
            setupNavigationTabs(user.role);
            setupHeaderLogout(user);
        } else if (user.role === 'CASSIERE') {
            if (currentPage !== 'cashier.html' && currentPage !== 'resoconto.html') {
                showAccessDenied(user, "La postazione Cassa può accedere unicamente al Monitor Cassa e al Resoconto Serata.");
                return;
            }
            setupNavigationTabs(user.role);
            setupHeaderLogout(user);
        } else if (user.role === 'CUCINA') {
            if (currentPage !== 'kitchen_matrix.html' && currentPage !== 'pizzeria.html') {
                showAccessDenied(user, "La postazione Cucina può accedere unicamente al Monitor Comande di reparto.");
                return;
            }
            lockKitchenStation(user.sector);
            setupNavigationTabs(user.role);
            setupHeaderLogout(user);
        } else if (user.role === 'ADMIN') {
            if (currentPage === 'cashier.html') {
                showAccessDenied(user, "L'accesso al Monitor Cassa è riservato ai Cassieri e al Super Amministratore.");
                return;
            } else if (currentPage === 'kitchen_matrix.html' || currentPage === 'pizzeria.html') {
                showAccessDenied(user, "L'accesso al Monitor Cucina/Pizzeria è riservato agli operatori di Cucina e al Super Amministratore.");
                return;
            } else if (currentPage === 'installer.html') {
                showAccessDenied(user, "L'accesso all'Installer e agli Aggiornamenti è riservato esclusivamente al Super Amministratore.");
                return;
            } else if (currentPage === 'guida_tecnica.html') {
                showAccessDenied(user, "L'accesso al Manuale Tecnico è riservato esclusivamente al Super Amministratore.");
                return;
            }
            setupNavigationTabs(user.role);
            setupHeaderLogout(user);
        } else if (user.role === 'SUPER_ADMIN') {
            setupNavigationTabs(user.role);
            setupHeaderLogout(user);
        }

        // Authentication succeeded and roles verified, reveal content
        document.documentElement.style.display = '';

    } catch (error) {
        console.error("Auth script verification error:", error);
        redirectToLogin();
    }

    // Dynamic UI helper functions
    function setupNavigationTabs(role) {
        runOnDOMReady(() => {
            const tabBtns = document.querySelectorAll('.tab-btn');
            tabBtns.forEach(btn => {
                const href = btn.getAttribute('href');
                if (!href) return;
                const page = href.split('/').pop().split('?')[0];
                
                let allowed = false;
                if (role === 'SUPER_ADMIN') {
                    allowed = true;
                } else if (role === 'ADMIN') {
                    if (page !== 'cashier.html' && page !== 'kitchen_matrix.html' && page !== 'installer.html') {
                        allowed = true;
                    }
                } else if (role === 'CASSIERE') {
                    if (page === 'cashier.html' || page === 'resoconto.html') {
                        allowed = true;
                    }
                } else if (role === 'CUCINA') {
                    if (page === 'kitchen_matrix.html' || page === 'pizzeria.html') {
                        allowed = true;
                    }
                }
                
                if (allowed) {
                    btn.style.display = 'inline-flex';
                } else {
                    btn.style.display = 'none';
                }
            });
        });
    }

    function setupHeaderLogout(user) {
        runOnDOMReady(() => {
            const header = document.querySelector('header');
            if (header) {
                // Find or create badge container on the right side of header
                let badgeContainer = header.querySelector(':scope > div:last-of-type');
                
                // If there is no right container, or if the matched div is just a badge (not a wrapper), create one
                if (!badgeContainer || badgeContainer === header.querySelector('.logo') || badgeContainer.classList.contains('badge')) {
                    badgeContainer = document.createElement('div');
                    badgeContainer.style.display = 'flex';
                    badgeContainer.style.gap = '10px';
                    badgeContainer.style.alignItems = 'center';
                    header.appendChild(badgeContainer);
                }

                // Add or update the user badge
                let userBadge = document.getElementById('user-profile-badge');
                if (!userBadge) {
                    userBadge = document.createElement('div');
                    userBadge.id = 'user-profile-badge';
                    userBadge.className = 'badge badge-validated';
                    userBadge.style.fontSize = '0.78rem';
                    userBadge.style.display = 'inline-flex';
                    userBadge.style.alignItems = 'center';
                    userBadge.style.gap = '5px';
                    badgeContainer.insertBefore(userBadge, badgeContainer.firstChild);
                }
                
                const roleLabels = {
                    'SUPER_ADMIN': '👑 Super Amministratore',
                    'ADMIN': '🔧 Amministratore',
                    'CASSIERE': '👤 Cassa',
                    'CUCINA': `🍳 Cucina (${user.sector || '?'})`,
                    'F&B_MANAGER': '📊 Food & Beverage Manager'
                };
                userBadge.innerText = `${roleLabels[user.role]}: ${user.username}`;

                // Add Logout button if not already exists
                if (!document.getElementById('header-logout-btn')) {
                    const logoutBtn = document.createElement('button');
                    logoutBtn.id = 'header-logout-btn';
                    logoutBtn.className = 'btn btn-secondary btn-sm';
                    logoutBtn.style.padding = '4px 10px';
                    logoutBtn.style.fontSize = '0.75rem';
                    logoutBtn.style.borderColor = 'var(--color-danger)';
                    logoutBtn.style.color = 'var(--color-danger)';
                    logoutBtn.innerHTML = '🚪 Esci';
                    logoutBtn.onclick = handleLogout;
                    badgeContainer.appendChild(logoutBtn);
                }
            }
        });
    }

    function lockKitchenStation(sector) {
        // Enforce the selected station in kitchen_matrix.html
        localStorage.setItem('kitchen_station', sector);
        runOnDOMReady(() => {
            const changeStationBtn = document.getElementById('change-station-btn');
            if (changeStationBtn) {
                changeStationBtn.style.display = 'none';
            }
            const selectorModal = document.getElementById('station-selector-modal');
            if (selectorModal) {
                selectorModal.style.display = 'none';
                selectorModal.classList.remove('active');
            }
            const mainContent = document.getElementById('dashboard-main-content');
            if (mainContent) {
                mainContent.style.display = 'grid';
            }
        });
    }

    async function handleLogout() {
        const token = localStorage.getItem('auth_token');
        if (token) {
            try {
                await fetch('/api/logout', { method: 'POST' });
            } catch (e) {
                console.error("Logout request failed:", e);
            }
        }
        redirectToLogin();
    }
})();
