// ---------------------------------------------------------------------------
// Native production console silencer — MUST run before anything else.
//
// On Android, every `console.log/info/debug/warn` from JS crosses the
// Capacitor bridge via `BridgeWebChromeClient.onConsoleMessage`, which runs
// on the WebView's UI thread. Under load (health checks, realtime, polling,
// React render logs) this saturates the main thread and Google Play reports
// it as "Input dispatching timed out" ANRs (visible in v1.0.37 Vitals).
//
// We keep `console.error` so real crashes still surface in Crashlytics /
// Logcat. Dev/preview keeps everything for debugging.
// ---------------------------------------------------------------------------
try {
  const cap: any = (window as any).Capacitor;
  const isNative = !!cap?.isNativePlatform?.();
  const isProd = !(import.meta as any).env?.DEV;
  if (isNative && isProd) {
    const noop = () => {};
    // eslint-disable-next-line no-console
    console.log = noop;
    // eslint-disable-next-line no-console
    console.info = noop;
    // eslint-disable-next-line no-console
    console.debug = noop;
    // eslint-disable-next-line no-console
    console.warn = noop;
  }
} catch (_) {}

// Global error handler - must be first before any imports can fail
window.addEventListener('error', (event) => {
  console.error('🚨 Global error:', event.error);
});

// Handle Service Worker and other non-critical promise rejections gracefully
window.addEventListener('unhandledrejection', (event) => {
  const reason = event.reason;
  const message = reason?.message || String(reason) || '';
  const stack = reason?.stack || '';
  
  const nonCriticalPatterns = [
    'registerSW',
    'ServiceWorker',
    'sw.js',
    'CHANNEL_ERROR',
    'Subscription timeout',
    'Capacitor',
    'not implemented',
  ];
  
  const isNonCritical = nonCriticalPatterns.some(pattern => 
    message.includes(pattern) || stack.includes(pattern)
  );
  
  if (isNonCritical) {
    event.preventDefault();
    console.log('🔇 Non-critical rejection handled:', message.substring(0, 100));
    return;
  }
});

// Async initialization - don't block app render
const initializeAsync = async () => {
  try {
    const { initializeCrashReporting } = await import('./utils/crashReporting');
    initializeCrashReporting();
  } catch (error) {
    console.warn('Crash reporting initialization failed:', error);
  }
};

// Start async init but don't wait for it
initializeAsync();

import './global.css';
import './index.css';
import { createRoot } from 'react-dom/client';
import { installViewportSelfHeal } from './utils/viewportReset';
import { installToastFilter } from './utils/toastFilter';

// Install global toast filter ASAP so the very first imperative toast call
// (load failures from admin panels mounting at boot, push hook errors, etc.)
// is already filtered before the Toaster element mounts.
installToastFilter();

// Native-only: auto-reset viewport after keyboard hide / OTP autofill / modal close.
installViewportSelfHeal();

/* ---------------------------------------------------------------------- */
/* Flavor detection — MUST happen before any App import so the customer    */
/* runtime is never evaluated inside the vendor binary.                    */
/* ---------------------------------------------------------------------- */
const detectVendorRuntime = (): boolean => {
  try {
    if ((import.meta as any).env?.VITE_APP_FLAVOR === 'vendor') return true;
    const cap: any = (window as any).Capacitor;
    const cfg = cap?.getConfig?.() || {};
    const appId = String(cfg.appId || '').toLowerCase();
    const appName = String(cfg.appName || '').toLowerCase();
    const initialPath = String(cfg.server?.initialPath || '').toLowerCase();
    if (appId === 'com.pomaago.vendor' || appId.includes('.vendor')) return true;
    if (appName.includes('vendor')) return true;
    if (initialPath.startsWith('/vendor')) return true;
    const path = window.location.pathname.toLowerCase();
    if (path.startsWith('/vendor')) return true;
  } catch {}
  return false;
};

const IS_VENDOR_RUNTIME = detectVendorRuntime();

// Brand document for vendor binary
if (IS_VENDOR_RUNTIME) {
  try {
    document.title = 'Pomaa Go Vendor — Manage your store';
    const desc = document.querySelector('meta[name="description"]');
    if (desc) desc.setAttribute('content', 'Pomaa Go Vendor: manage your store, orders, menu, and payouts on Pomaa Go.');
    const apple = document.querySelector('meta[name="apple-mobile-web-app-title"]');
    if (apple) apple.setAttribute('content', 'Pomaa Go Vendor');
  } catch {}
}

