<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAdminLocale } from '../../composables/useAdminLocale';
import api from '../../api';
import LogoUrlField from '../../components/LogoUrlField.vue';
import {
  BUILTIN_COUNTRIES,
  countryFlagUrl,
  teamRowDisplayName,
} from '../../data/builtinCountries';

interface SelectionRow {
  id: string;
  teamCode: string;
  rank: number;
  teamZh: string;
  teamEn: string;
  logoUrl: string | null;
  odds: string;
  status: string;
  editOdds: number;
}

interface AddableTeam {
  teamCode: string;
  teamZh: string;
  teamEn: string;
  logoUrl: string | null;
}

type AddFilter = 'all' | 'custom';
type SortKey = 'rank' | 'name' | 'code' | 'odds' | 'saved_odds';
type SortDir = 'asc' | 'desc';

function teamFlagUrl(row: { teamCode: string; logoUrl?: string | null }): string {
  const custom = row.logoUrl?.trim();
  if (custom) return custom;
  return countryFlagUrl(row.teamCode);
}

const props = defineProps<{
  leagueId: string;
}>();

const emit = defineEmits<{
  updated: [];
}>();

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

const matchStatus = ref('');

function teamDisplayName(row: { teamCode: string; teamZh: string; teamEn: string }) {
  return teamRowDisplayName(row, locale.value);
}

const loading = ref(false);
const savingOdds = ref(false);
const reopening = ref(false);
const adding = ref(false);
const matchId = ref('');
const leagueIsPublished = ref(true);
const unsettledFixtureCount = ref(0);
const selections = ref<SelectionRow[]>([]);

const addVisible = ref(false);
const addFilter = ref<AddFilter>('all');
const addSearch = ref('');
const selectedCodes = ref<Set<string>>(new Set());
const defaultOdds = ref(10);
const customTeam = ref({ teamCode: '', teamZh: '', teamEn: '', logoUrl: '' });

const batchMode = ref(false);
const batchSelectedIds = ref<Set<string>>(new Set());
const batchOdds = ref(10);
const batchRemoving = ref(false);

const sortBy = ref<SortKey>('rank');
const sortDir = ref<SortDir>('asc');

const openTeamCodes = computed(
  () => new Set(selections.value.map((s) => s.teamCode.toUpperCase())),
);

const allBuiltinAddable = computed<AddableTeam[]>(() =>
  BUILTIN_COUNTRIES.filter((c) => !openTeamCodes.value.has(c.code)).map((c) => ({
    teamCode: c.code,
    teamZh: c.nameZh,
    teamEn: c.nameEn,
    logoUrl: null,
  })),
);

const sourceTeams = computed<AddableTeam[]>(() => allBuiltinAddable.value);

const visibleAddTeams = computed(() => {
  const q = addSearch.value.trim().toLowerCase();
  if (!q) return sourceTeams.value;
  return sourceTeams.value.filter(
    (team) =>
      team.teamCode.toLowerCase().includes(q) ||
      team.teamZh.toLowerCase().includes(q) ||
      team.teamEn.toLowerCase().includes(q),
  );
});

const selectedCount = computed(() => selectedCodes.value.size);
const batchSelectedCount = computed(() => batchSelectedIds.value.size);

const sortedSelections = computed(() => {
  const rows = [...selections.value];
  const dir = sortDir.value === 'asc' ? 1 : -1;
  const loc = locale.value;
  rows.sort((a, b) => {
    let cmp = 0;
    switch (sortBy.value) {
      case 'rank':
        cmp = a.rank - b.rank;
        break;
      case 'name':
        cmp = teamRowDisplayName(a, loc).localeCompare(teamRowDisplayName(b, loc), loc);
        break;
      case 'code':
        cmp = a.teamCode.localeCompare(b.teamCode);
        break;
      case 'odds':
        cmp = a.editOdds - b.editOdds;
        break;
      case 'saved_odds':
        cmp =
          (Number.parseFloat(a.odds) || 0) - (Number.parseFloat(b.odds) || 0);
        break;
    }
    if (cmp === 0) cmp = a.teamCode.localeCompare(b.teamCode);
    return cmp * dir;
  });
  return rows;
});

