// Admin Authentication Protection
// Add this script to all admin pages to require login

(function() {
  'use strict';

  // Check if user is authenticated
  function checkAuth() {
    const token = localStorage.getItem('admin_token');
    const currentPage = window.location.pathname;
    
    // If no token and not on login page, redirect to login
    if (!token && !currentPage.includes('admin-login.html')) {
      window.location.href = '/admin-login.html';
      return false;
    }

    // If token exists, verify it
    if (token && !currentPage.includes('admin-login.html')) {
      fetch('/api/auth/verify', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      .then(response => {
        if (!response.ok) {
          // Token invalid, clear and redirect
          localStorage.removeItem('admin_token');
          localStorage.removeItem('admin_user');
          window.location.href = '/admin-login.html';
        }
      })
      .catch(() => {
        // Network error, allow staying on page but show warning
        console.warn('Unable to verify authentication');
      });
    }

    return true;
  }

  // Add logout functionality
  function setupLogout() {
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', (e) => {
        e.preventDefault();
        
        // Clear auth data
        localStorage.removeItem('admin_token');
        localStorage.removeItem('admin_user');
        localStorage.removeItem('remember_admin');
        
        // Redirect to login
        window.location.href = '/admin-login.html';
      });
    }
  }

  // Display user info
  function displayUserInfo() {
    const userDisplay = document.getElementById('userDisplay');
    if (userDisplay) {
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      if (user.email) {
        userDisplay.textContent = user.email;
      }
    }
  }

  // Run on page load
  document.addEventListener('DOMContentLoaded', () => {
    checkAuth();
    setupLogout();
    displayUserInfo();
  });

  // Export for use in other scripts
  window.adminAuth = {
    checkAuth: checkAuth,
    logout: () => {
      localStorage.removeItem('admin_token');
      localStorage.removeItem('admin_user');
      localStorage.removeItem('remember_admin');
      window.location.href = '/admin-login.html';
    },
    getToken: () => localStorage.getItem('admin_token'),
    getUser: () => JSON.parse(localStorage.getItem('admin_user') || '{}')
  };
})();
