import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'

declare const __APP_VERSION__: string;

/**
 * Auto-update detector.
 * Polls index.html every 30s. When the hashed bundle name changes we reload
 * immediately on next route change, or after a short idle window if the user
 * is sitting still — no hard refresh required.
 */
(function setupAutoReload() {
  if (typeof window === 'undefined') return;
  let currentAssets: string | null = null;
  let updatePending = false;
  const VERSION_KEY = 'grayinvested-app-version';
  const FORCE_REFRESH_KEY = 'grayinvested-force-refresh-v3';
  const BUILD_VERSION = typeof __APP_VERSION__ === 'string' ? __APP_VERSION__ : 'dev';

  const purgeOldCaches = async () => {
    if (!('caches' in window)) return;
    try {
      const keys = await caches.keys();
      await Promise.all(keys.map((key) => caches.delete(key)));
    } catch {
      /* browser cache APIs can be unavailable in strict modes */
    }
  };

  const unregisterServiceWorkers = async () => {
    if (!('serviceWorker' in navigator)) return;
    try {
      const registrations = await navigator.serviceWorker.getRegistrations();
      await Promise.all(registrations.map((registration) => registration.unregister()));
    } catch {
      /* old service workers should not block app boot */
    }
  };

  const captureCurrent = () => {
    const assetUrls = Array.from(document.querySelectorAll<HTMLScriptElement | HTMLLinkElement>('script[src], link[href*="/assets/"]'))
      .map((el) => ('src' in el ? el.src : el.href))
      .filter((url) => /\/assets\/.*\.(js|css)/.test(url))
      .map((url) => url.split('/').pop())
      .sort();
    currentAssets = assetUrls.join('|') || null;
  };

  const reloadNow = () => {
    if (!updatePending) return;
    updatePending = false;
    sessionStorage.setItem(VERSION_KEY, BUILD_VERSION);
    window.location.reload();
  };

  const checkForUpdate = async () => {
    if (updatePending) return;
    try {
      const res = await fetch(`/index.html?_=${Date.now()}`, { cache: 'no-store' });
      if (!res.ok) return;
      const html = await res.text();
      const latestAssets = Array.from(html.matchAll(/\/assets\/[A-Za-z0-9_.-]+\.(js|css)/g))
        .map((match) => match[0].split('/').pop())
        .sort()
        .join('|');
      if (latestAssets && currentAssets && latestAssets !== currentAssets) {
        updatePending = true;
        // Reload on any route change, tab focus change, or after 5s idle.
        window.addEventListener('popstate', reloadNow);
        window.addEventListener('hashchange', reloadNow);
        document.addEventListener('visibilitychange', () => {
          if (document.visibilityState === 'visible') reloadNow();
        });
        setTimeout(reloadNow, 5000);
      }
    } catch {
      /* transient — retry next tick */
    }
  };

  window.addEventListener('load', () => {
    const url = new URL(window.location.href);
    if (url.searchParams.has('v')) {
      url.searchParams.delete('v');
      window.history.replaceState(window.history.state, document.title, `${url.pathname}${url.search}${url.hash}`);
    }

    if (localStorage.getItem(FORCE_REFRESH_KEY) !== BUILD_VERSION) {
      localStorage.setItem(FORCE_REFRESH_KEY, BUILD_VERSION);
      Promise.all([purgeOldCaches(), unregisterServiceWorkers()]).finally(() => {
        window.location.reload();
      });
      return;
    }
    const storedVersion = sessionStorage.getItem(VERSION_KEY);
    if (storedVersion !== BUILD_VERSION) {
      sessionStorage.setItem(VERSION_KEY, BUILD_VERSION);
      purgeOldCaches();
    }
    captureCurrent();
    if (!currentAssets) return;
    checkForUpdate();
    setTimeout(checkForUpdate, 3_000);
    setInterval(checkForUpdate, 15_000);
    window.addEventListener('focus', checkForUpdate);
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') checkForUpdate();
    });
  });
})();

// Disable right-click context menu for content protection
document.addEventListener('contextmenu', (e) => {
  e.preventDefault();
  return false;
});

// Disable keyboard shortcuts for copying/saving
document.addEventListener('keydown', (e) => {
  // Disable Ctrl+C, Ctrl+U, Ctrl+S, Ctrl+P, Ctrl+Shift+I, F12
  if (
    (e.ctrlKey && (e.key === 'c' || e.key === 'u' || e.key === 's' || e.key === 'p')) ||
    (e.ctrlKey && e.shiftKey && e.key === 'I') ||
    e.key === 'F12'
  ) {
    // Allow Ctrl+C in input fields
    const target = e.target as HTMLElement;
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
      return true;
    }
    e.preventDefault();
    return false;
  }
});

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