import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";

// Signal to index.html boot loader that the entry file was loaded.
(globalThis as any).__APP_ENTRY_LOADED__ = true;

// Unregister any leftover service workers from the previous PWA setup.
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations().then((registrations) => {
    registrations.forEach((reg) => reg.unregister());
  });
}

// Boot error screen - displays if React fails to mount
function showBootError(error: unknown) {
  // Prevent the index.html timeout screen from overwriting this UI.
  (globalThis as any).__APP_MOUNTED__ = true;

  const root = document.getElementById("root");
  if (!root) return;

  const message = error instanceof Error ? error.message : String(error);
  const stack = error instanceof Error ? error.stack : "";

  root.innerHTML = `
    <div style="min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;font-family:system-ui,sans-serif;background:#fafafa;">
      <div style="max-width:500px;text-align:center;">
        <div style="width:64px;height:64px;margin:0 auto 24px;border-radius:50%;background:#fee2e2;display:flex;align-items:center;justify-content:center;">
          <svg width="32" height="32" fill="none" stroke="#dc2626" stroke-width="2" viewBox="0 0 24 24">
            <path d="M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
          </svg>
        </div>
        <h1 style="font-size:20px;font-weight:600;color:#1f2937;margin:0 0 8px;">Erreur de démarrage</h1>
        <p style="color:#6b7280;font-size:14px;margin:0 0 16px;">L'application n'a pas pu démarrer. Rechargez la page ou contactez le support.</p>
        <div style="background:#f3f4f6;border-radius:8px;padding:12px;text-align:left;margin-bottom:16px;">
          <p style="font-family:monospace;font-size:12px;color:#dc2626;word-break:break-all;margin:0;">${message}</p>
          ${stack ? `<pre style="font-family:monospace;font-size:10px;color:#6b7280;white-space:pre-wrap;word-break:break-all;margin:8px 0 0;max-height:120px;overflow:auto;">${stack}</pre>` : ""}
        </div>
        <button onclick="location.reload()" style="background:#1f2937;color:white;border:none;padding:10px 20px;border-radius:8px;font-size:14px;cursor:pointer;">
          Recharger la page
        </button>
        <button onclick="navigator.clipboard.writeText('${message.replace(/'/g, "\\'")}\\n${stack?.replace(/'/g, "\\'").replace(/\n/g, "\\n") || ""}')" style="background:transparent;border:1px solid #d1d5db;color:#374151;padding:10px 20px;border-radius:8px;font-size:14px;cursor:pointer;margin-left:8px;">
          Copier l'erreur
        </button>
      </div>
    </div>
  `;
}

// Catch global errors before React mounts
// (After mount, GlobalErrorHandler takes over. Do NOT replace the whole UI post-mount.)
const isMetaAdAccountMissing = (msg: string) =>
  msg.includes("No ad account selected") || msg.includes("ad_account_missing");

const isServiceWorkerError = (msg: string, name?: string) =>
  msg.includes("ServiceWorker") ||
  msg.includes("service worker") ||
  msg.includes("sw.js") ||
  msg.includes("behind a redirect") ||
  msg.includes("script resource") ||
  name === "SecurityError"; // Safari throws SecurityError for SW update failures

// Suppress SW update rejections in both capture and bubble phases.
// The old pimento.design/ SW tries to update but pimento.design/sw.js is behind a redirect
// (domain redirects to www.pimento.design) — a harmless browser-level error we can't clear.
// Using both capture and non-capture ensures at least one fires first regardless of browser
// AT_TARGET ordering quirks with stopImmediatePropagation().
function suppressSWRejection(event: Event) {
  const pe = event as PromiseRejectionEvent;
  const reason = pe.reason;
  const msg = reason instanceof Error ? reason.message : String(reason ?? "");
  const name = reason instanceof Error ? reason.name : undefined;
  if (isServiceWorkerError(msg, name)) {
    event.preventDefault();
    event.stopImmediatePropagation();
    event.stopPropagation();
  }
}
window.addEventListener("unhandledrejection", suppressSWRejection, { capture: true });
window.addEventListener("unhandledrejection", suppressSWRejection, { capture: false });

window.onerror = (message, _source, _lineno, _colno, error) => {
  if ((globalThis as any).__APP_MOUNTED__) return;

  const combined = `${String(message || "")} ${error instanceof Error ? error.message : ""}`;
  if (isMetaAdAccountMissing(combined)) return;
  if (isServiceWorkerError(combined, error instanceof Error ? error.name : undefined)) return;

  showBootError(error || message);
};

window.onunhandledrejection = (event) => {
  if ((globalThis as any).__APP_MOUNTED__) return;

  const reason = (event as PromiseRejectionEvent).reason;
  const msg = reason instanceof Error ? reason.message : String(reason || "");
  const name = reason instanceof Error ? reason.name : undefined;
  if (isMetaAdAccountMissing(msg)) return;
  if (isServiceWorkerError(msg, name)) return;

  showBootError(reason);
};

try {
  createRoot(document.getElementById("root")!).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
  // Prevent index.html timeout screen once React mounted successfully.
  (globalThis as any).__APP_MOUNTED__ = true;
} catch (error) {
  showBootError(error);
}

