import { createRoot } from 'react-dom/client';
import { registerSW } from 'virtual:pwa-register';
import App from './App.tsx';
import { ErrorBoundary } from './components/ErrorBoundary.tsx';
import './index.css';

const APP_SHELL_CACHE = 'ajraso-app-shell-runtime';

function collectOriginAppUrls(): string[] {
  const urls = new Set<string>([
    '/',
    '/index.html',
    '/manifest.webmanifest',
    '/manifest.json',
    '/icon.svg',
    '/pwa-192x192.png',
    '/pwa-512x512.png',
    '/pwa-maskable-512x512.png',
    '/apple-touch-icon.png',
    '/assets/aistudio/ajraso_nav_logo_0ca03158.png',
    '/assets/aistudio/A_logo_335828b9.png',
  ]);

  if (typeof document === 'undefined' || typeof window === 'undefined') {
    return Array.from(urls);
  }

  const origin = window.location.origin;
  const addIfSameOriginAppAsset = (rawUrl?: string | null) => {
    if (!rawUrl || rawUrl.startsWith('data:') || rawUrl.startsWith('blob:')) return;
    try {
      const parsed = new URL(rawUrl, origin);
      if (
        parsed.origin === origin &&
        !parsed.pathname.startsWith('/api/') &&
        !parsed.pathname.startsWith('/socket.io')
      ) {
        urls.add(parsed.pathname + parsed.search);
      }
    } catch {
      // Ignore malformed URLs
    }
  };

  document.querySelectorAll('script[src]').forEach((el) => {
    addIfSameOriginAppAsset(el.getAttribute('src'));
  });
  document.querySelectorAll('img[src]').forEach((el) => {
    addIfSameOriginAppAsset(el.getAttribute('src'));
  });
  document.querySelectorAll('link[href]').forEach((el) => {
    const rel = (el.getAttribute('rel') || '').toLowerCase();
    if (rel.includes('stylesheet') || rel.includes('icon') || rel.includes('manifest') || rel.includes('apple-touch')) {
      addIfSameOriginAppAsset(el.getAttribute('href'));
    }
  });

  if (typeof performance !== 'undefined' && typeof performance.getEntriesByType === 'function') {
    const resources = performance.getEntriesByType('resource') as PerformanceResourceTiming[];
    for (const entry of resources) {
      addIfSameOriginAppAsset(entry.name);
    }
  }

  return Array.from(urls);
}

async function requestPersistentOfflineStorage(): Promise<void> {
  try {
    if (typeof navigator !== 'undefined' && navigator.storage && typeof navigator.storage.persist === 'function') {
      const alreadyPersisted =
        typeof navigator.storage.persisted === 'function'
          ? await navigator.storage.persisted()
          : false;
      if (!alreadyPersisted) {
        await navigator.storage.persist();
      }
    }
  } catch {
    // Non-fatal on browsers without StorageManager persist permission
  }
}

async function prewarmOfflineAppShell(registration?: ServiceWorkerRegistration): Promise<void> {
  if (typeof window === 'undefined' || !('caches' in window)) return;
  if (typeof navigator !== 'undefined' && navigator.onLine === false) return;

  try {
    await requestPersistentOfflineStorage();
    const cache = await caches.open(APP_SHELL_CACHE);
    const urls = collectOriginAppUrls();

    // Notify active Service Worker to mirror all URLs into Cache Storage + IndexedDB (AjrasoOfflineShellDB)
    const activeWorker = registration?.active || navigator.serviceWorker?.controller;
    if (activeWorker) {
      try {
        activeWorker.postMessage({ type: 'PREWARM_SHELL', urls });
      } catch {
        // Non-fatal
      }
    }

    await Promise.all(
      urls.map(async (u) => {
        try {
          const cachedAlready = await cache.match(u, { ignoreSearch: false });
          if (cachedAlready) return;
          const res = await fetch(u, { cache: 'default' });
          if (res && res.ok) {
            await cache.put(u, res.clone());
            if (u === '/index.html') {
              await cache.put('/', res.clone());
            }
          }
        } catch {
          // Offline or transient asset miss is non-fatal; never delete existing cache
        }
      })
    );
  } catch {
    // Non-fatal fallback
  }
}

// Register VitePWA Service Worker cleanly for Cache-First / SWR offline reload support
if (
  typeof window !== 'undefined' &&
  'serviceWorker' in navigator &&
  (window.isSecureContext ||
    window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1')
) {
  requestPersistentOfflineStorage().catch(() => {});

  const updateSW = registerSW({
    immediate: true,
    onNeedRefresh() {
      // Promote waiting SW cleanly without forcing an abrupt window reload
      updateSW(false).catch(() => {});
    },
    onOfflineReady() {
      prewarmOfflineAppShell().catch(() => {});
    },
    onRegisteredSW(_swUrl, registration) {
      prewarmOfflineAppShell(registration).catch(() => {});
      if (registration) {
        setInterval(() => {
          if (navigator.onLine) {
            registration.update().catch(() => {});
          }
        }, 60 * 60 * 1000);
      }
    },
    onRegisterError() {
      // Non-fatal fallback
    },
  });

  navigator.serviceWorker.addEventListener('controllerchange', () => {
    navigator.serviceWorker.ready
      .then((registration) => prewarmOfflineAppShell(registration))
      .catch(() => {});
  });

  navigator.serviceWorker.ready
    .then((registration) => {
      prewarmOfflineAppShell(registration).catch(() => {});
      setTimeout(() => {
        prewarmOfflineAppShell(registration).catch(() => {});
      }, 1200);
      setTimeout(() => {
        prewarmOfflineAppShell(registration).catch(() => {});
      }, 4000);
    })
    .catch(() => {});

  window.addEventListener('online', () => {
    navigator.serviceWorker.ready
      .then((registration) => {
        registration.update().catch(() => {});
        return prewarmOfflineAppShell(registration);
      })
      .catch(() => {});
  });
}

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