const canCloseOutright = computed(() => matchStatus.value === 'PUBLISHED');
const canReopenOutright = computed(() =>
  ['CLOSED', 'PENDING_SETTLEMENT'].includes(matchStatus.value),
);
const canSettleOutright = computed(() =>
  ['CLOSED', 'PENDING_SETTLEMENT', 'SETTLED'].includes(matchStatus.value),
);
const canProceedSettle = computed(
  () => matchStatus.value === 'SETTLED' || unsettledFixtureCount.value === 0,
);
const showLeagueUnpublishedHint = computed(
  () => !leagueIsPublished.value && matchStatus.value === 'DRAFT',
);
const showUnsettledFixturesHint = computed(
  () =>
    unsettledFixtureCount.value > 0 &&
    ['CLOSED', 'PENDING_SETTLEMENT'].includes(matchStatus.value),
);
const settleButtonLabel = computed(() =>
  matchStatus.value === 'SETTLED' ? t('common.resettle') : t('common.settle'),
);
const statusLabel = computed(() => {
  const key = `match.status.${matchStatus.value}`;
  const label = t(key);
  return label === key ? matchStatus.value : label;
});
const statusTagType = computed(() => {
  switch (matchStatus.value) {
    case 'PUBLISHED':
      return 'success';
    case 'CLOSED':
    case 'PENDING_SETTLEMENT':
      return 'warning';
    case 'SETTLED':
      return 'info';
    default:
      return 'info';
  }
});

async function reopenOutright() {
  if (!matchId.value) return;
  try {
    await ElMessageBox.confirm(t('outright.confirm_reopen'), t('common.confirm'), {
      type: 'warning',
    });
  } catch {
    return;
  }
  reopening.value = true;
  try {
    await api.post(`/admin/matches/${matchId.value}/reopen`);
    ElMessage.success(t('msg.reopened'));
    await load();
    emit('updated');
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    reopening.value = false;
  }
}

async function closeOutright() {
  if (!matchId.value) return;
  try {
    await ElMessageBox.confirm(t('outright.confirm_close'), t('common.confirm'), {
      type: 'warning',
    });
  } catch {
    return;
  }
  await api.post(`/admin/matches/${matchId.value}/close`);
  ElMessage.success(t('msg.closed'));
  await load();
  emit('updated');
}

function goSettle() {
  if (!matchId.value) return;
  if (!canProceedSettle.value) {
    ElMessage.warning(
      t('outright.unsettled_fixtures_hint', { n: unsettledFixtureCount.value }),
    );
    return;
  }
  const title = String(route.query.title ?? '').trim();
  void router.push({
    path: `/settlement/${matchId.value}`,
    query: {
      returnTo: `/matches/outrights/leagues/${props.leagueId}`,
      ...(title ? { title } : {}),
    },
  });
}

async function load() {
  if (!props.leagueId) return;
  loading.value = true;
  try {
    const { data } = await api.get(`/admin/leagues/${props.leagueId}/outright`);
    const payload = data.data as {
      id: string;
      status?: string;
      leagueIsPublished?: boolean;
      unsettledFixtureCount?: number;
      fixtureSyncAdded?: number;
      fixtureSyncReopened?: number;
      selections: Array<{
        id: string;
        teamCode: string;
        rank: number;
        teamZh: string;
        teamEn: string;
        logoUrl?: string | null;
        odds: string;
        status: string;
      }>;
    };
    matchId.value = payload.id;
    matchStatus.value = payload.status ?? '';
    leagueIsPublished.value = payload.leagueIsPublished ?? true;
    unsettledFixtureCount.value = payload.unsettledFixtureCount ?? 0;
    selections.value = (payload.selections ?? [])
      .filter((s) => s.status === 'OPEN')
      .map((s) => ({
        ...s,
        logoUrl: s.logoUrl ?? null,
        editOdds: Number.parseFloat(s.odds) || 10,
      }));
    const openIds = new Set(selections.value.map((s) => s.id));
    batchSelectedIds.value = new Set(
      [...batchSelectedIds.value].filter((id) => openIds.has(id)),
    );
    const added = payload.fixtureSyncAdded ?? 0;
    if (added > 0) {
      ElMessage.success(t('outright.fixture_sync_added', { n: added }));
    }
  } 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;
  }
}

function resetCustomTeamForm() {
  customTeam.value = { teamCode: '', teamZh: '', teamEn: '', logoUrl: '' };
}

