'use client';

import { useCallback, useEffect, useState } from 'react';
import type { HostDetail } from '@pac/types';
import { ApiError } from '@/lib/api-client';
import { hostApi } from './host-api';

export type LoadState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; data: HostDetail }
  | { status: 'error'; message: string; code?: number };

export function useHostAdmin() {
  const [state, setState] = useState<LoadState>({ status: 'idle' });

  const fetch = useCallback(async () => {
    // 已有数据时**不切 loading**:否则父组件会把整页换成"加载中"占位、卸载 HostAdminApp,
    // 连带把"仅显示一次"的明文 secret 弹窗刷掉。刷新走 stale-while-revalidate,旧数据留屏。
    setState((prev) => (prev.status === 'ready' ? prev : { status: 'loading' }));
    try {
      const data = await hostApi.getSelf();
      setState({ status: 'ready', data });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      const code = err instanceof ApiError ? err.code : undefined;
      // 刷新失败若已有数据 → 保留旧数据不白屏;仅首屏(无数据)才进错误态。
      setState((prev) => (prev.status === 'ready' ? prev : { status: 'error', message, code }));
    }
  }, []);

  useEffect(() => {
    void fetch();
  }, [fetch]);

  return { state, refresh: fetch };
}
