"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ArrowRight, CornerDownRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Container } from "@/components/container";
import { cn } from "@/lib/utils";

// Canonical industry slugs, hardcoded so this client-bundled 404 does NOT pull
// the full industries dataset into its bundle. Keep in sync with
// content/industries.ts (canonical slugs only — no "ed-tech"/"e-commerce" aliases).
const INDUSTRY_SLUGS = ["healthcare", "automobile", "real-estate"];

// Known, real routes the matcher can suggest (labels for display).
const titleCase = (s: string) =>
  s.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());

const KNOWN_ROUTES: { href: string; label: string }[] = [
  { href: "/", label: "Home" },
  { href: "/about", label: "About" },
  { href: "/industries", label: "Industries" },
  ...INDUSTRY_SLUGS.map((s) => ({ href: `/industries/${s}`, label: `Industries · ${titleCase(s)}` })),
  { href: "/blog", label: "Blog" },
  { href: "/contact", label: "Contact" },
  { href: "/author", label: "Authors" },
  { href: "/privacy", label: "Privacy" },
  { href: "/terms", label: "Terms" },
  { href: "/disclaimer", label: "Disclaimer" },
  { href: "/sitemap", label: "Sitemap" },
];

const FALLBACK_LINKS = [
  { label: "Home", href: "/" },
  { label: "Solutions", href: "/#solutions" },
  { label: "Industries", href: "/industries" },
  { label: "Blog", href: "/blog" },
  { label: "Contact", href: "/contact" },
];

const norm = (p: string) => p.toLowerCase().replace(/\/+$/, "").replace(/^\/+/, "");