function onCustomCodeInput(value: string) {
  customTeam.value.teamCode = value.toUpperCase().replace(/[^A-Z0-9_]/g, '');
}

function openAddDialog() {
  addFilter.value = 'all';
  addSearch.value = '';
  defaultOdds.value = 10;
  resetCustomTeamForm();
  selectedCodes.value = new Set();
  addVisible.value = true;
}

function onAddFilterChange() {
  addSearch.value = '';
  if (addFilter.value === 'all') {
    selectedCodes.value = new Set();
  }
}

function toggleTeam(code: string) {
  const next = new Set(selectedCodes.value);
  if (next.has(code)) next.delete(code);
  else next.add(code);
  selectedCodes.value = next;
}

function selectAllVisible() {
  selectedCodes.value = new Set(
    visibleAddTeams.value.map((team) => team.teamCode),
  );
}

function clearSelection() {
  selectedCodes.value = new Set();
}

function toggleBatchMode() {
  batchMode.value = !batchMode.value;
  if (!batchMode.value) batchSelectedIds.value = new Set();
}

function toggleBatchSelect(id: string) {
  const next = new Set(batchSelectedIds.value);
  if (next.has(id)) next.delete(id);
  else next.add(id);
  batchSelectedIds.value = next;
}

function selectAllBatch() {
  batchSelectedIds.value = new Set(selections.value.map((row) => row.id));
}

function clearBatchSelection() {
  batchSelectedIds.value = new Set();
}

function applyBatchOdds() {
  if (batchSelectedIds.value.size === 0) {
    ElMessage.warning(t('outright.batch.err_none'));
    return;
  }
  if (batchOdds.value <= 1) {
    ElMessage.warning(t('outright.err_odds_min'));
    return;
  }
  for (const row of selections.value) {
    if (batchSelectedIds.value.has(row.id)) row.editOdds = batchOdds.value;
  }
  ElMessage.success(
    t('outright.batch.apply_ok', { n: batchSelectedIds.value.size }),
  );
}

async function batchRemove() {
  if (!matchId.value) return;
  if (batchSelectedIds.value.size === 0) {
    ElMessage.warning(t('outright.batch.err_none'));
    return;
  }
  try {
    await ElMessageBox.confirm(
      t('outright.batch.confirm_remove', { n: batchSelectedIds.value.size }),
      { type: 'warning' },
    );
  } catch {
    return;
  }

  batchRemoving.value = true;
  const ids = [...batchSelectedIds.value];
  let ok = 0;
  let fail = 0;
  try {
    for (const id of ids) {
      try {
        await api.delete(`/admin/outrights/${matchId.value}/selections/${id}`);
        ok++;
      } catch {
        fail++;
      }
    }
    if (fail === 0) {
      ElMessage.success(t('outright.batch.remove_ok', { n: ok }));
    } else {
      ElMessage.warning(t('outright.batch.remove_partial', { ok, fail }));
    }
    batchSelectedIds.value = new Set();
    await load();
    emit('updated');
  } finally {
    batchRemoving.value = false;
  }
}

async function saveOdds() {
  if (!matchId.value) return;
  for (const row of selections.value) {
    if (row.editOdds <= 1) {
      ElMessage.warning(t('outright.err_odds_min'));
      return;
    }
  }
  savingOdds.value = true;
  try {
    await api.put(`/admin/outrights/${matchId.value}/odds`, {
      updates: selections.value.map((row) => ({
        selectionId: row.id,
        odds: row.editOdds,
      })),
    });
    ElMessage.success(t('msg.outright_odds_saved'));
    await load();
    emit('updated');
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    savingOdds.value = false;
  }
}

async function submitCustomAdd() {
  if (!matchId.value) return;
  const code = customTeam.value.teamCode.trim().toUpperCase();
  const teamZh = customTeam.value.teamZh.trim();
  const teamEn = customTeam.value.teamEn.trim();
  if (!code) {
    ElMessage.warning(t('outright.add.err_code_required'));
    return;
  }
  if (!teamZh && !teamEn) {
    ElMessage.warning(t('outright.add.err_name_required'));
    return;
  }
  if (defaultOdds.value <= 1) {
    ElMessage.warning(t('outright.err_odds_min'));
    return;
  }
  if (openTeamCodes.value.has(code)) {
    ElMessage.warning(t('outright.add.err_duplicate'));
    return;
  }

  adding.value = true;
  try {
    await api.post(`/admin/outrights/${matchId.value}/selections`, {
      teamCode: code,
      teamZh: teamZh || teamEn,
      teamEn: teamEn || teamZh,
      logoUrl: customTeam.value.logoUrl.trim() || undefined,
      odds: defaultOdds.value,
    });
    ElMessage.success(t('msg.saved'));
    addVisible.value = false;
    resetCustomTeamForm();
    await load();
    emit('updated');
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    adding.value = false;
  }
}

