/** 赛事列表 UI 状态（返回列表时恢复展开等） */

const STORAGE_KEY = 'admin_matches_list_ui';
export const MAX_EXPANDED_LEAGUES = 3;

export type MatchesListUiState = {
  expandedLeagueIds: string[];
  page: number;
  pageSize: number;
  filterStatus: string;
  keyword: string;
};

function defaultState(): MatchesListUiState {
  return {
    expandedLeagueIds: [],
    page: 1,
    pageSize: 10,
    filterStatus: '',
    keyword: '',
  };
}

function capExpanded(ids: string[]): string[] {
  return ids.slice(0, MAX_EXPANDED_LEAGUES);
}

export function readMatchesListUiState(): MatchesListUiState | null {
  try {
    const raw = sessionStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as MatchesListUiState;
    if (!Array.isArray(parsed.expandedLeagueIds)) return null;
    return {
      ...parsed,
      expandedLeagueIds: capExpanded(parsed.expandedLeagueIds),
    };
  } catch {
    return null;
  }
}

export function writeMatchesListUiState(state: MatchesListUiState) {
  sessionStorage.setItem(
    STORAGE_KEY,
    JSON.stringify({
      ...state,
      expandedLeagueIds: capExpanded(state.expandedLeagueIds),
    }),
  );
}

export function patchMatchesListUiState(patch: Partial<MatchesListUiState>) {
  const base = readMatchesListUiState() ?? defaultState();
  writeMatchesListUiState({ ...base, ...patch });
}

/** 从子页返回前确保该赛事行处于展开记录中 */
export function ensureLeagueExpanded(leagueId: string) {
  if (!leagueId) return;
  const base = readMatchesListUiState() ?? defaultState();
  const ids = capExpanded([...new Set([...base.expandedLeagueIds, leagueId])]);
  writeMatchesListUiState({ ...base, expandedLeagueIds: ids });
}
