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

function enforceLightMode() {
  const root = document.documentElement;
  root.classList.remove("dark");
  root.setAttribute("data-theme", "light");
  root.style.colorScheme = "light";

  const observer = new MutationObserver(() => {
    if (root.classList.contains("dark")) {
      root.classList.remove("dark");
    }
    if (root.getAttribute("data-theme") === "dark") {
      root.setAttribute("data-theme", "light");
    }
    if (root.style.colorScheme !== "light") {
      root.style.colorScheme = "light";
    }
  });

  observer.observe(root, {
    attributes: true,
    attributeFilter: ["class", "data-theme", "style"],
  });
}

async function applyBrandingFavicon() {
  try {
    const res = await fetch("../api/get_branding.php", { credentials: "include" });
    const json = await res.json();
    const logoUrl = typeof json?.logo_url === "string" ? json.logo_url : null;
    const updatedAt = typeof json?.updated_at === "number" ? json.updated_at : null;
    if (!logoUrl) return;

    const href = `${logoUrl}${logoUrl.includes("?") ? "&" : "?"}v=${updatedAt ?? Date.now()}`;
    const link =
      (document.getElementById("app-favicon") as HTMLLinkElement | null) ||
      (document.querySelector('link[rel="icon"]') as HTMLLinkElement | null);
    if (link) link.href = href;
  } catch {
    // ignore
  }
}

applyBrandingFavicon();
enforceLightMode();

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

// Register PWA service worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').catch((err) => {
      console.warn('Service worker registration failed:', err);
    });
  });
}