function onAddConfirm() {
  if (addFilter.value === 'custom') {
    void submitCustomAdd();
    return;
  }
  void submitAdd();
}

async function submitAdd() {
  if (!matchId.value) return;
  if (selectedCodes.value.size === 0) {
    ElMessage.warning(t('outright.add.err_none'));
    return;
  }
  if (defaultOdds.value <= 1) {
    ElMessage.warning(t('outright.err_odds_min'));
    return;
  }

  const byCode = new Map(
    allBuiltinAddable.value.map((team) => [team.teamCode, team]),
  );

  const items = [...selectedCodes.value]
    .map((code) => byCode.get(code))
    .filter((team): team is AddableTeam => !!team)
    .map((team) => ({
      teamCode: team.teamCode,
      teamZh: team.teamZh,
      teamEn: team.teamEn,
      logoUrl: team.logoUrl?.trim() || undefined,
      odds: defaultOdds.value,
    }));

  if (!items.length) {
    ElMessage.warning(t('outright.add.err_none'));
    return;
  }

  adding.value = true;
  try {
    const { data } = await api.post(
      `/admin/outrights/${matchId.value}/selections/batch`,
      { items },
    );
    const batch = (data.data as { batchResult?: { added: number; skipped: number } })
      ?.batchResult;
    if (batch) {
      ElMessage.success(
        t('msg.outright_teams_added', {
          n: batch.added,
          skipped: batch.skipped,
        }),
      );
    } else {
      ElMessage.success(t('msg.saved'));
    }
    addVisible.value = false;
    selectedCodes.value = new Set();
    await load();
    emit('updated');
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    adding.value = false;
  }
}

