// Authentication related functions
import { showStatus } from './utils.js';

export let currentUser = null;

export async function checkAuth() {
    try {
        const response = await fetch('/api/auth/check');
        const data = await response.json();
        
        // Check if user has expired
        if (data.expired) {
            showStatus('Account has expired. Please contact an administrator.', 'error');
            // Immediate redirect for expired users
            window.location.href = '/login.html?expired=true';
            throw new Error('Account expired');
        }
        
        if (!data.authenticated) {
            // Immediate redirect for unauthenticated users
            window.location.href = '/login.html';
            throw new Error('Not authenticated');
        }
        
        currentUser = data.user;
        currentUser.userType = data.user.userType || 'user'; // Ensure userType is set
        
        // IMMEDIATE console blocking for all non-admin users - before any other code runs
        if (currentUser.userType !== 'admin') {
            const noop = () => {};
            setTimeout(() => {
                console.log = noop;
                console.debug = noop;
                console.info = noop;
                console.warn = noop;
                console.error = noop;
                console.trace = noop;
                console.dir = noop;
                console.dirxml = noop;
                console.group = noop;
                console.groupEnd = noop;
                console.time = noop;
                console.timeEnd = noop;
                console.assert = noop;
                console.profile = noop;
            }, 1000); // Give 1 second for initialization logs, then block
        }
        
        // Authentication successful - show the app
        document.body.classList.remove('authenticating');
        document.body.classList.add('authenticated');
        document.getElementById('app').classList.remove('app-hidden');
        
        updateUserInterface();
        
    } catch (error) {
        console.error('Auth check failed:', error);
        // Always redirect immediately on any auth failure
        window.location.href = '/login.html';
        throw error;
    }
}

export function updateUserInterface() {
    if (!currentUser) return;

    // CRITICAL: Add body class for temp users FIRST
    if (currentUser.userType === 'temp') {
        document.body.classList.add('temp-user');
    } else {
        document.body.classList.remove('temp-user');
    }
    
    // Also add admin class for consistency
    if (currentUser.isAdmin === true) {
        document.body.classList.add('admin-user');
    } else {
        document.body.classList.remove('admin-user');
    }

    // ----- existing code that manipulates DOM -----
    // Update user email in both desktop and mobile
    const userEmailElement = document.getElementById('user-email');
    const mobileUserEmailElement = document.getElementById('mobile-user-email');
    
    if (userEmailElement) {
        userEmailElement.textContent = currentUser.email;
    }
    if (mobileUserEmailElement) {
        mobileUserEmailElement.textContent = currentUser.email;
    }

    // Control visibility of homepage link for admins
    const homepageLink = document.getElementById('homepage-link');
    if (homepageLink) {
        if (currentUser.isAdmin) {
            homepageLink.style.display = 'inline-flex';
        } else {
            homepageLink.style.display = 'none';
        }
    }
    
    // Get all shifts links/buttons
    const shiftsLinks = document.querySelectorAll('a[href="/shifts.html"]');
    
    if (currentUser.userType === 'temp') {
        // If user is temp, hide all shifts-related elements
        shiftsLinks.forEach(link => {
            const desktopButton = link.closest('.btn');
            const mobileItem = link.closest('.mobile-dropdown-item');
            
            if (desktopButton) {
                desktopButton.classList.add('temp-restricted');
            }
            if (mobileItem) {
                mobileItem.classList.add('temp-restricted');
            }
        });
    } else {
        // If user is NOT temp, ensure all shifts-related elements are visible
        shiftsLinks.forEach(link => {
            const desktopButton = link.closest('.btn');
            const mobileItem = link.closest('.mobile-dropdown-item');

            if (desktopButton) {
                desktopButton.classList.remove('temp-restricted');
            }
            if (mobileItem) {
                mobileItem.classList.remove('temp-restricted');
            }
        });
    }
    
    // Add temp user indicator for temp users
    if (currentUser.userType === 'temp') {
        // Hide user profile links
        const userLinks = document.querySelectorAll('a[href="/user.html"]');
        userLinks.forEach(link => link.style.display = 'none');
        
        // Add temp user indicator
        if (userEmailElement) {
            userEmailElement.innerHTML = `${currentUser.email} <span class="badge temp-badge">Temp</span>`;
        }
        if (mobileUserEmailElement) {
            mobileUserEmailElement.innerHTML = `${currentUser.email} <span class="badge temp-badge">Temp</span>`;
        }
    }
    
    // Add admin link if user is admin
    if (currentUser.isAdmin) {
        addAdminLinks();
    }
    
        // CRITICAL: Final check to hide delete buttons for temp users
    if (currentUser.userType === 'temp') {
        // Use setTimeout to ensure this runs after all other DOM operations
        setTimeout(() => {
            const deleteButtons = document.querySelectorAll('#delete-location-btn, .delete-location-btn, .btn-danger[id*="delete"]');
            deleteButtons.forEach(btn => {
                btn.style.display = 'none';
                btn.style.visibility = 'hidden';
                btn.disabled = true;
                btn.classList.add('temp-hidden');
                btn.setAttribute('hidden', 'true');
            });
        }, 100);
    }
}

