"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { Truck } from "lucide-react";
import { cn } from "@/lib/cn";
import { useT } from "@/i18n";

type Phase = "idle" | "entering" | "leaving";

const HOLD_MS = 340;
const EXIT_MS = 300;

function isReducedMotion(): boolean {
  return (
    typeof window !== "undefined" &&
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
  );
}

/**
 * Smooth branded transition between routes. On every soft navigation a quick,
 * GPU-friendly overlay (brand mark inside a spinning ring + shimmer bar) sweeps
 * in, holds a beat, then fades out to reveal the new page. Skipped entirely
 * when the OS asks for reduced motion, and never blocks interaction.
 */
export function PageTransitionLoader() {
  const t = useT();
  const pathname = usePathname();

  // Detect soft navigations by storing the last-seen pathname and syncing state
  // during render (the documented "previous props" pattern), so effects only
  // schedule async timeouts (no cascading setState-in-effect).
  const [seenPath, setSeenPath] = useState(pathname);
  const [phase, setPhase] = useState<Phase>("idle");

  if (seenPath !== pathname) {
    setSeenPath(pathname);
    if (!isReducedMotion()) setPhase("entering");
  }

  // Drive each phase with a single self-contained timeout; cleanup on next
  // navigation or unmount (no cross-phase timer clearing that could strand it).
  useEffect(() => {
    if (phase === "entering") {
      const hold = window.setTimeout(() => setPhase("leaving"), HOLD_MS);
      return () => window.clearTimeout(hold);
    }
    if (phase === "leaving") {
      const done = window.setTimeout(() => setPhase("idle"), EXIT_MS);
      return () => window.clearTimeout(done);
    }
  }, [phase]);

  if (phase === "idle") return null;

  return (
    <div
      role="status"
      aria-live="polite"
      data-loader="brand"
      data-phase={phase}
      className={cn(
        "pointer-events-none fixed inset-0 z-[80] flex items-center justify-center overflow-hidden",
        phase === "entering"
          ? "animate-[kap-loader-in_0.34s_ease-out_forwards]"
          : "animate-[kap-loader-out_0.3s_ease-in_forwards]",
      )}
    >
      {/* Frosted backdrop + ambient brand glow */}
      <div className="absolute inset-0 bg-background/70 backdrop-blur-md" aria-hidden />
      <div
        className="absolute h-96 w-96 rounded-full bg-primary/15 blur-[90px]"
        aria-hidden
      />

      <div className="relative flex flex-col items-center gap-5">
        {/* Spinning ring with the brand mark in the middle */}
        <div className="relative h-24 w-24">
          <span
            aria-hidden
            className="absolute -inset-4 rounded-full border border-primary/20"
            style={{ animation: "kap-loader-ring-drift 3.2s linear infinite" }}
          />
          <span
            aria-hidden
            className="absolute -inset-2 rounded-full border border-dashed border-primary/25"
            style={{ animation: "kap-loader-ring-spin 9s linear infinite" }}
          />
          <span
            aria-hidden
            className="absolute inset-0 rounded-full"
            style={{
              padding: 3,
              animation: "kap-loader-ring-spin 1.1s linear infinite",
              background:
                "conic-gradient(from 120deg, transparent 0deg, transparent 190deg, var(--ring) 300deg, transparent 360deg)",
            }}
          >
            <span className="flex h-full w-full items-center justify-center rounded-full bg-background">
              <span
                className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-primary-hover text-primary-foreground shadow-lg"
                style={{ animation: "kap-loader-logo-breathe 2.1s ease-in-out infinite" }}
              >
                <Truck className="h-6 w-6" strokeWidth={2.2} aria-hidden />
              </span>
            </span>
          </span>
        </div>

        {/* Shimmer progress line */}
        <div className="h-1 w-44 overflow-hidden rounded-full bg-muted" role="presentation">
          <div
            className="h-full w-full rounded-full bg-gradient-to-r from-transparent via-primary to-transparent"
            style={{ animation: "kap-loader-shimmer 1.1s ease-in-out infinite" }}
          />
        </div>

        <p className="text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground">
          {t("common.appName")}
        </p>

        <span className="sr-only">{t("common.loading")}</span>
      </div>
    </div>
  );
}