import { StrictMode } from "react";
import { createRoot, hydrateRoot } from "react-dom/client";

import { CalculatorApp } from "@/app/components/calculator-app";
import "@/app/globals.css";
import type { Locale } from "@/app/lib/types";

const container = document.getElementById("root");

if (!container) throw new Error("Missing calculator root element.");

const locales = new Set<Locale>([
  "en",
  "de",
  "es-ES",
  "fr",
  "it",
  "ja",
  "ru",
  "zh-CN",
  "zh-TW",
]);
const pathLocale = window.location.pathname.split("/").filter(Boolean)[0];
const documentLocale = document.documentElement.lang;
const initialLocale = locales.has(pathLocale as Locale)
  ? (pathLocale as Locale)
  : locales.has(documentLocale as Locale)
    ? (documentLocale as Locale)
    : "en";
const application = (
  <StrictMode>
    <CalculatorApp
      initialLocale={initialLocale}
      publicLocaleRouting
    />
  </StrictMode>
);

if (container.hasChildNodes()) hydrateRoot(container, application);
else createRoot(container).render(application);
