import { Fragment, type ReactNode, useEffect, useState } from "react";

type LocaleRefreshBoundaryProps = {
  children: ReactNode;
};

function LocaleRefreshBoundary({ children }: LocaleRefreshBoundaryProps) {
  const [localeVersion, setLocaleVersion] = useState(0);

  useEffect(() => {
    const syncLocale = () => {
      setLocaleVersion((current) => current + 1);
    };

    window.addEventListener("localechange", syncLocale);
    window.addEventListener("storage", syncLocale);

    return () => {
      window.removeEventListener("localechange", syncLocale);
      window.removeEventListener("storage", syncLocale);
    };
  }, []);

  return <Fragment key={localeVersion}>{children}</Fragment>;
}

export default LocaleRefreshBoundary;