async function removeSelection(row: SelectionRow) {
  if (!matchId.value) return;
  try {
    await ElMessageBox.confirm(
      t('outright.confirm_remove', { name: teamDisplayName(row) }),
      { type: 'warning' },
    );
  } catch {
    return;
  }
  loading.value = true;
  try {
    await api.delete(`/admin/outrights/${matchId.value}/selections/${row.id}`);
    ElMessage.success(t('msg.saved'));
    await load();
    emit('updated');
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.leagueId,
  () => {
    void load();
  },
  { immediate: true },
);
</script>

<template>
  <div v-loading="loading" class="outright-odds-panel">
    <div class="outright-odds-panel__head">
      <div class="outright-odds-panel__head-text">
        <p class="outright-odds-panel__hint">{{ t('outright.odds_only_hint') }}</p>
        <p v-if="showLeagueUnpublishedHint" class="outright-odds-panel__workflow-hint">
          {{ t('outright.league_unpublished_hint') }}
        </p>
        <p v-if="showUnsettledFixturesHint" class="outright-odds-panel__workflow-hint">
          {{ t('outright.unsettled_fixtures_hint', { n: unsettledFixtureCount }) }}
        </p>
      </div>
      <div class="outright-odds-panel__actions">
        <el-tag v-if="matchStatus" size="small" :type="statusTagType" effect="dark">
          {{ statusLabel }}
        </el-tag>
        <el-button
          v-if="canCloseOutright"
          type="warning"
          plain
          size="small"
          @click="closeOutright"
        >
          {{ t('outright.btn.close') }}
        </el-button>
        <el-button
          v-if="canReopenOutright"
          type="primary"
          plain
          size="small"
          :loading="reopening"
          @click="reopenOutright"
        >
          {{ t('outright.btn.reopen') }}
        </el-button>
        <el-button
          v-if="canSettleOutright"
          type="success"
          plain
          size="small"
          :disabled="!canProceedSettle"
          @click="goSettle"
        >
          {{ settleButtonLabel }}
        </el-button>
        <el-button
          v-if="selections.length"
          :type="batchMode ? 'warning' : 'default'"
          plain
          size="small"
          @click="toggleBatchMode"
        >
          {{ batchMode ? t('outright.batch.exit') : t('outright.batch.mode') }}
        </el-button>
        <el-button type="primary" plain size="small" @click="openAddDialog">
          {{ t('outright.btn.add_team') }}
        </el-button>
        <el-button
          type="primary"
          size="small"
          :loading="savingOdds"
          :disabled="selections.length === 0"
          @click="saveOdds"
        >
          {{ t('outright.btn.save_odds') }}
        </el-button>
      </div>
    </div>

    <div v-if="batchMode && selections.length" class="outright-odds-panel__batch">
      <el-button size="small" link type="primary" @click="selectAllBatch">
        {{ t('outright.add.select_all') }}
      </el-button>
      <el-button size="small" link @click="clearBatchSelection">
        {{ t('outright.add.clear_selection') }}
      </el-button>
      <span class="outright-odds-panel__batch-count">
        {{ t('outright.add.selected_count', { n: batchSelectedCount }) }}
      </span>
      <label class="outright-odds-panel__batch-odds">
        {{ t('outright.add.default_odds') }}
        <el-input-number
          v-model="batchOdds"
          :min="1.01"
          :step="0.05"
          :precision="2"
          size="small"
          controls-position="right"
          @click.stop
        />
      </label>
      <el-button
        size="small"
        :disabled="batchSelectedCount === 0"
        @click="applyBatchOdds"
      >
        {{ t('outright.batch.apply_odds') }}
      </el-button>
      <el-button
        size="small"
        type="danger"
        plain
        :loading="batchRemoving"
        :disabled="batchSelectedCount === 0"
        @click="batchRemove"
      >
        {{ t('outright.batch.remove') }}
      </el-button>
    </div>

    <div v-if="selections.length" class="outright-odds-panel__sort">
      <span class="outright-odds-panel__sort-label">{{ t('outright.sort.label') }}</span>
      <el-select v-model="sortBy" size="small" class="outright-odds-panel__sort-by">
        <el-option value="rank" :label="t('outright.sort.rank')" />
        <el-option value="name" :label="t('outright.sort.name')" />
        <el-option value="code" :label="t('outright.sort.code')" />
        <el-option value="odds" :label="t('outright.sort.odds')" />
        <el-option value="saved_odds" :label="t('outright.sort.saved_odds')" />
      </el-select>
      <el-select v-model="sortDir" size="small" class="outright-odds-panel__sort-dir">
        <el-option value="asc" :label="t('outright.sort.asc')" />
        <el-option value="desc" :label="t('outright.sort.desc')" />
      </el-select>
    </div>

    <div v-if="selections.length" class="team-list-scroll">
      <div class="team-list">
        <div
          v-for="row in sortedSelections"
          :key="row.id"
          class="team-row-wrap"
          :class="{
            'team-row-wrap--batch': batchMode,
            'team-row-wrap--batch-selected': batchMode && batchSelectedIds.has(row.id),
          }"
          @click="batchMode ? toggleBatchSelect(row.id) : undefined"
        >
          <article class="team-row">
            <span
              v-if="batchMode && batchSelectedIds.has(row.id)"
              class="team-row__check"
              aria-hidden="true"
            >✓</span>
            <div class="team-row__head">
              <span class="team-row__rank">{{ row.rank }}</span>
              <img
                v-if="teamFlagUrl(row)"
                :src="teamFlagUrl(row)"
                :alt="teamDisplayName(row)"
                class="team-row__flag"
              />
              <div class="team-row__names">
                <span class="team-row__name" :title="teamDisplayName(row)">
                  {{ teamDisplayName(row) }}
                </span>
                <span class="team-row__meta">{{ row.teamCode }}</span>
              </div>
            </div>
            <div class="team-row__right" @click.stop>
              <div class="team-row__odds-row">
                <span class="team-row__odds-label">{{ t('outright.col.odds') }}</span>
                <el-input-number
                  v-model="row.editOdds"
                  class="team-row__odds"
                  :min="1.01"
                  :max="9999"
                  :step="0.01"
                  :precision="2"
                  size="small"
                  controls-position="right"
                />
              </div>
            </div>
          </article>
          <button
            v-if="!batchMode"
            type="button"
            class="team-row__trash"
            :title="t('common.delete')"
            :aria-label="t('common.delete')"
            @click.stop="removeSelection(row)"
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path
                fill="currentColor"
                d="M9 3a1 1 0 0 0-.894.553L7.382 6H4a1 1 0 1 0 0 2h1v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h1a1 1 0 1 0 0-2h-3.382l-.724-2.447A1 1 0 0 0 15 3H9zm2 5a1 1 0 0 1 2 0v9a1 1 0 1 1-2 0V8zm4 0a1 1 0 0 1 2 0v9a1 1 0 1 1-2 0V8z"
              />
            </svg>
          </button>
        </div>
      </div>
    </div>
    <p v-else class="outright-odds-panel__empty">{{ t('outright.empty_no_teams') }}</p>

    <el-dialog
      v-model="addVisible"
      :title="t('outright.btn.add_team')"
      width="640px"
      class="add-teams-dialog"
    >
      <div class="add-teams-dialog__toolbar">
        <el-radio-group v-model="addFilter" size="small" @change="onAddFilterChange">
          <el-radio-button value="all">
            {{ t('outright.add.filter_all') }}
          </el-radio-button>
          <el-radio-button value="custom">
            {{ t('outright.add.filter_custom') }}
          </el-radio-button>
        </el-radio-group>
        <el-input
          v-if="addFilter !== 'custom'"
          v-model="addSearch"
          size="small"
          clearable
          class="add-teams-dialog__search"
          :placeholder="t('outright.add.search_ph')"
        />
      </div>

      <div v-if="addFilter === 'custom'" class="add-teams-dialog__custom">
        <p class="add-teams-dialog__custom-hint">{{ t('outright.add.custom_hint') }}</p>
        <el-form label-width="88px" label-position="left" @submit.prevent="onAddConfirm">
          <el-form-item :label="t('outright.add.field_code')" required>
            <el-input
              :model-value="customTeam.teamCode"
              size="small"
              maxlength="32"
              :placeholder="t('outright.add.ph_code')"
              @update:model-value="onCustomCodeInput"
            />
          </el-form-item>
          <el-form-item :label="t('match.field.lang_zh')">
            <el-input v-model="customTeam.teamZh" size="small" :placeholder="t('outright.add.ph_name_zh')" />
          </el-form-item>
          <el-form-item :label="t('match.field.lang_en')">
            <el-input v-model="customTeam.teamEn" size="small" :placeholder="t('outright.add.ph_name_en')" />
          </el-form-item>
          <el-form-item :label="t('outright.add.field_logo')">
            <LogoUrlField
              v-model="customTeam.logoUrl"
              upload-only
              upload-category="teams"
            />
          </el-form-item>
          <el-form-item :label="t('outright.add.default_odds')" required>
            <el-input-number
              v-model="defaultOdds"
              :min="1.01"
              :step="0.05"
              :precision="2"
              size="small"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
      </div>

      <template v-else>
      <div class="add-teams-dialog__actions">
        <el-button size="small" link type="primary" @click="selectAllVisible">
          {{ t('outright.add.select_all') }}
        </el-button>
        <el-button size="small" link @click="clearSelection">
          {{ t('outright.add.clear_selection') }}
        </el-button>
        <span class="add-teams-dialog__count">
          {{ t('outright.add.selected_count', { n: selectedCount }) }}
        </span>
        <label class="add-teams-dialog__odds">
          {{ t('outright.add.default_odds') }}
          <el-input-number
            v-model="defaultOdds"
            :min="1.01"
            :step="0.05"
            :precision="2"
            size="small"
            controls-position="right"
          />
        </label>
      </div>

      <div v-if="visibleAddTeams.length" class="add-teams-grid">
        <button
          v-for="team in visibleAddTeams"
          :key="team.teamCode"
          type="button"
          class="add-team-pick"
          :class="{ 'add-team-pick--selected': selectedCodes.has(team.teamCode) }"
          @click="toggleTeam(team.teamCode)"
        >
          <span
            v-if="selectedCodes.has(team.teamCode)"
            class="add-team-pick__check"
            aria-hidden="true"
          >✓</span>
          <img
            v-if="teamFlagUrl(team)"
            :src="teamFlagUrl(team)"
            :alt="teamDisplayName(team)"
            class="add-team-pick__flag"
          />
          <span class="add-team-pick__name">{{ teamDisplayName(team) }}</span>
          <span class="add-team-pick__code">{{ team.teamCode }}</span>
        </button>
      </div>
      <p v-else class="add-teams-dialog__empty">
        {{ t('outright.add.empty_all') }}
      </p>
      </template>

      <template #footer>
        <el-button @click="addVisible = false">{{ t('common.cancel') }}</el-button>
        <el-button
          type="primary"
          :loading="adding"
          :disabled="addFilter !== 'custom' && selectedCount === 0"
          @click="onAddConfirm"
        >
          {{ t('common.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.outright-odds-panel {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  height: 100%;
  padding: 10px 12px 12px;
  background: #fbfaf7;
}
.outright-odds-panel__head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 10px;
  flex-wrap: wrap;
  flex-shrink: 0;
  margin-bottom: 8px;
}
.outright-odds-panel__head-text {
  flex: 1;
  min-width: 200px;
}
.outright-odds-panel__actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.outright-odds-panel__hint {
  margin: 0;
  font-size: 12px;
  color: #777;
  line-height: 1.5;
}
.outright-odds-panel__workflow-hint {
  margin: 6px 0 0;
  font-size: 12px;
  color: #e6a23c;
  line-height: 1.5;
}
.outright-odds-panel__batch {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  flex-shrink: 0;
  margin-bottom: 10px;
  padding: 8px 10px;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.02);
}
.outright-odds-panel__batch-count {
  font-size: 12px;
  color: #888;
}
.outright-odds-panel__batch-odds {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
  font-size: 12px;
  color: #aaa;
}
.outright-odds-panel__sort {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  margin-bottom: 8px;
}
.outright-odds-panel__sort-label {
  font-size: 12px;
  color: #888;
  white-space: nowrap;
}
.outright-odds-panel__sort-by {
  width: 132px;
}
.outright-odds-panel__sort-dir {
  width: 96px;
}
.outright-odds-panel__empty {
  margin: 0;
  padding: 16px 0;
  font-size: 13px;
  color: #666;
  text-align: center;
}