// Safe storage import - synchronous to avoid top-level await blocking
import { safeStorage } from './utils/safeStorage';

// Visible runtime marker so we can confirm exactly which build is live
try {
  const buildMeta = document.querySelector('meta[name="app-build-version"]') as HTMLMetaElement | null;
  console.log(
    `%c[Pomaa Go] Build v1.0.46 (83) — html:${buildMeta?.content || 'n/a'}`,
    'color:#ea580c;font-weight:bold',
  );
} catch (_) {}

// Lovable previews/development must never be controlled by a stale service
// worker. Keep push SW behavior for production/native, but aggressively clear
// preview workers/caches so route changes and app fixes appear immediately.
const isPreviewLikeHost = (() => {
  try {
    const host = window.location.hostname;
    return (
      host === 'localhost' ||
      host === '127.0.0.1' ||
      host.includes('lovable') ||
      host.includes('lovableproject') ||
      host.includes('sandbox')
    );
  } catch (_) {
    return false;
  }
})();

if (isPreviewLikeHost) {
  try {
    safeStorage.removeItem('appBuildVersion');
    safeStorage.removeItem('appLastReloadTime');
    safeStorage.removeItem('appLastReloadVersion');
    safeStorage.removeItem('pomaa_last_route');
    safeStorage.removeItem('pomaa_admin_route');
    safeStorage.removeItem('pomaa_admin_active_section');
  } catch (_) {}
  try {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.getRegistrations()
        .then((regs) => Promise.all(regs.map((r) => r.unregister())))
        .catch(() => {});
    }
    if ('caches' in window) {
      caches.keys()
        .then((keys) => Promise.all(keys.map((k) => caches.delete(k))))
        .catch(() => {});
    }
  } catch (_) {}
}

// Build version check: force-refresh clients when a new build is deployed.
// Disabled on Capacitor native shells (the app uses native update flow) and on
// preview hosts. Hard-capped to ONE reload per session to self-heal any loop.
let isReloading = false;
const isCapNative = !!(window as any).Capacitor?.isNativePlatform?.();
try {
  const meta = document.querySelector('meta[name="app-build-version"]') as HTMLMetaElement | null;
  const current = meta?.content;
  const reloadedThisSession = (() => {
    try { return sessionStorage.getItem('app_reloaded_once') === '1'; } catch { return false; }
  })();
  if (current && !isPreviewLikeHost && !isCapNative && !reloadedThisSession) {
    const prev = safeStorage.getItem('appBuildVersion');

    if (prev && prev !== current) {
      // Tight loop guard ONLY: if we already reloaded for *this* version in the
      // last 10s, skip. Otherwise always reload so freshly-published bundles win.
      const lastReloadVersion = safeStorage.getItem('appLastReloadVersion');
      const lastReload = safeStorage.getItem('appLastReloadTime');
      const now = Date.now();
      const recentSameVersionReload =
        lastReloadVersion === current && lastReload && now - parseInt(lastReload, 10) < 10000;

      if (recentSameVersionReload) {
        console.log('📦 Version reload already happened in last 10s — skipping to avoid loop');
        safeStorage.setItem('appBuildVersion', current);
      } else {
        safeStorage.setItem('appBuildVersion', current);
        safeStorage.setItem('appLastReloadTime', now.toString());
        safeStorage.setItem('appLastReloadVersion', current);
        // Always clear the mount flag so the next boot does not short-circuit
        try { sessionStorage.removeItem('app_mounted'); } catch (_) {}
        console.log(`📦 New app version detected: ${current} (previous: ${prev}). Hard reloading...`);
        isReloading = true;
        const clearPromises: Promise<any>[] = [];
        if ('caches' in window) {
          clearPromises.push(
            caches.keys().then(keys => Promise.all(keys.map(k => caches.delete(k)))).catch(() => {})
          );
        }
        if ('serviceWorker' in navigator) {
          clearPromises.push(
            navigator.serviceWorker.getRegistrations().then(regs => Promise.all(regs.map(r => r.unregister()))).catch(() => {})
          );
        }
        Promise.all(clearPromises).finally(() => {
          try { sessionStorage.setItem('app_reloaded_once', '1'); } catch (_) {}
          window.location.reload();
        });
      }
    } else if (!prev) {
      safeStorage.setItem('appBuildVersion', current);
    }
  }
} catch (_) {
  // Never block app boot due to version/check issues
}

