import { RemixBrowser } from "@remix-run/react";
import posthog from "posthog-js";
import { StrictMode, startTransition, useEffect } from "react";
import { hydrateRoot } from "react-dom/client";
import { Routes } from "./routes";

function PosthogInit() {
  useEffect(() => {
    if (process.env.NODE_ENV !== "development") {
      posthog.init("phc_iZ0VLonpOMLBi7z9cljlvKHXODB1udna8oQbtFDlBbQ", {
        api_host: "https://app.posthog.com",
      });
    }
  }, []);

  return null;
}

function CookieTZInit() {
  useEffect(() => {
    const setTimeZoneCookie = async () => {
      // Check if the timezone cookie is already set
      const timezoneCookie = document.cookie.split("; ").find((row) => row.startsWith("timezone="));

      // If the cookie isn't set, determine the timezone and send it to the server
      if (!timezoneCookie) {
        const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

        try {
          await fetch(Routes.actions.setTZ, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ timezone }),
          });
        } catch (error) {
          console.error("Error setting timezone", error);
        }
      }
    };

    void setTimeZoneCookie();
  }, []);

  return null;
}

startTransition(() => {
  hydrateRoot(
    document,
    <StrictMode>
      <RemixBrowser />
      <PosthogInit />
      <CookieTZInit />
    </StrictMode>,
  );
});