function addAdminLinks() {
    // Add admin link to desktop header
    const headerActions = document.querySelector('.header-actions');
    if (headerActions) {
        const adminLink = document.createElement('a');
        adminLink.href = '/admin.html';
        adminLink.className = 'btn btn-secondary';
        adminLink.textContent = '⚙️ Admin';
        headerActions.insertBefore(adminLink, headerActions.firstChild);
    }
    
    // Add admin link to mobile dropdown
    const mobileDropdownContent = document.getElementById('mobile-dropdown-content');
    if (mobileDropdownContent) {
        // Check if admin link already exists
        if (!mobileDropdownContent.querySelector('.admin-link-mobile')) {
            const adminItem = document.createElement('div');
            adminItem.className = 'mobile-dropdown-item admin-link-mobile';
            
            const adminLink = document.createElement('a');
            adminLink.href = '/admin.html';
            adminLink.style.color = 'inherit';
            adminLink.style.textDecoration = 'none';
            adminLink.textContent = '⚙️ Admin Panel';
            
            adminItem.appendChild(adminLink);
            
            // Insert admin link at the top of the dropdown
            if (mobileDropdownContent.firstChild) {
                mobileDropdownContent.insertBefore(adminItem, mobileDropdownContent.firstChild);
            } else {
                mobileDropdownContent.appendChild(adminItem);
            }
        }

        // Add homepage link for mobile dropdown if it doesn't exist
        if (!mobileDropdownContent.querySelector('.homepage-link-mobile')) {
            const homepageItem = document.createElement('div');
            homepageItem.className = 'mobile-dropdown-item homepage-link-mobile';
            
            const homepageLink = document.createElement('a');
            homepageLink.href = '#'; // Or the correct link for homepage
            homepageLink.id = 'mobile-homepage-link';
            homepageLink.style.color = 'inherit';
            homepageLink.style.textDecoration = 'none';
            homepageLink.textContent = '🖥️ Homepage';
            
            homepageItem.appendChild(homepageLink);
            
            // Insert after the admin link
            const adminLink = mobileDropdownContent.querySelector('.admin-link-mobile');
            if (adminLink && adminLink.nextSibling) {
                mobileDropdownContent.insertBefore(homepageItem, adminLink.nextSibling);
            } else if (adminLink) {
                mobileDropdownContent.appendChild(homepageItem);
            } else if (mobileDropdownContent.firstChild) {
                mobileDropdownContent.insertBefore(homepageItem, mobileDropdownContent.firstChild);
            } else {
                mobileDropdownContent.appendChild(homepageItem);
            }

            // Add event listener for mobile homepage link
            const mobileHomepageLink = document.getElementById('mobile-homepage-link');
            const desktopHomepageLink = document.getElementById('homepage-link');
            if (mobileHomepageLink && desktopHomepageLink) {
                mobileHomepageLink.addEventListener('click', (e) => {
                    e.preventDefault();
                    desktopHomepageLink.click();
                });
            }
        }
    }
}
