// FIX: Moved import statements to the top-level of the module, as required by JavaScript syntax.
import React from 'react';
import ReactDOM from 'react-dom/client';
import SystemInitializer from './SystemInitializer.tsx';
import { syncOfflineSales } from './lib/sync.ts';

// Add a global error handler to catch unhandled promise rejections
window.addEventListener('unhandledrejection', function(event) {
  console.error('DEBUG: Unhandled Promise Rejection:', event.reason);
  const errorDisplay = document.getElementById('error-display');
  if (errorDisplay) {
    errorDisplay.style.display = 'block';
    const reason = event.reason || {};
    errorDisplay.textContent += `\n\n[UNHANDLED PROMISE REJECTION]: ${reason.message || String(reason)}`;
  }
});


// Main application logic wrapped in a try-catch
try {
  console.log('DEBUG: index.tsx script started execution.');
  
  console.log('DEBUG: All imports in index.tsx were successfully resolved.');

  const rootElement = document.getElementById('root');
  if (!rootElement) {
    console.error("DEBUG: CRITICAL ERROR - Could not find root element to mount to.");
    throw new Error("Could not find root element with id='root'");
  }
  console.log("DEBUG: Root element with id='root' was found successfully.", rootElement);


  const root = ReactDOM.createRoot(rootElement);
  console.log("DEBUG: React root created.");

  root.render(
    <React.StrictMode>
      <SystemInitializer />
    </React.StrictMode>
  );
  console.log("DEBUG: React application rendered into the root element.");


  // Register the service worker for PWA capabilities
  if ('serviceWorker' in navigator) {
    console.log("DEBUG: Service Worker API is available.");
    window.addEventListener('load', () => {
      console.log("DEBUG: Window loaded, attempting to register Service Worker.");
      navigator.serviceWorker.register('/sw.js').then(registration => {
        console.log('DEBUG: ServiceWorker registration successful with scope: ', registration.scope);
        
        // Initial sync check on load
        console.log("DEBUG: Triggering initial offline sales sync.");
        syncOfflineSales();

        // Listen for online event to trigger sync
        window.addEventListener('online', syncOfflineSales);
        console.log("DEBUG: 'online' event listener for sync added.");

      }, err => {
        console.error('DEBUG: ServiceWorker registration failed: ', err);
      });
    });
  } else {
    console.warn("DEBUG: Service Worker API is not available in this browser.");
  }
} catch (e) {
  console.error('DEBUG: A critical error occurred during application initialization:', e);
  const errorDisplay = document.getElementById('error-display');
  if (errorDisplay) {
    // FIX: Replaced TypeScript 'as' casting with standard JavaScript property access.
    // This resolves the Babel parsing SyntaxError.
    const error = e || {};
    errorDisplay.style.display = 'block';
    errorDisplay.textContent = `A fatal error occurred:\n\n${error.message || String(e)}\n\nStack Trace:\n${error.stack || ''}`;
  }
}