"use client";

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { getAdminPlayTypes } from "@/api/admin-config";
import {
  getAdminPlayTypesLoadPromise,
  getCachedAdminPlayTypes,
  resolveAdminPlayTypeDisplayName,
} from "@/lib/admin-play-types";

export type PlayTypeOption = { code: string; label: string };

/**
 * 从全局玩法缓存生成下拉选项；仅首次 miss 时请求 API，语言切换只重算 label。
 */
export function useCachedPlayTypeOptions(): PlayTypeOption[] {
  const { i18n } = useTranslation();
  const [options, setOptions] = useState<PlayTypeOption[]>([]);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      await getAdminPlayTypesLoadPromise(getAdminPlayTypes);
      if (cancelled) {
        return;
      }
      setOptions(
        getCachedAdminPlayTypes().map((item) => ({
          code: item.play_code,
          label:
            resolveAdminPlayTypeDisplayName(item.play_code, i18n.language, item) || item.play_code,
        })),
      );
    })();
    return () => {
      cancelled = true;
    };
  }, [i18n.language]);

  return options;
}
