import { ref } from 'vue';
import api from '../api';
import type { MatchPhase } from '../utils/matchPhase';

export interface PlayerMatchSummary {
  id: string;
  leagueId?: string;
  homeTeamName: string;
  awayTeamName: string;
  homeTeamCode?: string;
  awayTeamCode?: string;
  homeTeamLogoUrl?: string | null;
  awayTeamLogoUrl?: string | null;
  startTime: string;
  leagueName: string;
  leagueLogoUrl?: string | null;
  displayOrder?: number;
  isHot?: boolean;
  status?: string;
  bettingOpen?: boolean;
  matchPhase?: MatchPhase;
  score?: {
    htHome: number | null;
    htAway: number | null;
    ftHome: number | null;
    ftAway: number | null;
    homeCorners?: number | null;
    awayCorners?: number | null;
    homeYellowCards?: number | null;
    awayYellowCards?: number | null;
    homeRedCards?: number | null;
    awayRedCards?: number | null;
    homeCards?: number | null;
    awayCards?: number | null;
  } | null;
}

const summaryMatches = ref<PlayerMatchSummary[]>([]);
const summaryLoading = ref(false);

let summaryInflight: Promise<void> | null = null;

async function loadSummary(force = false, silent = false): Promise<void> {
  if (force && !silent) summaryMatches.value = [];
  if (!force && !silent && summaryMatches.value.length > 0) return;
  if (summaryInflight) return summaryInflight;

  if (!silent) summaryLoading.value = true;
  summaryInflight = (async () => {
    try {
      const { data } = await api.get('/player/matches');
      const fresh = (data.data ?? []) as PlayerMatchSummary[];

      if (silent && summaryMatches.value.length > 0) {
        // 静默模式：原地更新，保留对象引用，避免图片重新加载
        const freshMap = new Map(fresh.map((m) => [m.id, m]));
        const existingIds = new Set(summaryMatches.value.map((m) => m.id));

        for (const fm of fresh) {
          if (!existingIds.has(fm.id)) {
            summaryMatches.value.push(fm);
          }
        }
        for (let i = summaryMatches.value.length - 1; i >= 0; i--) {
          const existing = summaryMatches.value[i];
          const f = freshMap.get(existing.id);
          if (f) {
            Object.assign(existing, f);
          } else {
            summaryMatches.value.splice(i, 1);
          }
        }
      } else {
        summaryMatches.value = fresh;
      }
    } catch {
      if (!summaryMatches.value.length) summaryMatches.value = [];
    } finally {
      summaryLoading.value = false;
      summaryInflight = null;
    }
  })();

  return summaryInflight;
}

export function usePlayerMatches() {
  return {
    summaryMatches,
    summaryLoading,
    loadSummary,
  };
}
