
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import './i18n'
import { Capacitor } from '@capacitor/core';

// Native (Capacitor) status bar setup — makes Android match the PWA layout.
// Use overlay mode so env(safe-area-inset-top) reports the real status-bar
// height and our drawer/header padding lines up with the PWA.
if (Capacitor.isNativePlatform()) {
  import('@capacitor/status-bar').then(({ StatusBar, Style }) => {
    StatusBar.setOverlaysWebView({ overlay: true }).catch(() => {});
    StatusBar.setBackgroundColor({ color: '#16a34a' }).catch(() => {});
    StatusBar.setStyle({ style: Style.Light }).catch(() => {});
  }).catch(() => {});
  document.documentElement.classList.add('capacitor-native');
}

// Capture beforeinstallprompt globally BEFORE React mounts so it's never missed
(window as any).__pwaInstallPrompt = null;
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  (window as any).__pwaInstallPrompt = e;
});

createRoot(document.getElementById("root")!).render(<App />);

// Hide the initial loading splash once React has rendered and painted a frame.
// Two rAFs guarantees we run after commit + paint. A short delay smooths the fade.
requestAnimationFrame(() => {
  requestAnimationFrame(() => {
    setTimeout(() => {
      (window as any).__hideAppLoader?.();
    }, 150);
  });
});


// Register service worker for PWA installability (production only, not in iframes)
if ('serviceWorker' in navigator) {
  const isInIframe = (() => {
    try { return window.self !== window.top; } catch { return true; }
  })();
  const isPreview = window.location.hostname.includes('id-preview--') || window.location.hostname.includes('lovableproject.com');

  if (!isInIframe && !isPreview) {
    // The CRM service worker must never own the marketing website root. Remove
    // legacy root-scoped registrations, then register only for /app/.
    navigator.serviceWorker.getRegistrations().then(async (registrations) => {
      const appScope = `${window.location.origin}/app/`;
      await Promise.all(
        registrations
          .filter((registration) => registration.scope !== appScope)
          .map((registration) => registration.unregister()),
      );

      if (/^\/app(?:\/|$)/.test(window.location.pathname)) {
        await navigator.serviceWorker.register('/sw.js', { scope: '/app/' });
      }
    }).catch(() => {});

    navigator.serviceWorker.addEventListener('message', (event) => {
      if (event.data?.type !== 'SW_UPDATED') return;

      // Never reload mid-authentication: the URL carries the token/code that
      // Supabase needs to establish the session, and a reload discards it.
      const authMarkers = /(access_token|refresh_token|code=|error_description|type=recovery)/;
      if (authMarkers.test(window.location.hash) || authMarkers.test(window.location.search)) return;

      // Guard against reload loops (one refresh per tab session).
      try {
        if (sessionStorage.getItem('sw-reloaded') === '1') return;
        sessionStorage.setItem('sw-reloaded', '1');
      } catch { /* ignore */ }

      const doReload = () => { window.location.reload(); };
      if ('caches' in window) {
        caches.keys().then(names => Promise.all(names.map(n => caches.delete(n))))
          .then(doReload).catch(doReload);
      } else {
        doReload();
      }
    });
  } else {
    // Clean up any stale SW in preview/iframe
    navigator.serviceWorker.getRegistrations().then(regs => regs.forEach(r => r.unregister()));
  }
}

// Prevent zooming on mobile devices and improve touch experience
document.addEventListener('touchmove', (e: TouchEvent) => {
  // Prevent pinch zoom
  if (e.touches.length > 1) {
    e.preventDefault();
  }
}, { passive: false });

// Prevent double-tap zoom
let lastTouchEnd = 0;
document.addEventListener('touchend', (e) => {
  const now = (new Date()).getTime();
  if (now - lastTouchEnd <= 300) {
    e.preventDefault();
  }
  lastTouchEnd = now;
}, false);

// Add viewport meta tag if not present
if (!document.querySelector('meta[name="viewport"]')) {
  const viewport = document.createElement('meta');
  viewport.name = 'viewport';
  viewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover';
  document.head.appendChild(viewport);
}
