"use client";

import { useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { archiveApi } from "@/lib/api/client";
import type { ArchiveIssue } from "@/types";

/**
 * Legacy-issue resolver: 301s from old phocadownload category URLs land here
 * with the Joomla category id; we look up the imported issue and forward.
 * The legacy top menu's broken "Vol.8, Issue 1" link used id=0 — mapped to
 * its real category (50) rather than reproducing the dead end.
 */
const LEGACY_CATEGORY_FIXES: Record<string, number> = { "0": 50 };

export default function LegacyIssueResolver() {
  const { catId } = useParams<{ catId: string }>();
  const router = useRouter();

  useEffect(() => {
    if (!catId) return;
    const wanted = LEGACY_CATEGORY_FIXES[catId] ?? parseInt(catId, 10);
    let cancelled = false;
    (async () => {
      try {
        const issues = (await archiveApi.issues()).data as ArchiveIssue[];
        const hit = issues.find((i) => i.legacyCategoryId === wanted);
        if (!cancelled) {
          router.replace(hit ? `/journal/archive/${hit.id}` : "/journal/archive");
        }
      } catch {
        if (!cancelled) router.replace("/journal/archive");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [catId, router]);

  return (
    <div className="flex min-h-[50vh] items-center justify-center">
      <Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
    </div>
  );
}
