"use client";

import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import type Lenis from "lenis";

let registered = false;
export function ensureGsap() {
  if (!registered && typeof window !== "undefined") {
    gsap.registerPlugin(ScrollTrigger);
    registered = true;
  }
  return { gsap, ScrollTrigger };
}

/** Shared Lenis instance (null when smooth scrolling is disabled, e.g. reduced motion). */
let lenisInstance: Lenis | null = null;
export const setLenis = (l: Lenis | null) => {
  lenisInstance = l;
  // QA hook: only with ?motion=force, so automated checks can scroll precisely.
  if (document.documentElement.hasAttribute("data-force-motion")) (window as unknown as { __lenis?: Lenis | null }).__lenis = l;
};
export const getLenis = () => lenisInstance;

export const prefersReducedMotion = () =>
  typeof window !== "undefined" &&
  !document.documentElement.hasAttribute("data-force-motion") &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

/** Motion is "on" when the inline boot script enabled it (see layout). */
export const motionEnabled = () =>
  typeof document !== "undefined" && document.documentElement.classList.contains("js-motion");

/** Smoothly scroll to an element id (falls back to native scrolling). */
export function scrollToId(id: string) {
  const el = document.getElementById(id);
  if (!el) return;
  const lenis = getLenis();
  if (lenis) lenis.scrollTo(el, { offset: 0, duration: 1.6 });
  else el.scrollIntoView({ behavior: prefersReducedMotion() ? "auto" : "smooth", block: "start" });
  // Move focus for keyboard / screen-reader users without a second jump.
  if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "-1");
  el.focus({ preventScroll: true });
}
