"use client";

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

/**
 * /screen/{screenCode} → /screens/{screenId} 리다이렉트
 * 메뉴 URL이 screenCode 기반이므로, screenId로 변환 후 이동
 */
export default function ScreenCodeRedirectPage() {
  const params = useParams();
  const router = useRouter();
  const screenCode = params.screenCode as string;

  useEffect(() => {
    if (!screenCode) return;

    const numericId = parseInt(screenCode);
    if (!isNaN(numericId)) {
      router.replace(`/screens/${numericId}`);
      return;
    }

    const resolve = async () => {
      try {
        const res = await apiClient.get("/screen-management/screens", {
          params: { searchTerm: screenCode, size: 50 },
        });
        const items = res.data?.data?.data || res.data?.data || [];
        const arr = Array.isArray(items) ? items : [];
        const exact = arr.find((s: any) => s.screenCode === screenCode);
        const target = exact || arr[0];
        if (target) {
          router.replace(`/screens/${target.screenId || target.screen_id}`);
        } else {
          router.replace("/");
        }
      } catch {
        router.replace("/");
      }
    };
    resolve();
  }, [screenCode, router]);

  return (
    <div className="flex h-full items-center justify-center">
      <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" />
    </div>
  );
}