// SW_UPDATED auto-reload removed: caused reload loops on Capacitor native shells
// when stale shipped SW (older version) re-activated on every cold start. The
// service worker still purges caches on activate; tabs pick up new bundles on
// the next natural navigation. Native app updates flow through useNativeAppUpdate.

// CRITICAL: Native app redirect - runs BEFORE React mounts
// This ensures landing pages NEVER render on native apps, and vendor native
// shells always enter the vendor experience even if the build env was missed.
// IMPORTANT: Only use Capacitor.isNativePlatform() - user agent checks cause false positives on Android browsers
try {
  const isNative = !!(window as any).Capacitor?.isNativePlatform?.();
  const currentPath = window.location.pathname;
  
  const capacitorConfig = (window as any).Capacitor?.getConfig?.() || {};
  const appId = String(capacitorConfig.appId || '').toLowerCase();
  const appName = String(capacitorConfig.appName || '').toLowerCase();
  const initialPath = String(capacitorConfig.server?.initialPath || '').toLowerCase();
  const isVendorShell = appId === 'com.pomaago.vendor' || appName.includes('vendor') || initialPath.startsWith('/vendor');

  // Only redirect if Capacitor explicitly confirms we're on a native platform
  if (isNative && (currentPath === '/' || currentPath === '/landing')) {
    const target = isVendorShell ? '/vendor/login' : '/portal';
    console.log(`[main.tsx] Native platform detected, redirecting to ${target}`);
    window.location.replace(target);
  }
} catch (_) {}

// Redirect recovery links to the password reset page BEFORE React mounts
try {
  const { pathname, hash, search } = window.location;
  const params = new URLSearchParams(search);
  const hasQueryRecovery = (params.get('type')?.toLowerCase() === 'recovery') && (params.get('token_hash') || params.get('token') || params.get('code'));
  const hasHashRecovery = hash.includes('type=recovery') || (hash.includes('access_token') && hash.includes('refresh_token'));
  const hasCode = !!params.get('code'); // PKCE/code flow
  if ((hasQueryRecovery || hasHashRecovery || hasCode) && pathname !== '/password-reset') {
    const suffix = (hasQueryRecovery || hasCode) ? search : hash;
    window.location.replace(`/password-reset${suffix}`);
  }
} catch (_) {
  // Do nothing on failure
}

// Mount app with error boundary — skip if we're about to hard-reload
if (!isReloading) {
  // Mark that the app has mounted in this session to prevent version-check reloads
  try { sessionStorage.setItem('app_mounted', '1'); } catch (_) {}
  const rootElement = document.getElementById("root");
  if (rootElement) {
    // Dynamically import EITHER the customer App OR the standalone VendorApp.
    // This ensures the customer module graph is never evaluated in the vendor
    // binary and vice-versa.
    const loader = IS_VENDOR_RUNTIME
      ? import('./VendorApp.tsx')
      : import('./App.tsx');
    loader
      .then(({ default: RootComponent }) => {
        try {
          createRoot(rootElement).render(<RootComponent />);
        } catch (error) {
          console.error('🚨 Failed to render app:', error);
          rootElement.innerHTML = `
            <div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:20px;font-family:system-ui;">
              <div style="text-align:center;max-width:400px;">
                <h1 style="color:#ef4444;margin-bottom:16px;">App Failed to Load</h1>
                <p style="color:#666;margin-bottom:16px;">Please try refreshing the page.</p>
                <button onclick="location.reload()" style="padding:12px 24px;background:#3b82f6;color:white;border:none;border-radius:8px;cursor:pointer;">
                  Refresh Page
                </button>
              </div>
            </div>
          `;
        }
      })
      .catch((err) => {
        console.error('🚨 Failed to load root component:', err);
      });
  } else {
    console.error('Root element not found');
  }
}
