<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Build: 2025-12-15 - Fix CSP for Google Maps and manifest loading -->
    <!-- Content Security Policy -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' blob:; connect-src 'self' http://localhost:* https://cfa-backend-d0mo.onrender.com wss://cfa-backend-d0mo.onrender.com https://res.cloudinary.com https://btvikrmtqdcgbkgnztwf.supabase.co https://*.supabase.co https://api.openweathermap.org https://openweathermap.org https://api.giphy.com https://*.giphy.com https://fcm.googleapis.com https://ik.imagekit.io https://*.ik.imagekit.io https://*.ingest.us.sentry.io https://*.ingest.sentry.io https://lh3.googleusercontent.com https://maps.googleapis.com https://*.google.com https://api.rainviewer.com https://tilecache.rainviewer.com https://*.rainviewer.com https://api.weather.gov https://api.open-meteo.com https://api.met.no wss: ws:; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://cdnjs.cloudflare.com https://maps.googleapis.com https://maps.gstatic.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https: blob: http://localhost:* https://lh3.googleusercontent.com https://maps.googleapis.com https://maps.gstatic.com; font-src 'self' data: https://fonts.gstatic.com https://btvikrmtqdcgbkgnztwf.supabase.co https://*.supabase.co; media-src 'self' https: blob:; object-src 'self' blob: https://*.supabase.co; worker-src 'self' blob:; manifest-src 'self' http://localhost:* https://cfa-backend-d0mo.onrender.com; frame-src https: blob:; child-src 'self' blob: https:;">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes, viewport-fit=cover">
    <meta name="format-detection" content="telephone=no, date=no, email=no, address=no">
    <meta name="description" content="Access to important company information, documents, training materials, and complete team communication tools.">
    
    <!-- Security Headers -->
    <meta http-equiv="X-Content-Type-Options" content="nosniff">
    <meta http-equiv="Referrer-Policy" content="strict-origin-when-cross-origin">
    
    <!-- DNS Prefetch for external domains -->
    <link rel="dns-prefetch" href="//fonts.googleapis.com">
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link rel="dns-prefetch" href="//cdn.jsdelivr.net">
    
    <!-- Preconnect to critical domains -->
    <link rel="preconnect" href="https://cfa-backend-d0mo.onrender.com">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    <!-- Google Fonts - Outfit (used by AI Assistant) -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap">
    
    <!-- Module Preload for modern browsers -->
    <link rel="modulepreload" href="/js/app-init.js">
    
    <!-- PWA Theme and Capabilities -->
    <meta name="theme-color" content="#004f71">
    <meta name="theme-color" media="(prefers-color-scheme: light)" content="#004f71">
    <meta name="theme-color" media="(prefers-color-scheme: dark)" content="#004f71">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Employee Portal">
    <meta name="apple-touch-fullscreen" content="yes">
    
    <!-- Advanced PWA Features -->
    <meta name="display-mode" content="standalone">
    <meta name="orientation" content="portrait-primary">
    <meta name="color-scheme" content="light">
    
    <!-- Critical CSS for instant rendering -->
    <style>
        /* Critical CSS for app shell - loads instantly */
        * { box-sizing: border-box; margin: 0; padding: 0; }
        html { height: 100%; background-color: #ffffff; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif; }
        body { height: 100%; background-color: #ffffff; color: #333; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif; }
        #root { min-height: 100vh; min-height: 100dvh; width: 100%; }
        
        /* App shell skeleton */
        .app-shell-loading {
            display: flex;
            flex-direction: column;
            height: 100vh;
            background-color: #004F71;
            color: white;
        }
        .app-shell-header {
            height: 64px;
            display: flex;
            align-items: center;
            padding: 0 16px;
            background-color: #004F71;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .app-shell-logo {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 12px;
            background-color: rgba(255,255,255,0.1);
        }
        .app-shell-title {
            font-size: 1.25rem;
            font-weight: 600;
        }
        .app-shell-content {
            flex: 1;
            background-color: #EEEDEB;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        .app-shell-spinner {
            width: 40px;
            height: 40px;
            border: 3px solid rgba(0,79,113,0.3);
            border-radius: 50%;
            border-top-color: #004F71;
            animation: spin 0.8s linear infinite;
        }
        .app-shell-text {
            margin-top: 16px;
            color: #666;
            font-size: 0.875rem;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* Prevent FOUC */
        .loading-hidden { visibility: hidden; }
        .loading-visible { visibility: visible; }
        
        /* Performance optimizations */
        img { content-visibility: auto; }
        .lazy-load { content-visibility: auto; contain-intrinsic-size: 200px; }
    </style>
    <link rel="preconnect" href="https://res.cloudinary.com">
    <!-- Remove unused preconnects that were causing warnings -->
    
    <title>Employee Ops-Portal</title>
    
    <!-- PWA Manifest - Dynamic (fetches from backend with tenant branding) -->
    <link rel="manifest" href="/api/saas/manifest.json" id="pwa-manifest">
    <script>
        // Update manifest URL based on environment
        (function() {
            const manifestLink = document.getElementById('pwa-manifest');
            const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
            
            // Cache busting version - increment this when manifest structure changes
            const manifestVersion = 'v2';
            
            if (isDev) {
                // Development: Use backend server directly
                manifestLink.href = `http://localhost:5000/api/saas/manifest.json?v=${manifestVersion}`;
            } else {
                // Production: Use absolute URL to backend API
                // This ensures the manifest is fetched from the backend, not the frontend domain
                manifestLink.href = `https://cfa-backend-d0mo.onrender.com/api/saas/manifest.json?v=${manifestVersion}`;
            }
            
            console.log('📋 [PWA] Manifest URL configured:', manifestLink.href);
        })();
    </script>
    
    <!-- Favicon and App Icons -->
    <link rel="icon" type="image/png" href="/icons/icon-192x192.png">
    <link rel="shortcut icon" type="image/png" href="/icons/icon-192x192.png">
    
    <!-- Apple Touch Icons for iOS - Must be 180x180 or 192x192, non-transparent PNG -->
    <link rel="apple-touch-icon" href="/icons/icon-192x192.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/icons/icon-192x192.png">
    <link rel="apple-touch-icon" sizes="192x192" href="/icons/icon-192x192.png">
    
    <!-- Safari pinned tab icon -->
    <link rel="mask-icon" href="/icons/icon-192x192.png" color="#004F71">
  <script type="module" crossorigin src="/assets/index-dTNteiZH.js"></script>
  <link rel="stylesheet" crossorigin href="/assets/index-D5yiilyA.css">
</head>
<body>
    <!-- App Shell - Renders instantly while React loads -->
    <div id="app-shell-loading" class="app-shell-loading">
        <div class="app-shell-header">
            <div class="app-shell-logo"></div>
            <div class="app-shell-title">Employee Ops-Portal</div>
        </div>
        <div class="app-shell-content">
            <div class="app-shell-spinner"></div>
            <div class="app-shell-text">Loading...</div>
        </div>
    </div>
    
    <!-- React app root -->
    <div id="root" class="loading-hidden"></div>
    
    <!-- Load Configuration from Backend (Production-Ready) -->
    <script>
        (async function() {
          // Check if running on localhost first
          const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
          
          if (isLocalhost) {
            // Always use localhost:5000 for local development
            console.log('💻 Local development mode detected');
            window.REACT_APP_VAPID_PUBLIC_KEY = 'BF7Cl7dbMtkYTBThy-_fHzZBfnsjSjKhqs0YimfWOQ0FoJnnDskYTG7egd6KhZYfS6ub38wSXjnYF0BKTC9AEGs';
            window.REACT_APP_API_URL = 'http://localhost:5000/api';
            window.REACT_APP_SERVER_URL = 'http://localhost:5000';
            return;
          }
          
          try {
            // Try to fetch config from backend (production only)
            const response = await fetch('/api/config', { signal: AbortSignal.timeout(2000) });
            if (response.ok) {
              const config = await response.json();
              window.REACT_APP_VAPID_PUBLIC_KEY = config.vapidPublicKey;
              window.REACT_APP_API_URL = config.apiUrl;
              window.REACT_APP_SERVER_URL = config.apiUrl;
              console.log('✅ Configuration loaded from backend');
            } else {
              // Non-OK HTTP responses should also use production fallback
              console.log('⚠️ Config endpoint returned', response.status, '- using fallback');
              window.REACT_APP_VAPID_PUBLIC_KEY = window.REACT_APP_VAPID_PUBLIC_KEY || 'BF7Cl7dbMtkYTBThy-_fHzZBfnsjSjKhqs0YimfWOQ0FoJnnDskYTG7egd6KhZYfS6ub38wSXjnYF0BKTC9AEGs';
              window.REACT_APP_API_URL = 'https://cfa-backend-d0mo.onrender.com/api';
              window.REACT_APP_SERVER_URL = 'https://cfa-backend-d0mo.onrender.com';
            }
          } catch (error) {
            // Fallback configuration for production
            console.log('⚠️ Using fallback production configuration');
            window.REACT_APP_VAPID_PUBLIC_KEY = window.REACT_APP_VAPID_PUBLIC_KEY || 'BF7Cl7dbMtkYTBThy-_fHzZBfnsjSjKhqs0YimfWOQ0FoJnnDskYTG7egd6KhZYfS6ub38wSXjnYF0BKTC9AEGs';
            window.REACT_APP_API_URL = 'https://cfa-backend-d0mo.onrender.com/api';
            window.REACT_APP_SERVER_URL = 'https://cfa-backend-d0mo.onrender.com';
          }
        })();
    </script>
    
    <!-- Load Tenant Branding Early (Before React) -->
    <script>
        (async function() {
          try {
            // Determine API URL
            const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
            const apiUrl = isLocalhost ? 'http://localhost:5000/api' : '/api';
            
            // Extract tenant from domain
            const hostname = window.location.hostname;
            let tenantSubdomain = null;
            
            if (hostname.endsWith('.ops-portal.app')) {
              // Remove .ops-portal.app and handle www prefix
              const parts = hostname.replace('.ops-portal.app', '').split('.');
              tenantSubdomain = parts[parts.length - 1]; // Get last part (handles www.tenant case)
              
              if (tenantSubdomain === 'www' && parts.length > 1) {
                tenantSubdomain = parts[0]; // If www, use first part
              }
            } else if (hostname.endsWith('.netlify.app')) {
              // Netlify site / deploy preview / branch deploy → site name is tenant
              // e.g. preview-69--cfakville.netlify.app → cfakville
              const withoutSuffix = hostname.slice(0, -'.netlify.app'.length);
              tenantSubdomain = withoutSuffix.includes('--')
                ? withoutSuffix.split('--').pop()
                : withoutSuffix;
            }
            
            if (!tenantSubdomain) return; // No tenant, use defaults
            
            // Fetch tenant branding using header instead of path parameter
            const response = await fetch(`${apiUrl}/saas/tenant/branding-public`, {
              headers: {
                'X-Tenant-Subdomain': tenantSubdomain
              },
              signal: AbortSignal.timeout(1000)
            });
            
            if (!response.ok) return;
            
            const data = await response.json();
            const tenant = data.tenant;
            
            if (!tenant) return;
            
            // Apply branding immediately to document
            if (tenant.primary_color) {
              document.documentElement.style.setProperty('--primary-color', tenant.primary_color);
              
              // Update theme-color meta tags once at bootstrap (React bodyBackgroundStack owns updates after mount)
              const metaTags = document.querySelectorAll('meta[name="theme-color"]');
              metaTags.forEach(tag => tag.setAttribute('content', tenant.primary_color));
              
              // Update app shell background
              const appShell = document.querySelector('.app-shell-loading');
              const appShellHeader = document.querySelector('.app-shell-header');
              if (appShell) appShell.style.backgroundColor = tenant.primary_color;
              if (appShellHeader) appShellHeader.style.backgroundColor = tenant.primary_color;
            }
            
            if (tenant.secondary_color) {
              document.documentElement.style.setProperty('--secondary-color', tenant.secondary_color);
            }
            
            if (tenant.background_color) {
              document.documentElement.style.setProperty('--tenant-bg-color', tenant.background_color);
            }
            
            // Update page title
            if (tenant.header_logo_text) {
              document.title = tenant.header_logo_text;
              const titleEl = document.querySelector('.app-shell-title');
              if (titleEl) titleEl.textContent = tenant.header_logo_text;
            }
            
            console.log('🎨 Pre-loaded tenant branding for:', tenantSubdomain);
          } catch (error) {
            // Silent fail - React will load branding again
            console.log('⚠️ Could not pre-load branding, will load with React');
          }
        })();
    </script>
    
    <!-- Rescue-only PWA scripts (normal updates are automatic) -->
    <script src="/force-pwa-update.js"></script>
    <script src="/service-worker-migration.js"></script>
    
    <!-- Google Maps API Loader - loads with proper error handling -->
    <script src="/google-maps-loader.js"></script>
    
    <!-- Performance optimization script -->
    <script src="/js/app-init.js"></script>

    <!-- Vite entry point -->
</body>
</html>