"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { smoothScrollTo } from "@/lib/scroll";

/**
 * Handles smooth anchor-scroll navigation across desktop and mobile,
 * dynamically offsetting the rendered sticky/fixed header and supporting
 * both in-page clicks and direct URL hash landings.
 */
export function SmoothAnchorHandler() {
  const pathname = usePathname();

  useEffect(() => {
    // Intercept in-page anchor clicks
    const handleClick = (e: MouseEvent) => {
      // Don't intercept if modifier keys were pressed (Cmd/Ctrl click)
      if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
        return;
      }

      const target = (e.target as HTMLElement)?.closest<HTMLAnchorElement>("a[href*='#']");
      if (!target) return;

      const href = target.getAttribute("href");
      if (!href) return;

      let hash = "";
      if (href.startsWith("#")) {
        hash = href.slice(1);
      } else if (href.startsWith("/#") && pathname === "/") {
        hash = href.slice(2);
      }

      if (hash) {
        let el =
          document.getElementById(hash) ||
          document.querySelector<HTMLElement>(`[data-section="${hash}"], a[name="${hash}"]`);
        if (!el && (hash === "what-we-build" || hash === "solutions")) {
          el = document.getElementById("what-we-build") || document.getElementById("solutions");
        }
        if (el) {
          e.preventDefault();
          smoothScrollTo(el);
          window.history.pushState(null, "", `#${hash}`);
        }
      }
    };

    document.addEventListener("click", handleClick);

    // Initial page load hash check (e.g. user opens https://qutoai.com/#what-we-build)
    if (window.location.hash) {
      const hash = window.location.hash.slice(1);
      // Brief timeout to ensure layout/fonts have stabilized
      const timer = window.setTimeout(() => {
        const el =
          document.getElementById(hash) ||
          document.querySelector<HTMLElement>(`[data-section="${hash}"], a[name="${hash}"]`);
        if (el) {
          smoothScrollTo(el);
        }
      }, 150);
      return () => {
        document.removeEventListener("click", handleClick);
        window.clearTimeout(timer);
      };
    }

    return () => {
      document.removeEventListener("click", handleClick);
    };
  }, [pathname]);

  return null;
}
