import type { MutableRefObject } from "react";
import { useEffect, useRef, useState } from "react";
import { supportsDialog } from "../../utils";

// Add polyfill for HTML Dialog in old browsers
export const useDialogPolyfill = () => {
  const [hasDialogSupport, setHasDialogSupport] = useState(false);
  const hasAlreadyLoaded = useRef(false);

  useEffect(() => {
    setHasDialogSupport(supportsDialog());
  }, []);

  const polyfillDialog = async (
    ref: MutableRefObject<HTMLDialogElement | null>,
  ) => {
    if (
      !hasAlreadyLoaded.current &&
      !hasDialogSupport &&
      typeof window !== "undefined" &&
      ref.current !== null
    ) {
      const { default: dialogPolyfill } = await import("dialog-polyfill");

      hasAlreadyLoaded.current = true;
      try {
        if (ref.current) {
          dialogPolyfill.registerDialog(ref.current);
        }
      } catch (error) {
        console.error("Failed to load dialog-polyfill", error);
      }
    }
  };

  return {
    polyfillDialog,
  };
};