.team-list-scroll {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding-right: 4px;
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.16) transparent;
}

.team-list-scroll::-webkit-scrollbar {
  width: 6px;
}

.team-list-scroll::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.16);
  border-radius: 3px;
}

.team-list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 6px;
}

@media (min-width: 1440px) {
  .team-list {
    grid-template-columns: repeat(5, minmax(0, 1fr));
  }
}

.team-row-wrap {
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 0;
}

.team-row-wrap--batch {
  cursor: pointer;
}

.team-row {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
  min-width: 0;
  flex: 1;
  padding: 6px 8px 6px 6px;
  background: #ffffff;
  border: 1px solid var(--border);
  border-radius: 8px;
  transition:
    border-color 0.15s ease,
    background 0.15s ease;
}

.team-row-wrap:hover .team-row {
  border-color: #d5cfc3;
  background: var(--accent-hover);
}

.team-row-wrap--batch-selected .team-row {
  border-color: var(--el-color-primary);
  background: rgba(64, 158, 255, 0.08);
}

.team-row__trash {
  flex-shrink: 0;
  width: 28px;
  height: 28px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #666;
  cursor: pointer;
  transition:
    color 0.15s ease,
    background 0.15s ease;
}

.team-row__trash svg {
  width: 16px;
  height: 16px;
}

