"use client";

import { useEffect, useState } from "react";
import { AlertTriangle } from "lucide-react";
import { checkForUpdate, checkBuildIntegrity } from "@/lib/update";
import { withBuildId } from "@/lib/update";
import { normalizePath, retiredTarget } from "@/lib/update/retired-routes";

// One rescue attempt per path per tab.
const GUARD_KEY = "not-found-rescue";

type State = "checking" | "lost";

export default function Custom404() {
  const [state, setState] = useState<State>("checking");

  useEffect(() => {
    let cancelled = false;
    const done = () => { if (!cancelled) setState("lost"); };

    const path = normalizePath(window.location.pathname);

    let tried = false;
    try { tried = sessionStorage.getItem(GUARD_KEY) === path; } catch { }
    if (tried) { done(); return; }
    try { sessionStorage.setItem(GUARD_KEY, path); } catch { }

    // 1.
    const moved = retiredTarget(path);
    if (moved) {
      window.location.replace(withBuildId(moved + window.location.search));
      return;
    }

    // 2/3.
    (async () => {
      try {
        if (await checkForUpdate()) return;
        // Deferred so this route's chunks have finished loading before checkBuildIntegrity() looks at what was actually fetched.
        await new Promise((r) => setTimeout(r, 1200));
        if (cancelled) return;
        if (await checkBuildIntegrity()) return;
      } catch { }
      done();
    })();

    return () => { cancelled = true; };
  }, []);

  // data-page marks this page for debugging in DevTools.
  return (
    <div
      data-page="not-found"
      className="w-full h-screen bg-background flex items-center justify-center px-4 relative overflow-hidden"
    >

      <div className="absolute w-[500px] h-[500px] bg-primary/10 blur-[120px] rounded-full top-[-180px] left-[-180px] animate-pulse" />
      <div className="absolute w-[450px] h-[450px] bg-blue-500/10 blur-[120px] rounded-full bottom-[-180px] right-[-180px] animate-pulse" />

      {state === "checking" ? (
        <div className="flex flex-col items-center text-center z-10">
          <div className="w-12 h-12 rounded-full border-4 border-primary/20 border-t-primary animate-spin" />
          <p className="mt-5 text-sm text-muted-foreground">
            در حال بررسی نسخه برنامه...
          </p>
        </div>
      ) : (
        <div className="flex flex-col items-center text-center z-10">

          <div className="mb-6 w-24 h-24 rounded-3xl bg-primary/10 border border-primary/20 flex items-center justify-center animate-bounce">
            <AlertTriangle className="w-12 h-12 text-primary" />
          </div>

          <h1 className="mt-3 text-[110px] md:text-[160px] font-extrabold text-foreground leading-none tracking-tight animate-fadeIn">
            404
          </h1>

          <p className="my-1 text-xl md:text-3xl text-foreground/80 font-bold animate-fadeIn delay-100">
            صفحه مورد نظر یافت نشد!
          </p>

          <p className="my-1 text-sm text-muted-foreground max-w-md animate-fadeIn delay-200">
            ممکن است صفحه حذف شده باشد یا آدرس اشتباه وارد شده باشد
          </p>

          {/* A real <a>, not next/link, and deliberately so. */}
          {/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
          <a
            href="/"
            className="mt-4 px-6 py-3 rounded-xl bg-primary text-primary-foreground font-medium hover:scale-105 active:scale-95 transition"
          >
            بازگشت به خانه
          </a>

        </div>
      )}

      <style jsx>{`
        .animate-fadeIn {
          animation: fadeIn 0.6s ease both;
        }

        .delay-100 {
          animation-delay: 0.1s;
        }

        .delay-200 {
          animation-delay: 0.2s;
        }

        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </div>
  );
}
