<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAdminLocale } from '../../composables/useAdminLocale';
import api from '../../api';
import MatchMarketsPanel from './MatchMarketsPanel.vue';
import type { AdminMatchDetail } from '../match-form';
import AdminSubNav from '../../components/AdminSubNav.vue';

const route = useRoute();
const router = useRouter();
const { t } = useAdminLocale();

const matchId = computed(() => String(route.params.matchId ?? ''));
const loading = ref(false);
const status = ref('DRAFT');
const matchLabel = ref('');

async function load() {
  if (!matchId.value) return;
  loading.value = true;
  try {
    const { data } = await api.get(`/admin/matches/${matchId.value}`);
    const detail = data.data as AdminMatchDetail;
    if (detail.isOutright) {
      ElMessage.warning(t('msg.outright_no_edit'));
      router.replace('/matches');
      return;
    }
    status.value = detail.status;
    const home = detail.homeTeamZh || detail.homeTeamEn || detail.homeTeamCode || '';
    const away = detail.awayTeamZh || detail.awayTeamEn || detail.awayTeamCode || '';
    matchLabel.value =
      detail.matchName?.trim() ||
      (home && away ? `${home} vs ${away}` : `#${matchId.value}`);
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.load_failed'));
  } finally {
    loading.value = false;
  }
}

watch(matchId, load, { immediate: true });
</script>

<template>
  <div v-loading="loading" class="match-markets-page page-scroll">
    <AdminSubNav
      :title="t('matchEditor.section_markets')"
      :subtitle="matchLabel"
    >
      <template #extra>
        <el-tag size="small" type="info">{{ t(`match.status.${status}`) }}</el-tag>
      </template>
    </AdminSubNav>

    <section v-if="matchId" class="panel">
      <MatchMarketsPanel :match-id="matchId" />
    </section>
  </div>
</template>

<style scoped>
.match-markets-page {
  padding: 0 4px 24px;
}

.panel {
  background: #111;
  border: 1px solid #2a2a2a;
  border-radius: 12px;
  overflow: hidden;
}
</style>
