"use client";

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

/**
 * /screen/COMPANY_7_167 → /screens/4153 리다이렉트
 * 메뉴 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: { screenCode },
        });
        const screens = res.data?.data || [];
        if (screens.length > 0) {
          const id = screens[0].screenId || screens[0].screen_id;
          router.replace(`/screens/${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>
  );
}
