import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App.tsx";
import "./index.css";
import { registerPwa } from "./lib/pwa";
import { sendInstalledAppTelemetry } from "./lib/telemetry";

function upsertHeadLink(rel: string, href: string) {
  let link = document.head.querySelector(`link[rel="${rel}"]`) as HTMLLinkElement | null;
  if (!link) {
    link = document.createElement("link");
    link.rel = rel;
    document.head.appendChild(link);
  }
  link.href = href;
}

function upsertHeadMeta(name: string, content: string) {
  let meta = document.head.querySelector(`meta[name="${name}"]`) as HTMLMetaElement | null;
  if (!meta) {
    meta = document.createElement("meta");
    meta.name = name;
    document.head.appendChild(meta);
  }
  meta.content = content;
}

function syncVisualViewportVariables() {
  const root = document.documentElement;
  const viewport = window.visualViewport;
  const top = viewport?.offsetTop ?? 0;
  const left = viewport?.offsetLeft ?? 0;
  const width = viewport?.width ?? window.innerWidth;
  const height = viewport?.height ?? window.innerHeight;
  const bottom = Math.max(0, window.innerHeight - height - top);

  root.style.setProperty("--app-vv-top", `${top}px`);
  root.style.setProperty("--app-vv-left", `${left}px`);
  root.style.setProperty("--app-vv-width", `${width}px`);
  root.style.setProperty("--app-vv-bottom", `${bottom}px`);
}

function installViewportTracking() {
  syncVisualViewportVariables();
  const viewport = window.visualViewport;
  const handler = () => syncVisualViewportVariables();

  viewport?.addEventListener("resize", handler);
  viewport?.addEventListener("scroll", handler);
  window.addEventListener("resize", handler);
  window.addEventListener("orientationchange", handler);
}

async function applyThemeFromServer() {
  try {
    const res = await fetch("/api/settings/public", { headers: { Accept: "application/json" } });
    if (!res.ok) return;
    const json = (await res.json()) as any;
    const root = document.documentElement;
    if (typeof json?.theme_primary === "string") root.style.setProperty("--color-primary", json.theme_primary);
    if (typeof json?.theme_secondary === "string") root.style.setProperty("--color-secondary", json.theme_secondary);
    if (typeof json?.theme_text_dark === "string") root.style.setProperty("--color-text-dark", json.theme_text_dark);
    if (typeof json?.theme_text_light === "string") root.style.setProperty("--color-text-light", json.theme_text_light);
    const primary = typeof json?.theme_primary === "string" ? json.theme_primary : null;
    const brand = typeof json?.home?.brand === "string" && json.home.brand.trim() ? json.home.brand.trim() : null;
    const favicon = typeof json?.favicon_path === "string" && json.favicon_path.trim() ? json.favicon_path.trim() : "/pwa-icon-192.png";
    const heroImagePath = typeof json?.home?.hero_image_path === "string" && json.home.hero_image_path.trim() ? json.home.hero_image_path.trim() : null;
    const logoPath = typeof json?.logo_path === "string" && json.logo_path.trim() ? json.logo_path.trim() : null;
    if (brand) document.title = brand;
    if (brand) {
      upsertHeadMeta("application-name", brand);
      upsertHeadMeta("apple-mobile-web-app-title", brand);
    }
    if (logoPath) window.localStorage.setItem("app_splash_logo_path", logoPath);
    if (heroImagePath) window.localStorage.setItem("app_splash_hero_image_path", heroImagePath);
    upsertHeadLink("icon", favicon);
    upsertHeadLink("apple-touch-icon", favicon);
    if (primary) {
      document.querySelector('meta[name="theme-color"]')?.setAttribute("content", primary);
      const hex = primary.replace("#", "");
      const r = Number.parseInt(hex.slice(0, 2), 16) / 255;
      const g = Number.parseInt(hex.slice(2, 4), 16) / 255;
      const b = Number.parseInt(hex.slice(4, 6), 16) / 255;
      const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
      root.style.setProperty("--color-primary-contrast", luminance > 0.62 ? "#0f172a" : "#ffffff");
    }
  } catch {
    // ignore
  }
}

installViewportTracking();
void applyThemeFromServer();
void registerPwa();
void sendInstalledAppTelemetry();

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