import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { bootstrapTheme } from "./hooks/useTheme";
import { bootstrapUIScale } from "./hooks/useUIScale";
import { bootstrapThemeColors } from "./hooks/useThemeColors";

bootstrapTheme();
bootstrapThemeColors();
bootstrapUIScale();

// Redirecionamento de domínios não conectados → domínio oficial
const ALLOWED_HOSTS = new Set([
  "localhost",
  "127.0.0.1",
  "optimusweb.lovable.app",
  "optimuspedidos.lovable.app",
  "optimusweb.com.br",
  "www.optimusweb.com.br",
  "app.optimusweb.com.br",
]);
(() => {
  const host = window.location.hostname;
  const isAllowed =
    ALLOWED_HOSTS.has(host) ||
    host.endsWith(".lovable.app") ||
    host.endsWith(".lovableproject.com") ||
    host.endsWith(".lovable.dev");
  if (isAllowed) return;
  const target = "https://optimuspedidos.lovable.app" + window.location.pathname + window.location.search;
  document.documentElement.innerHTML = `
    <head>
      <meta charset="utf-8">
      <title>Domínio não conectado — OPTIMUS WEB</title>
      <meta name="viewport" content="width=device-width,initial-scale=1">
    </head>
    <body style="margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f1115;color:#fff;font-family:system-ui,-apple-system,sans-serif;padding:24px;">
      <div style="max-width:560px;width:100%;background:#16181f;border:1px solid #262833;border-radius:16px;padding:32px;box-shadow:0 20px 60px rgba(0,0,0,.4);">
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px;">
          <div style="width:36px;height:36px;border-radius:8px;background:#ef4444;display:flex;align-items:center;justify-content:center;font-weight:700;">!</div>
          <h1 style="font-size:20px;margin:0;font-weight:700;">Domínio não conectado</h1>
        </div>
        <p style="color:#cbd0d9;margin:0 0 16px;line-height:1.55;font-size:14px;">
          O endereço <strong style="color:#fff;">${host}</strong> ainda não está vinculado ao OPTIMUS WEB.
          Você será redirecionado automaticamente para o domínio oficial em alguns segundos.
        </p>
        <a href="${target}" style="display:block;text-align:center;background:#ef4444;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600;font-size:14px;margin-bottom:20px;">Ir agora para optimuspedidos.lovable.app</a>

        <div style="border-top:1px solid #262833;padding-top:18px;">
          <h2 style="font-size:13px;font-weight:700;margin:0 0 10px;color:#fff;text-transform:uppercase;letter-spacing:.5px;">Como conectar este domínio</h2>
          <ol style="color:#cbd0d9;font-size:13px;line-height:1.7;margin:0 0 14px;padding-left:18px;">
            <li>Abra o painel do projeto no Lovable.</li>
            <li>Vá em <strong style="color:#fff;">Project Settings → Domains</strong> e clique em <strong style="color:#fff;">Connect Domain</strong>.</li>
            <li>Cadastre <code style="background:#0f1115;padding:1px 6px;border-radius:4px;">${host}</code> (e o <code style="background:#0f1115;padding:1px 6px;border-radius:4px;">www</code>, se aplicável).</li>
            <li>No seu registrador DNS, crie um <strong style="color:#fff;">A record</strong> apontando para <code style="background:#0f1115;padding:1px 6px;border-radius:4px;">185.158.133.1</code> e o <strong style="color:#fff;">TXT</strong> <code style="background:#0f1115;padding:1px 6px;border-radius:4px;">_lovable</code> exibido no painel.</li>
            <li>Aguarde a propagação (até 72h). O SSL é provisionado automaticamente.</li>
          </ol>
          <a href="https://docs.lovable.dev/features/custom-domain" target="_blank" rel="noopener" style="display:inline-block;color:#60a5fa;font-size:13px;text-decoration:none;">Abrir documentação de domínios →</a>
        </div>
      </div>
    </body>`;
  setTimeout(() => window.location.replace(target), 6000);
  throw new Error("__OPTIMUS_DOMAIN_REDIRECT__");
})();

// Recuperação automática de chunks quebrados após novo deploy
// (evita tela em branco quando um chunk antigo é referenciado).
const RELOAD_KEY = "__optimus_chunk_reload_at";
function handleChunkError(reason: unknown) {
  const msg = (reason as any)?.message || String(reason || "");
  if (!/Loading chunk|Failed to fetch dynamically imported module|ChunkLoadError|Importing a module script failed/i.test(msg)) return;
  try {
    const last = Number(sessionStorage.getItem(RELOAD_KEY) || 0);
    if (Date.now() - last < 10_000) return; // evita loop de reload
    sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
  } catch {}
  window.location.reload();
}
window.addEventListener("error", e => handleChunkError(e.error || e.message));
window.addEventListener("unhandledrejection", e => handleChunkError(e.reason));

const rootEl = document.getElementById("root")!;
createRoot(rootEl).render(<App />);
// Remove o splash inline assim que o React tiver pintado o primeiro frame
requestAnimationFrame(() => {
  const s = document.getElementById("__boot_splash");
  if (s) s.remove();
});