.team-row__trash:hover {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.12);
}

.team-row__trash:focus-visible {
  outline: 2px solid rgba(245, 108, 108, 0.45);
  outline-offset: 1px;
}

.team-row__check {
  position: absolute;
  top: 6px;
  right: 8px;
  font-size: 12px;
  color: var(--el-color-primary);
}

.team-row__head {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
  flex: 1;
}

.team-row__right {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.team-row__rank {
  flex-shrink: 0;
  width: 16px;
  font-size: 11px;
  font-weight: 600;
  color: #555;
  text-align: center;
}

.team-row__flag {
  flex-shrink: 0;
  width: 28px;
  height: 20px;
  object-fit: cover;
  border-radius: 3px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.35);
}

.team-row__names {
  display: flex;
  flex-direction: column;
  gap: 1px;
  min-width: 0;
  flex: 1;
}

.team-row__name {
  font-size: 12px;
  font-weight: 600;
  color: #e8e8e8;
  line-height: 1.3;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.team-row__meta {
  font-size: 10px;
  color: #666;
  line-height: 1.2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.team-row__odds-row {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
}

.team-row__odds-label {
  font-size: 10px;
  color: #666;
  line-height: 1.2;
  white-space: nowrap;
  text-align: right;
}

.team-row__odds,
.team-row__odds.el-input-number {
  width: 86px;
}

.team-row__odds :deep(.el-input__wrapper) {
  padding-right: 28px !important;
}

.add-teams-dialog__toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.add-teams-dialog__search {
  flex: 1;
  min-width: 160px;
}

.add-teams-dialog__badge {
  margin-left: 4px;
  font-size: 11px;
  opacity: 0.75;
}

.add-teams-dialog__actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid #262626;
}

.add-teams-dialog__count {
  margin-left: auto;
  font-size: 12px;
  color: #888;
}

.add-teams-dialog__odds {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #aaa;
}

.add-teams-dialog__empty {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: #666;
}

.add-teams-dialog__custom {
  margin-top: 4px;
}

.add-teams-dialog__custom-hint {
  margin: 0 0 12px;
  font-size: 12px;
  color: #888;
  line-height: 1.5;
}

.add-teams-dialog__custom :deep(.el-form-item) {
  margin-bottom: 12px;
}

.add-teams-dialog__custom :deep(.el-form-item__label) {
  color: #8e8e93;
}

.add-teams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 8px;
  max-height: 360px;
  overflow-y: auto;
  padding-right: 4px;
}