// Levenshtein edit distance.
function lev(a: string, b: string): number {
  const m = a.length;
  const n = b.length;
  if (!m) return n;
  if (!n) return m;
  const dp = Array.from({ length: m + 1 }, (_, i) => i);
  for (let j = 1; j <= n; j++) {
    let prev = dp[0];
    dp[0] = j;
    for (let i = 1; i <= m; i++) {
      const tmp = dp[i];
      dp[i] = Math.min(dp[i] + 1, dp[i - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
      prev = tmp;
    }
  }
  return dp[m];
}

// Lower is a better match. Compares whole path + last segment, with a small
// bonus for sharing the first segment / same depth.
function scoreRoute(attempted: string, route: string): number {
  const p = norm(attempted);
  const r = norm(route);
  if (!r) return p ? 0.9 : 0; // home
  const pSeg = p.split("/").filter(Boolean);
  const rSeg = r.split("/").filter(Boolean);
  const full = lev(p, r) / Math.max(p.length, r.length, 1);
  const pLast = pSeg[pSeg.length - 1] ?? "";
  const rLast = rSeg[rSeg.length - 1] ?? "";
  const last = lev(pLast, rLast) / Math.max(pLast.length, rLast.length, 1);
  const parentBonus = pSeg[0] && pSeg[0] === rSeg[0] ? -0.18 : 0;
  const depthBonus = pSeg.length === rSeg.length ? -0.06 : 0;
  return Math.min(full, last) + parentBonus + depthBonus;
}

export function NotFoundContent() {
  const pathname = usePathname() || "";
  const [shown, setShown] = useState(false);

  useEffect(() => {
    // Not rAF (throttled in background tabs) — an effect fires regardless of
    // focus, so content is always revealed.
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: SSR-safe reveal on mount (effect fires even in background tabs)
    setShown(true);
  }, []);

  const { best, related } = useMemo(() => {
    const ranked = KNOWN_ROUTES.map((route) => ({ ...route, score: scoreRoute(pathname, route.href) })).sort(
      (a, b) => a.score - b.score,
    );
    const top = ranked[0];
    // Confident suggestion only when the attempted path is a near-miss.
    const confident = top && top.score <= 0.55 && norm(pathname).length > 0;
    return {
      best: confident ? top : null,
      related: ranked.filter((r) => r.href !== top?.href && r.score <= 0.8).slice(0, 3),
    };
  }, [pathname]);

  const reveal = () =>
    cn("transition-all duration-500 ease-out", shown ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3");
  const delayStyle = (delay: number) => ({ transitionDelay: shown ? `${delay}ms` : "0ms" });

  return (
    <Container className="flex max-w-xl flex-col items-center py-20 text-center md:py-28">
      {/* Animated signal glyph: 4 — [Q signal] — 4 */}
      <div className={reveal()} style={delayStyle(0)} aria-hidden>
        <div className="flex select-none items-center justify-center gap-3 sm:gap-5">
          <span className="font-display text-[4.5rem] font-semibold leading-none text-foreground sm:text-[6rem]">4</span>
          <span className="relative flex size-[4.5rem] items-center justify-center sm:size-24">
            {[0, 1, 2].map((i) => (
              <span
                key={i}
                className="absolute inset-0 rounded-full border border-foreground/30 motion-safe:animate-ping"
                style={{ animationDuration: "2.6s", animationDelay: `${i * 0.85}s`, opacity: 0.2 }}
              />
            ))}
            <span className="absolute inset-[16%] rounded-full border-2 border-foreground" />
            <span className="relative font-display text-2xl font-bold text-foreground sm:text-3xl">Q</span>
          </span>
          <span className="font-display text-[4.5rem] font-semibold leading-none text-foreground sm:text-[6rem]">4</span>
        </div>
      </div>

      <h1
        className={cn("mt-8 font-display text-3xl font-medium tracking-tight text-foreground", reveal())}
        style={delayStyle(120)}
      >
        This route has no agent
      </h1>
      <p
        className={cn("mt-3 text-pretty text-muted-foreground", reveal())}
        style={delayStyle(200)}
      >
        {best
          ? "That page went off-script — but this one looks close to where you were headed."
          : "The page you're after went off-script. Let's get you back on a path that answers."}
      </p>

      {/* Smart closest-route suggestion */}
      {best && (
        <div className={cn("mt-8 w-full", reveal())} style={delayStyle(280)}>
          <Link
            href={best.href}
            className="group flex items-center justify-between gap-3 rounded-2xl border border-border bg-muted/60 px-5 py-4 text-left transition-colors hover:border-foreground/30 hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          >
            <span className="flex min-w-0 items-center gap-3">
              <CornerDownRight className="size-4 shrink-0 text-foreground" />
              <span className="min-w-0">
                <span className="block text-[11px] font-bold uppercase tracking-wider text-muted-foreground">
                  Did you mean
                </span>
                <span className="block truncate font-mono text-sm font-semibold text-foreground">{best.href}</span>
              </span>
            </span>
            <ArrowRight className="size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
          </Link>

          {related.length > 0 && (
            <div className="mt-3 flex flex-wrap items-center justify-center gap-2">
              <span className="text-xs text-muted-foreground">Related:</span>
              {related.map((r) => (
                <Link
                  key={r.href}
                  href={r.href}
                  className="rounded-full border border-border bg-card px-3 py-1 font-mono text-xs text-foreground transition-colors hover:border-foreground/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                >
                  {r.href}
                </Link>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Standard quick links (fallback / always available) */}
      {!best && (
        <div className={cn("mt-8 flex flex-wrap justify-center gap-2", reveal())} style={delayStyle(280)}>
          {FALLBACK_LINKS.map((l) => (
            <Button key={l.href} asChild variant="outline" size="pill-sm">
              <Link href={l.href}>{l.label}</Link>
            </Button>
          ))}
        </div>
      )}

      <div className={cn("mt-5", reveal())} style={delayStyle(360)}>
        <Button asChild variant="brand" size="pill">
          <Link href="/" className="gap-2">
            Back to home
            <ArrowRight className="size-4" />
          </Link>
        </Button>
      </div>
    </Container>
  );
}
