"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { cn } from "@/lib/utils";
import { ZelligeMark } from "@/components/ui/zellige-mark";

const FORM_FEEDBACK_MS = 1800;
const NAVIGATION_FALLBACK_MS = 12000;
const OVERLAY_DELAY_MS = 280;

export function RouteLoader() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [active, setActive] = useState(false);
  const [overlayVisible, setOverlayVisible] = useState(false);
  const [progress, setProgress] = useState(0);
  const activeRef = useRef(false);
  const timeouts = useRef<ReturnType<typeof setTimeout>[]>([]);
  const progressInterval = useRef<ReturnType<typeof setInterval> | null>(null);

  const clearTimers = useCallback(() => {
    timeouts.current.forEach((timer) => clearTimeout(timer));
    timeouts.current = [];
    if (progressInterval.current) {
      clearInterval(progressInterval.current);
      progressInterval.current = null;
    }
  }, []);

  const finish = useCallback(() => {
    if (!activeRef.current) return;
    activeRef.current = false;
    clearTimers();
    setProgress(100);
    const hideTimer = setTimeout(() => {
      setActive(false);
      setOverlayVisible(false);
      setProgress(0);
    }, 340);
    timeouts.current.push(hideTimer);
  }, [clearTimers]);

  const start = useCallback(
    (mode: "navigation" | "form") => {
      if (activeRef.current) return;
      clearTimers();
      activeRef.current = true;
      setActive(true);
      setOverlayVisible(false);
      setProgress(12);

      let currentProgress = 12;
      progressInterval.current = setInterval(() => {
        currentProgress = Math.min(88, currentProgress + Math.max(1, (90 - currentProgress) * 0.12));
        setProgress(currentProgress);
      }, 180);

      if (mode === "navigation") {
        const overlayTimer = setTimeout(() => setOverlayVisible(true), OVERLAY_DELAY_MS);
        timeouts.current.push(overlayTimer);
      }

      const fallbackTimer = setTimeout(
        finish,
        mode === "navigation" ? NAVIGATION_FALLBACK_MS : FORM_FEEDBACK_MS,
      );
      timeouts.current.push(fallbackTimer);
    },
    [clearTimers, finish],
  );

  const search = searchParams.toString();

  useEffect(() => {
    if (activeRef.current) finish();
  }, [pathname, search, finish]);

  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      if (
        event.defaultPrevented ||
        event.button !== 0 ||
        event.metaKey ||
        event.ctrlKey ||
        event.shiftKey ||
        event.altKey
      ) {
        return;
      }

      const element = event.target instanceof Element ? event.target.closest("a[href]") : null;
      if (!(element instanceof HTMLAnchorElement)) return;
      if (element.target && element.target !== "_self") return;
      if (element.hasAttribute("download") || element.hasAttribute("data-no-loader")) return;
      if (element.getAttribute("aria-disabled") === "true") return;

      const href = element.getAttribute("href");
      if (!href || href.startsWith("#")) return;

      let url: URL;
      try {
        url = new URL(element.href, window.location.href);
      } catch {
        return;
      }

      if (url.origin !== window.location.origin) return;
      if (url.pathname === window.location.pathname && url.search === window.location.search) return;

      start("navigation");
    };

    const handleSubmit = (event: SubmitEvent) => {
      const form = event.target;
      if (!(form instanceof HTMLFormElement)) return;
      if (form.target && form.target !== "_self") return;
      if (form.method.toLowerCase() === "dialog") return;
      if (form.hasAttribute("data-no-loader")) return;
      start("form");
    };

    document.addEventListener("click", handleClick, true);
    document.addEventListener("submit", handleSubmit, true);

    return () => {
      document.removeEventListener("click", handleClick, true);
      document.removeEventListener("submit", handleSubmit, true);
    };
  }, [start]);

  useEffect(() => clearTimers, [clearTimers]);

  const localeSegment = pathname?.split("/")[1] ?? "";
  const isArabic = localeSegment === "ar";
  const loadingLabel =
    localeSegment === "en" ? "Loading" : localeSegment === "ar" ? "جارٍ التحميل" : "Chargement";

  return (
    <>
      <div
        data-route-loader
        aria-hidden="true"
        dir={isArabic ? "rtl" : "ltr"}
        className={cn(
          "pointer-events-none fixed inset-x-0 top-0 z-[300] h-[2px] transition-opacity duration-300",
          active ? "opacity-100" : "opacity-0",
        )}
      >
        <div className="h-full bg-charcoal/[0.06]">
          <div
            className={cn(
              "relative me-auto h-full shadow-[0_0_14px_rgba(185,154,100,0.5)] transition-[width] duration-300 ease-out",
              isArabic
                ? "bg-gradient-to-l from-gold via-[#d7b87e] to-terracotta"
                : "bg-gradient-to-r from-gold via-[#d7b87e] to-terracotta",
            )}
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>

      <div
        data-route-loader-veil
        aria-hidden={!overlayVisible}
        aria-live="polite"
        role="status"
        className={cn(
          "pointer-events-none fixed inset-0 z-[290] flex items-center justify-center overflow-hidden bg-ivory/[0.97] backdrop-blur-[6px] transition-opacity duration-300",
          overlayVisible ? "opacity-100" : "opacity-0",
        )}
      >
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(185,154,100,0.1),transparent_58%)]"
        />
        <div
          aria-hidden="true"
          className="pointer-events-none absolute left-1/2 top-1/2 h-[min(76vw,31rem)] w-[min(76vw,31rem)] -translate-x-1/2 -translate-y-1/2 rotate-45 border border-gold/15"
        />
        <div
          aria-hidden="true"
          className="pointer-events-none absolute left-1/2 top-1/2 h-[min(56vw,23rem)] w-[min(56vw,23rem)] -translate-x-1/2 -translate-y-1/2 border border-gold/10"
        />

        <div
          className={cn(
            "relative flex flex-col items-center px-6 text-center transition-all duration-500",
            overlayVisible ? "translate-y-0 opacity-100" : "translate-y-2 opacity-0",
          )}
        >
          <ZelligeMark animated className="h-20 w-20 text-gold md:h-24 md:w-24" />
          <p
            dir="ltr"
            className="mt-7 text-[24px] tracking-[0.34em] text-charcoal md:text-[29px]"
            style={{ fontFamily: "var(--font-cormorant), Georgia, serif" }}
          >
            DAR ZELLIGE
          </p>
          <div className="mt-5 flex items-center gap-3">
            <span className="h-px w-8 bg-gold/50" />
            <span
              dir={isArabic ? "rtl" : undefined}
              className={cn(
                "text-charcoal/40",
                isArabic
                  ? "font-arabic text-[13px] tracking-normal"
                  : "text-[12px] uppercase tracking-[0.28em]",
              )}
            >
              {loadingLabel}
            </span>
            <span className="h-px w-8 bg-gold/50" />
          </div>
          <div className="mt-6 h-px w-28 overflow-hidden bg-charcoal/10">
            <span className="loader-sweep block h-full w-1/3 bg-gold" />
          </div>
        </div>
      </div>
    </>
  );
}
