"use client";

import { useEffect, useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";

function isDownloadOrExternal(anchor: HTMLAnchorElement) {
  if (anchor.hasAttribute("download") || anchor.target === "_blank") return true;
  const url = new URL(anchor.href, window.location.href);
  return url.origin !== window.location.origin || url.pathname.startsWith("/api/") || url.hash !== "";
}

export default function NavigationProgress() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const routeKey = `${pathname}?${searchParams.toString()}`;
  const [pendingTarget, setPendingTarget] = useState<string | null>(null);
  const pending = pendingTarget !== null && pendingTarget !== routeKey;

  useEffect(() => {
    let timeout: number | undefined;
    const begin = (target: string) => {
      setPendingTarget(target);
      if (timeout) window.clearTimeout(timeout);
      timeout = window.setTimeout(() => setPendingTarget(null), 30_000);
    };

    const onClick = (event: MouseEvent) => {
      if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
      const target = event.target;
      if (!(target instanceof Element)) return;
      const anchor = target.closest("a[href]");
      if (!(anchor instanceof HTMLAnchorElement) || isDownloadOrExternal(anchor)) return;
      const url = new URL(anchor.href, window.location.href);
      const targetRoute = `${url.pathname}?${url.searchParams.toString()}`;
      if (targetRoute === routeKey) return;
      begin(targetRoute);
    };

    const onSubmit = (event: SubmitEvent) => {
      const form = event.target;
      if (!(form instanceof HTMLFormElement) || form.target === "_blank") return;
      const action = new URL(form.action || window.location.href, window.location.href);
      begin(`${action.pathname}?${action.searchParams.toString()}`);
    };

    document.addEventListener("click", onClick, true);
    document.addEventListener("submit", onSubmit, true);
    return () => {
      document.removeEventListener("click", onClick, true);
      document.removeEventListener("submit", onSubmit, true);
      if (timeout) window.clearTimeout(timeout);
    };
  }, [routeKey]);

  if (!pending) return null;
  return (
    <div aria-label="Memuat halaman" aria-live="polite" className="fixed inset-x-0 top-0 z-[200] h-1 overflow-hidden bg-emerald-100/80 dark:bg-emerald-950/80" role="status">
      <span className="block h-full w-1/3 animate-[sfs-navigation-progress_1.2s_ease-in-out_infinite] bg-emerald-600 dark:bg-emerald-400" />
      <style>{"@keyframes sfs-navigation-progress{0%{transform:translateX(-110%)}100%{transform:translateX(310%)}}"}</style>
    </div>
  );
}
