import { getHintUtils } from "@epic-web/client-hints";
import {
  clientHint as colorSchemeHint,
  subscribeToSchemeChange,
} from "@epic-web/client-hints/color-scheme";
import { clientHint as timeZoneHint } from "@epic-web/client-hints/time-zone";
import * as React from "react";
import { useRevalidator } from "react-router";
import { useRequestInfo } from "./request-info";

const hintsUtils = getHintUtils({
  theme: colorSchemeHint,
  timeZone: timeZoneHint,
});

export function getHints(request?: Request): {
  theme?: "light" | "dark" | null;
  timeZone?: string | null;
} {
  return hintsUtils.getHints(request);
}

export function useHints() {
  const requestInfo = useRequestInfo();
  return requestInfo?.hints;
}

export function ClientHintCheck() {
  const { revalidate } = useRevalidator();
  React.useEffect(
    () => subscribeToSchemeChange(() => revalidate()),
    [revalidate],
  );

  return (
    <script
      dangerouslySetInnerHTML={{
        __html: hintsUtils.getClientHintCheckScript(),
      }}
    />
  );
}