.add-team-pick {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 10px 8px 8px;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  background: #141414;
  cursor: pointer;
  transition:
    border-color 0.15s ease,
    background 0.15s ease;
}

.add-team-pick:hover {
  border-color: #3d3d3d;
}

.add-team-pick--selected {
  border-color: var(--el-color-primary);
  background: rgba(64, 158, 255, 0.08);
}

.add-team-pick__check {
  position: absolute;
  top: 6px;
  right: 6px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: var(--el-color-primary);
}

.add-team-pick__flag {
  width: 36px;
  height: 24px;
  object-fit: cover;
  border-radius: 3px;
}

.add-team-pick__name {
  font-size: 12px;
  font-weight: 600;
  color: #e0e0e0;
  text-align: center;
  line-height: 1.25;
}

.add-team-pick__code {
  font-size: 9px;
  font-weight: 700;
  letter-spacing: 0.05em;
  color: #555;
}

.outright-odds-panel__hint,
.outright-odds-panel__batch-count,
.outright-odds-panel__sort-label,
.outright-odds-panel__empty,
.team-row__rank,
.team-row__meta,
.team-row__odds-label,
.add-teams-dialog__count,
.add-teams-dialog__odds,
.add-teams-dialog__empty,
.add-teams-dialog__custom-hint,
.add-team-pick__code {
  color: var(--text-muted);
}

.outright-odds-panel__workflow-hint {
  color: var(--warning-text);
}

.outright-odds-panel__batch,
.team-row,
.add-team-pick {
  border-color: var(--border);
  background: #ffffff;
}

.team-row-wrap:hover .team-row,
.add-team-pick:hover {
  border-color: #d5cfc3;
  background: var(--accent-hover);
}

.team-row-wrap--batch-selected .team-row,
.add-team-pick--selected {
  border-color: var(--primary);
  background: var(--accent-subtle);
}

.team-list-scroll {
  scrollbar-color: #d5cfc3 transparent;
}

.team-list-scroll::-webkit-scrollbar-thumb {
  background: #d5cfc3;
}

.team-row__trash {
  color: var(--text-muted);
}

.team-row__trash:hover {
  background: var(--danger-bg);
  color: var(--danger-text);
}

.team-row__flag {
  box-shadow: none;
}

.team-row__name,
.add-team-pick__name {
  color: var(--text);
}

.add-teams-dialog__actions {
  border-bottom-color: var(--border-soft);
}

.add-teams-dialog__custom :deep(.el-form-item__label) {
  color: var(--text-muted);
}

@media (max-width: 960px) {
  .team-list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 560px) {
  .team-list {
    grid-template-columns: 1fr;
  }

  .outright-odds-panel__batch,
  .outright-odds-panel__sort {
    align-items: stretch;
  }
}
</style>
