"use client";

import { useEffect, useRef } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { useTranslation } from "@enode/core/translations/hooks";
import { SHELL_MAIN_ID } from "../shell-cover";
import { findLabelElement } from "./find-target";
import { entryForFind, FIND_PARAM, toMessage } from "./settings-index";
import { SETTINGS_INDEX } from "./settings-index.generated";

function prefersReducedMotion(): boolean {
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

/** How long a page may take to show the setting (data loading in). */
const FIND_TIMEOUT_MS = 6000;

/**
 * Scrolls to the setting a global-search result pointed at (`?find=<key>`):
 * waits for its row to appear on the page and scrolls it to the centre, then
 * drops `find` from the address so Back and reload don't scroll again. A
 * setting that never appears (a hidden or since-removed one) leaves the page
 * as it is. Mounted once, in the app shell.
 */
export function FindTargetScroller() {
  const { t } = useTranslation();
  const params = useSearchParams();
  const pathname = usePathname();
  const key = params.get(FIND_PARAM);
  const stopRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    if (!key) return;
    // A new request replaces a running one.
    stopRef.current?.();
    const url = new URL(window.location.href);
    url.searchParams.delete(FIND_PARAM);
    window.history.replaceState(window.history.state, "", url.toString());

    const entry = entryForFind(SETTINGS_INDEX, key, pathname);
    if (!entry) return;
    // The index holds strings already extracted from the settings pages' own
    // t("…") calls; translating one from data is not a new string.
    const translateIndexed = t;
    const label = translateIndexed(toMessage(entry.message));
    const root = document.getElementById(SHELL_MAIN_ID) ?? document.body;
    const tryFind = (): boolean => {
      // The row's anchor when it has one, else the label.
      const element =
        (entry.anchor
          ? root.querySelector<HTMLElement>(`[data-find="${CSS.escape(entry.anchor)}"]`)
          : null) ?? findLabelElement(root, label);
      if (!element) return false;
      element.scrollIntoView({ block: "center", behavior: prefersReducedMotion() ? "auto" : "smooth" });
      return true;
    };
    const observer = new MutationObserver(() => {
      if (tryFind()) stop();
    });
    const timeout = window.setTimeout(() => stop(), FIND_TIMEOUT_MS);
    function stop() {
      observer.disconnect();
      window.clearTimeout(timeout);
    }
    if (tryFind()) stop();
    else observer.observe(root, { subtree: true, childList: true, characterData: true });
    stopRef.current = stop;
  }, [key, pathname, t]);

  useEffect(() => () => stopRef.current?.(), []);
  return null;
}
