// Main initialization script
import { initializeSupabase } from '/lib/init-supabase-cpanel.js';
import connectionStatusIndicator from '/lib/connection-status-indicator.js';
import realTimeSyncCPanel from '/lib/real-time-sync-cpanel.js';
import offlineSync from '/lib/offline-sync.js';

// Function to redirect to database setup page
function redirectToSetup() {
  console.log('Redirecting to database setup page...');
  
  // Check if we're in a cPanel environment or regular hosting
  const isProduction = window.location.hostname !== 'localhost' && 
                      window.location.hostname !== '127.0.0.1' && 
                      !window.location.hostname.includes('stackblitz') &&
                      !window.location.hostname.includes('webcontainer');
  
  // Show user-friendly message before redirect
  const message = document.createElement('div');
  message.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  `;
  
  message.innerHTML = `
    <div style="
      background: white;
      padding: 40px;
      border-radius: 16px;
      box-shadow: 0 20px 40px rgba(0,0,0,0.1);
      text-align: center;
      max-width: 500px;
      margin: 20px;
    ">
      <h2 style="color: #2d3748; margin-bottom: 16px; font-size: 1.5rem;">Database Setup Required</h2>
      <p style="color: #718096; margin-bottom: 24px; line-height: 1.6;">
        Your database needs to be initialized before you can use the application. 
        You'll be redirected to the setup page in a moment.
      </p>
      <div style="
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 2px solid #e2e8f0;
        border-top: 2px solid #4299e1;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      "></div>
      <style>
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      </style>
    </div>
  `;
  
  document.body.appendChild(message);
  
  // Redirect after a short delay to show the message
  setTimeout(() => {
    if (isProduction) {
      window.location.href = 'init-db-cpanel.html';
    } else {
      window.location.href = 'init-db.html';
    }
  }, 2000);
}

// Initialize when the page loads
document.addEventListener('DOMContentLoaded', async function() {
  console.log('Initializing application...');
  
  try {
    // Initialize connection status indicator
    connectionStatusIndicator.initialize();
    
    // Initialize Supabase and check if successful
    console.log('Starting Supabase initialization...');
    const supabaseInitialized = await initializeSupabase();
    
    if (!supabaseInitialized) {
      console.warn('Supabase initialization failed - redirecting to setup page');
      redirectToSetup();
      return;
    }
    
    console.log('Supabase initialized successfully');
    
    // Initialize real-time sync for cPanel
    await realTimeSyncCPanel.initialize();
    
    // Initialize offline sync
    offlineSync.initialize();
    
    // Initialize website functionality
    if (typeof initializeWebsite === 'function') {
      initializeWebsite();
    }
    
    console.log('Application initialized successfully');
    
  } catch (error) {
    console.error('Application initialization failed:', error);
    console.log('Redirecting to setup page due to initialization error');
    redirectToSetup();
  }
});