"use client";

import { useEffect } from "react";

/**
 * Sets `lang` and `dir` on <html>.
 *
 * These belong on <html> and only the root layout may render that element, but
 * the root layout cannot see the resolved locale of a deep dynamic segment
 * without reading headers() — which opts the entire route tree out of static
 * rendering and takes ISR with it.
 *
 * So the values are written two ways, and both matter:
 *
 *  1. A blocking inline script in the server-rendered HTML, so the attributes
 *     are correct on the very first paint and an RTL page never flashes LTR.
 *  2. This effect, which keeps them correct across client-side navigations
 *     between locales, where no new document is parsed.
 *
 * A reader with JavaScript disabled gets neither, so the server default in
 * app/layout.tsx is the Arabic RTL case — the default locale, and the one that
 * looks wrong most obviously if it is missed.
 */
export default function HtmlAttributes({ lang, dir }: { lang: string; dir: "rtl" | "ltr" }) {
  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = dir;
  }, [lang, dir]);

  return (
    <script
      // Values come from our own locale table, never from user input, and are
      // JSON-encoded rather than interpolated.
      dangerouslySetInnerHTML={{
        __html:
          `document.documentElement.lang=${JSON.stringify(lang)};` +
          `document.documentElement.dir=${JSON.stringify(dir)};`,
      }}
    />
  );
}
