<script setup lang="ts">
import { ref, computed, onMounted, onActivated, onBeforeUnmount } from 'vue';

defineOptions({ name: 'AdminMatches' });
import { useRoute } from 'vue-router';
import { useAdminLocale } from '../composables/useAdminLocale';
import { resolveFormError } from '../i18n/form-validation';
import api from '../api';
import { ElMessage, ElMessageBox } from 'element-plus';
import LeagueMatchesPanel from './matches/LeagueMatchesPanel.vue';
import MatchesSubNav from '../components/MatchesSubNav.vue';
import CountryFlagSelect from '../components/outright/CountryFlagSelect.vue';
import LogoUrlField from '../components/LogoUrlField.vue';
import LeagueArchiveDialog from '../components/LeagueArchiveDialog.vue';
import { getBuiltinCountry } from '../data/builtinCountries';
import {
  readMatchesListUiState,
  writeMatchesListUiState,
  MAX_EXPANDED_LEAGUES,
} from '../utils/matchesListState';
import { formatAmount } from '../utils/format-amount';
import {
  emptyMatchForm,
  buildPlatformPayload,
  fillBuiltinTeam,
  clearBuiltinTeam,
  type MatchCreateForm,
} from './match-form';

const { t } = useAdminLocale();
const route = useRoute();
const leagues = ref<unknown[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const filterStatus = ref('');
const keyword = ref('');
const expandedRowKeys = ref<string[]>([]);

const createLeagueVisible = ref(false);
const createLeagueLoading = ref(false);
const leagueDialogMode = ref<'create' | 'edit'>('create');
const leagueEditingId = ref('');
const leagueForm = ref({ leagueEn: '', leagueZh: '', leagueMs: '', logoUrl: '', deleteOldLogo: false, originalLogoUrl: '' });
const publishingLeagueId = ref('');
const leagueArchiveVisible = ref(false);
const leagueArchiveId = ref('');
const leagueArchiveName = ref('');

const leagueDialogTitle = computed(() =>
  leagueDialogMode.value === 'edit'
    ? t('match.dialog.edit_league')
    : t('match.dialog.create_league'),
);

const createVisible = ref(false);
const createLoading = ref(false);
const form = ref<MatchCreateForm>(emptyMatchForm());
const createUnderLeagueLabel = ref('');

const isFixtureCreate = computed(() => !!form.value.leagueId.trim());

function persistListUiState() {
  writeMatchesListUiState({
    expandedLeagueIds: [...expandedRowKeys.value],
    page: page.value,
    pageSize: pageSize.value,
    filterStatus: filterStatus.value,
    keyword: keyword.value,
  });
}

function applyExpandedFromSaved(savedIds: string[]) {
  const allowed = new Set(leagues.value.map((row) => leagueId(row)));
  expandedRowKeys.value = savedIds.filter((id) => allowed.has(id));
}

type LoadOptions = { restoreExpand?: boolean; keepExpand?: boolean };

async function load(options: LoadOptions = {}) {
  const saved = options.restoreExpand ? readMatchesListUiState() : null;
  if (saved) {
    page.value = saved.page;
    pageSize.value = saved.pageSize;
    filterStatus.value = saved.filterStatus;
    keyword.value = saved.keyword;
  }

  const { data } = await api.get('/admin/leagues', {
    params: {
      page: page.value,
      pageSize: pageSize.value,
      status: filterStatus.value || undefined,
      keyword: keyword.value.trim() || undefined,
    },
  });
  leagues.value = data.data.items;
  total.value = data.data.total;

  if (options.restoreExpand && saved) {
    applyExpandedFromSaved(saved.expandedLeagueIds);
  } else if (!options.keepExpand) {
    expandedRowKeys.value = [];
  } else {
    applyExpandedFromSaved(expandedRowKeys.value);
  }
  persistListUiState();
}

function onSearch() {
  page.value = 1;
  expandedRowKeys.value = [];
  load();
}

onMounted(() => {
  const qStatus = route.query.status;
  if (typeof qStatus === 'string' && qStatus.trim()) {
    filterStatus.value = qStatus.trim();
    page.value = 1;
    load();
    return;
  }
  load({ restoreExpand: true });
});
// KeepAlive 激活时静默刷新，保持展开状态
onActivated(() => { if (leagues.value.length > 0) void load({ keepExpand: true }); });
onBeforeUnmount(persistListUiState);

function onPageChange(p: number) {
  page.value = p;
  load({ keepExpand: true });
}

function onSizeChange(size: number) {
  pageSize.value = size;
  page.value = 1;
  load({ keepExpand: true });
}

function openCreateLeague() {
  leagueDialogMode.value = 'create';
  leagueEditingId.value = '';
  leagueForm.value = { leagueEn: '', leagueZh: '', leagueMs: '', logoUrl: '', deleteOldLogo: false, originalLogoUrl: '' };
  createLeagueVisible.value = true;
}

function openEditLeague(row: unknown) {
  const r = rowOf(row);
  leagueDialogMode.value = 'edit';
  leagueEditingId.value = String(r.id ?? '');
  const currentLogoUrl = String(r.logoUrl ?? '');
  leagueForm.value = {
    leagueEn: String(r.leagueEn ?? ''),
    leagueZh: String(r.leagueZh ?? ''),
    leagueMs: String(r.leagueMs ?? ''),
    logoUrl: currentLogoUrl,
    deleteOldLogo: false,
    originalLogoUrl: currentLogoUrl,
  };
  createLeagueVisible.value = true;
}

async function toggleLeaguePublish(row: unknown) {
  const r = rowOf(row);
  const id = String(r.id ?? '');
  const published = leagueIsPublished(row);
  if (published) {
    try {
      await ElMessageBox.confirm(t('league.confirm_unpublish'), t('common.confirm'), {
        type: 'warning',
        confirmButtonText: t('league.btn.unpublish'),
        cancelButtonText: t('common.cancel'),
      });
    } catch {
      return;
    }
  }
  publishingLeagueId.value = id;
  try {
    await api.put(`/admin/leagues/${id}`, {
      leagueEn: String(r.leagueEn ?? ''),
      leagueZh: String(r.leagueZh ?? ''),
      leagueMs: String(r.leagueMs ?? ''),
      logoUrl: String(r.logoUrl ?? '').trim() || undefined,
      isActive: !published,
    });
    ElMessage.success(published ? t('msg.league_unpublished') : t('msg.league_published'));
    await load({ keepExpand: true });
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    publishingLeagueId.value = '';
  }
}

async function submitLeagueForm() {
  const { leagueEn, leagueZh, leagueMs, logoUrl, deleteOldLogo, originalLogoUrl } = leagueForm.value;
  if (!leagueZh.trim() && !leagueEn.trim()) {
    ElMessage.warning(t('err.league_required'));
    return;
  }
  createLeagueLoading.value = true;
  try {
    const body = {
      leagueEn: leagueEn.trim(),
      leagueZh: leagueZh.trim(),
      leagueMs: leagueMs.trim() || undefined,
      logoUrl: logoUrl.trim() || undefined,
      ...(leagueDialogMode.value === 'create' ? { isActive: false } : {}),
    };
    if (leagueDialogMode.value === 'edit') {
      await api.put(`/admin/leagues/${leagueEditingId.value}`, body);
      ElMessage.success(t('msg.league_updated'));
    } else {
      await api.post('/admin/leagues', body);
      ElMessage.success(t('msg.league_created'));
    }

    // Delete old resource if user checked the option and the URL actually changed
    if (deleteOldLogo && originalLogoUrl && originalLogoUrl !== logoUrl.trim()) {
      try {
        await api.delete('/admin/uploads/by-url', { data: { url: originalLogoUrl } });
        ElMessage.success('旧资源已删除');
      } catch {
        ElMessage.warning('旧资源删除失败，可稍后在媒体库中清理');
      }
    }

    createLeagueVisible.value = false;
    load({ keepExpand: true });
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    createLeagueLoading.value = false;
  }
}

function onTeamCodeChange(side: 'home' | 'away', code: string) {
  if (!code?.trim()) {
    clearBuiltinTeam(form.value, side);
    return;
  }
  const country = getBuiltinCountry(code);
  if (country) fillBuiltinTeam(form.value, side, country);
}

function openCreateFixture(leagueRow: unknown) {
  const r = rowOf(leagueRow);
  form.value = emptyMatchForm();
  form.value.leagueId = String(r.id ?? '');
  form.value.leagueEn = String(r.leagueEn ?? '');
  form.value.leagueZh = String(r.leagueZh ?? '');
  form.value.leagueMs = String(r.leagueMs ?? '');
  createUnderLeagueLabel.value = leagueTitle(leagueRow);
  createVisible.value = true;
}

async function submitCreate() {
  let payload: ReturnType<typeof buildPlatformPayload>;
  try {
    payload = buildPlatformPayload(form.value);
  } catch (e) {
    ElMessage.warning(resolveFormError(e, t));
    return;
  }
  createLoading.value = true;
  try {
    await api.post('/admin/matches', payload);
    ElMessage.success(t('msg.match_created_draft'));
    createUnderLeagueLabel.value = '';
    createVisible.value = false;
    const lid = form.value.leagueId.trim();
    await load({ keepExpand: true });
    if (lid && !expandedRowKeys.value.includes(lid)) {
      expandedRowKeys.value = capExpandedLeagueIds([...expandedRowKeys.value, lid]);
      persistListUiState();
    }
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.create_failed'));
  } finally {
    createLoading.value = false;
  }
}

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

function onExpandChange(_row: unknown, expanded: unknown[]) {
  expandedRowKeys.value = capExpandedLeagueIds(expanded.map((r) => leagueId(r)));
  persistListUiState();
}

function onRowClick(row: unknown, _column: unknown, event: MouseEvent) {
  if ((event.target as HTMLElement).closest('.el-table__expand-icon')) return;
  const id = leagueId(row);
  if (expandedRowKeys.value.includes(id)) {
    expandedRowKeys.value = expandedRowKeys.value.filter((k) => k !== id);
  } else {
    const next = [...expandedRowKeys.value, id];
    expandedRowKeys.value = capExpandedLeagueIds(next);
  }
  persistListUiState();
}

function rowClassName() {
  return 'row-expandable';
}

function rowOf(row: unknown) {
  return row as Record<string, unknown>;
}
function leagueId(row: unknown) {
  return String(rowOf(row).id ?? '');
}
function leagueTitle(row: unknown) {
  const r = rowOf(row);
  const zh = String(r.leagueZh ?? '').trim();
  const en = String(r.leagueEn ?? '').trim();
  return zh || en || String(r.code ?? '—');
}
function leagueNameZh(row: unknown) {
  const zh = String(rowOf(row).leagueZh ?? '').trim();
  return zh || '—';
}
function leagueNameEn(row: unknown) {
  const en = String(rowOf(row).leagueEn ?? '').trim();
  return en || '—';
}
function leagueMatchCount(row: unknown) {
  return Number(rowOf(row).matchCount ?? 0);
}

function leagueIsPublished(row: unknown) {
  return Boolean(rowOf(row).isPublished);
}

function leagueStatusLabel(row: unknown) {
  return leagueIsPublished(row) ? t('league.status.PUBLISHED') : t('league.status.UNPUBLISHED');
}

function leagueStatusTagType(row: unknown): 'success' | 'info' {
  return leagueIsPublished(row) ? 'success' : 'info';
}

function leagueBetStats(row: unknown) {
  return rowOf(row).betStats as
    | { betCount?: number; totalStake?: string; pendingCount?: number }
    | undefined;
}

function leagueBetCount(row: unknown) {
  return Number(leagueBetStats(row)?.betCount ?? 0);
}

function leagueTotalStake(row: unknown) {
  return formatAmount(String(leagueBetStats(row)?.totalStake ?? '0'));
}

function leaguePendingBets(row: unknown) {
  return Number(leagueBetStats(row)?.pendingCount ?? 0);
}
function isLeagueExpanded(id: string) {
  return expandedRowKeys.value.includes(id);
}

function openLeagueArchive(row: unknown) {
  leagueArchiveId.value = leagueId(row);
  leagueArchiveName.value = leagueTitle(row);
  leagueArchiveVisible.value = true;
}

function onLeagueArchived() {
  void load();
}

</script>

<template>
  <div class="admin-list-page matches-page">
  <div class="list-chrome">
    <div class="list-chrome__row">
      <div class="list-chrome__left">
        <MatchesSubNav embedded />
        <div class="list-chrome__filters">
          <div class="list-chrome__field">
            <span class="list-chrome__label">{{ t('common.keyword') }}</span>
            <el-input
              v-model="keyword"
              :placeholder="t('match.filter.keyword_ph')"
              clearable
              style="width: 200px"
              @keyup.enter="load"
            />
          </div>
          <div class="list-chrome__field">
            <span class="list-chrome__label">{{ t('common.status') }}</span>
            <el-select v-model="filterStatus" :placeholder="t('common.all')" clearable style="width: 120px">
              <el-option :label="t('match.status.DRAFT')" value="DRAFT" />
              <el-option :label="t('match.status.PUBLISHED')" value="PUBLISHED" />
              <el-option :label="t('match.status.CLOSED')" value="CLOSED" />
              <el-option :label="t('match.status.PENDING_SETTLEMENT')" value="PENDING_SETTLEMENT" />
              <el-option :label="t('match.status.SETTLED')" value="SETTLED" />
            </el-select>
          </div>
          <el-button type="primary" class="list-chrome__submit" @click="onSearch">
            {{ t('common.search') }}
          </el-button>
        </div>
      </div>
      <div class="list-chrome__actions">
        <el-button type="primary" @click.stop="openCreateLeague">
          {{ t('match.create_btn') }}
        </el-button>
      </div>
    </div>
    <p v-if="filterStatus" class="list-hint">{{ t('match.filter.status_hint') }}</p>
  </div>

  <section class="list-panel">
    <p class="list-hint">{{ t('match.expand_league_hint') }}</p>
    <div class="table-wrap">
    <el-table
      :data="leagues"
      stripe
      row-key="id"
      :expand-row-keys="expandedRowKeys"
      :row-class-name="rowClassName"
      @expand-change="onExpandChange"
      @row-click="onRowClick"
    >
      <el-table-column type="expand" width="40">
        <template #default="{ row }">
          <template v-if="isLeagueExpanded(leagueId(row))">
            <LeagueMatchesPanel
              :league-id="leagueId(row)"
              :filter-status="filterStatus"
              :keyword="keyword"
              @changed="() => load({ keepExpand: true })"
              @add-match="openCreateFixture(row)"
            />
          </template>
        </template>
      </el-table-column>
      <el-table-column type="index" :index="(i: number) => (page - 1) * pageSize + i + 1" :label="t('common.seq')" width="70" align="center" />
      <el-table-column :label="t('match.col.league')" width="148" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="league-cell">
            <img
              v-if="rowOf(row).logoUrl"
              :src="String(rowOf(row).logoUrl)"
              alt=""
              class="league-logo"
            />
            <span class="matchup-link">{{ leagueNameZh(row) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.league_en')" width="180" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="league-en">{{ leagueNameEn(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('common.status')" width="88" align="center">
        <template #default="{ row }">
          <el-tag :type="leagueStatusTagType(row)" size="small" effect="plain">
            {{ leagueStatusLabel(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.fixture_count')" width="88" align="center">
        <template #default="{ row }">{{ leagueMatchCount(row) }}</template>
      </el-table-column>
      <el-table-column :label="t('match.col.bet_count')" width="72" align="center">
        <template #default="{ row }">
          <span :class="{ 'bet-stat-active': leagueBetCount(row) > 0 }">{{ leagueBetCount(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.total_stake')" width="108" align="right">
        <template #default="{ row }">{{ leagueTotalStake(row) }}</template>
      </el-table-column>
      <el-table-column :label="t('match.col.pending_bets')" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="leaguePendingBets(row) > 0" type="warning" size="small" effect="plain">
            {{ leaguePendingBets(row) }}
          </el-tag>
          <span v-else class="bet-stat-zero">0</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('match.col.league_code')" width="120" show-overflow-tooltip>
        <template #default="{ row }">{{ rowOf(row).code }}</template>
      </el-table-column>
      <el-table-column width="168" align="center" fixed="right">
        <template #header>
          <div class="actions-col-header">
            <span class="actions-col-header__label">{{ t('common.actions') }}</span>
          </div>
        </template>
        <template #default="{ row }">
          <div class="league-row-actions">
            <div class="league-action-group">
              <el-button size="small" type="primary" @click.stop="openEditLeague(row)">
                {{ t('common.edit') }}
              </el-button>
              <el-button
                v-if="!leagueIsPublished(row)"
                size="small"
                type="success"
                :loading="publishingLeagueId === leagueId(row)"
                @click.stop="toggleLeaguePublish(row)"
              >
                {{ t('common.publish') }}
              </el-button>
              <el-button
                v-else
                size="small"
                type="warning"
                :loading="publishingLeagueId === leagueId(row)"
                @click.stop="toggleLeaguePublish(row)"
              >
                {{ t('league.btn.unpublish') }}
              </el-button>
              <el-button size="small" type="danger" plain @click.stop="openLeagueArchive(row)">
                {{ t('common.delete') }}
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        background
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>
  </section>

  <el-dialog v-model="createLeagueVisible" :title="leagueDialogTitle" width="520px" destroy-on-close>
    <el-form label-width="96px">
      <el-form-item :label="t('match.field.league_zh')">
        <el-input v-model="leagueForm.leagueZh" :placeholder="t('match.ph.league_zh')" />
      </el-form-item>
      <el-form-item :label="t('match.field.league_en')">
        <el-input v-model="leagueForm.leagueEn" :placeholder="t('match.ph.league_en')" />
      </el-form-item>
      <el-form-item :label="t('match.field.league_ms')">
        <el-input v-model="leagueForm.leagueMs" :placeholder="t('match.ph.league_ms')" />
      </el-form-item>
      <el-form-item :label="t('match.field.league_logo')">
        <LogoUrlField
          v-model="leagueForm.logoUrl"
          v-model:delete-old="leagueForm.deleteOldLogo"
          upload-only
          upload-category="banners"
        />
      </el-form-item>
      <p v-if="leagueDialogMode === 'create'" class="field-hint">{{ t('match.hint.create_league') }}</p>
    </el-form>
    <template #footer>
      <el-button @click="createLeagueVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="createLeagueLoading" @click="submitLeagueForm">
        {{ leagueDialogMode === 'edit' ? t('common.save') : t('user.btn.create') }}
      </el-button>
    </template>
  </el-dialog>

  <el-dialog
    v-model="createVisible"
    :title="t('match.dialog.create_fixture')"
    width="860px"
    destroy-on-close
  >
    <el-form label-width="96px">
      <el-form-item v-if="isFixtureCreate" :label="t('match.col.league')">
        <span class="league-readonly">{{ createUnderLeagueLabel }}</span>
      </el-form-item>
      <template v-else>
        <el-form-item :label="t('match.field.league_en')">
          <el-input v-model="form.leagueEn" :placeholder="t('match.ph.league_en')" />
        </el-form-item>
        <el-form-item :label="t('match.field.league_zh')">
          <el-input v-model="form.leagueZh" :placeholder="t('match.ph.league_zh')" />
        </el-form-item>
      </template>
      <el-form-item :label="t('match.field.kickoff')" required>
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          value-format="YYYY-MM-DDTHH:mm:ss"
          :placeholder="t('matchEditor.ph.kickoff')"
          style="width: 100%"
        />
        <p class="field-hint schedule-timezone-hint">{{ t('match.timezone.platform_hint') }}</p>
      </el-form-item>
      <div class="teams-row">
        <!-- Home Team Column -->
        <div class="team-col">
          <div class="team-col-title">{{ t('match.field.home_team') }}</div>
          <el-form-item :label="t('match.field.home_team')" required>
            <CountryFlagSelect
              v-model="form.homeTeamCode"
              size="default"
              class="team-country-select"
              @update:model-value="onTeamCodeChange('home', $event)"
            />
          </el-form-item>
          <el-form-item :label="t('match.field.home_en')" label-width="108px">
            <el-input v-model="form.homeTeamEn" :placeholder="t('match.ph.home_en')" />
          </el-form-item>
          <el-form-item :label="t('match.field.home_zh')" label-width="108px">
            <el-input v-model="form.homeTeamZh" :placeholder="t('match.ph.home_zh')" />
          </el-form-item>
          <el-form-item :label="t('match.field.home_ms')" label-width="108px">
            <el-input v-model="form.homeTeamMs" :placeholder="t('match.ph.home_ms')" />
          </el-form-item>
          <el-form-item :label="t('matchEditor.field.home_logo')" label-width="108px">
            <LogoUrlField v-model="form.homeTeamLogoUrl" :team-code="form.homeTeamCode" upload-category="teams" />
          </el-form-item>
        </div>
        <!-- Away Team Column -->
        <div class="team-col">
          <div class="team-col-title">{{ t('match.field.away_team') }}</div>
          <el-form-item :label="t('match.field.away_team')" required>
            <CountryFlagSelect
              v-model="form.awayTeamCode"
              size="default"
              class="team-country-select"
              @update:model-value="onTeamCodeChange('away', $event)"
            />
          </el-form-item>
          <el-form-item :label="t('match.field.away_en')" label-width="108px">
            <el-input v-model="form.awayTeamEn" :placeholder="t('match.ph.away_en')" />
          </el-form-item>
          <el-form-item :label="t('match.field.away_zh')" label-width="108px">
            <el-input v-model="form.awayTeamZh" :placeholder="t('match.ph.away_zh')" />
          </el-form-item>
          <el-form-item :label="t('match.field.away_ms')" label-width="108px">
            <el-input v-model="form.awayTeamMs" :placeholder="t('match.ph.away_ms')" />
          </el-form-item>
          <el-form-item :label="t('matchEditor.field.away_logo')" label-width="108px">
            <LogoUrlField v-model="form.awayTeamLogoUrl" :team-code="form.awayTeamCode" upload-category="teams" />
          </el-form-item>
        </div>
      </div>
      <el-form-item :label="t('match.field.featured')">
        <el-switch v-model="form.isHot" />
      </el-form-item>
      <p class="field-hint">{{ t('match.hint.create_draft') }}</p>
    </el-form>
    <template #footer>
      <el-button @click="createVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="createLoading" @click="submitCreate">{{ t('user.btn.create') }}</el-button>
    </template>
  </el-dialog>

  <LeagueArchiveDialog
    v-model="leagueArchiveVisible"
    :league-id="leagueArchiveId"
    :league-name="leagueArchiveName"
    @archived="onLeagueArchived"
  />
  </div>
</template>

<style scoped>
.team-country-select {
  width: 100%;
}

.teams-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0 20px;
}

.team-col {
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.team-col-title {
  font-size: 14px;
  font-weight: 750;
  color: var(--text);
  margin-bottom: 10px;
  padding-bottom: 6px;
  border-bottom: 1px solid var(--border-soft);
}

.field-hint {
  font-size: 12px;
  color: var(--text-muted);
  margin: 0;
  line-height: 1.5;
}

.schedule-timezone-hint {
  margin-top: 4px;
}

.edit-hint {
  margin-bottom: 16px;
}

/* 列表表格随内容增高，滚动交给外层 table-wrap（仅赛事行） */
.matches-page .table-wrap .el-table {
  height: auto !important;
}
.matches-page .table-wrap :deep(.el-table__header),
.matches-page .table-wrap :deep(.el-table__body) {
  width: 100% !important;
}

.matches-page :deep(.el-table__expanded-cell) {
  padding: 0 !important;
  background: #fbfaf7;
}

.list-panel :deep(.row-expandable) {
  cursor: pointer;
}

.list-panel :deep(.row-no-expand .el-table__expand-icon) {
  visibility: hidden;
  pointer-events: none;
}

.matchup-link {
  color: var(--green-text);
}
.bet-stat-active {
  color: var(--green-text);
  font-weight: 600;
}
.bet-stat-zero {
  color: #aaa49a;
}

.league-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.league-logo {
  width: 28px;
  height: 28px;
  object-fit: contain;
  flex-shrink: 0;
}

.league-en {
  color: var(--text-muted);
  font-size: 13px;
}

.league-readonly {
  color: var(--success-text);
  font-weight: 700;
}

.actions-col-header {
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 0 4px;
  box-sizing: border-box;
  white-space: nowrap;
}

.actions-col-header__label {
  font-size: 12px;
  font-weight: 700;
  color: var(--text-muted);
  line-height: 1;
}

.actions-col-header :deep(.el-button) {
  margin: 0 !important;
  padding: 6px 10px !important;
  height: 28px !important;
  min-height: 28px !important;
  font-size: 12px !important;
  font-weight: 600;
  border-radius: 6px;
  white-space: nowrap;
}

.matches-page .table-wrap :deep(.el-table__header .el-table__cell) {
  padding: 6px 0;
}

.matches-page .table-wrap :deep(.el-table__header .cell) {
  overflow: visible;
}

.league-row-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px 8px;
  flex-wrap: wrap;
}

.league-action-group {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 2px 4px;
  border-radius: 8px;
  background: #fbfaf7;
  border: 1px solid var(--border-soft);
}

.league-row-actions :deep(.el-button) {
  margin: 0 !important;
  min-width: 52px;
  padding: 4px 10px !important;
  font-size: 12px !important;
  border-radius: 6px;
}

.league-row-actions :deep(.el-button:not(.is-disabled):not(:disabled)) {
  cursor: pointer;
}

.league-row-actions :deep(.el-button.is-disabled),
.league-row-actions :deep(.el-button:disabled) {
  cursor: not-allowed;
}

:deep(.logo-url-field) {
  width: 100%;
}

.list-chrome__actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.team-col {
  padding: 12px;
  border: 1px solid var(--border-soft);
  border-radius: 8px;
  background: #fbfaf7;
}

.matchup-link,
.bet-stat-active {
  color: var(--primary-link);
}

.league-row-actions :deep(.el-button) {
  min-height: 26px;
  font-weight: 700;
}

@media (max-width: 760px) {
  .list-chrome__actions {
    width: 100%;
    justify-content: flex-start;
  }

  .teams-row {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .actions-col-header {
    flex-wrap: wrap;
    justify-content: flex-start;
  }

  .league-row-actions {
    justify-content: flex-start;
  }
}

</style>
