<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useMatchFilters } from '../../composables/useMatchFilters';
import { useDesktopParlayMatches } from '../../composables/useDesktopParlayMatches';
import MatchBetCard from '../MatchBetCard.vue';
import GoldSpinner from '../GoldSpinner.vue';
import {
  isAfterLocalTodayMatchWindow as isAfterTodayMatchWindow,
  isInLocalTodayMatchWindow as isInTodayMatchWindow,
} from '@thebet365/shared';
import { ref, watch, nextTick } from 'vue';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { searchQuery, filterState } = useMatchFilters();
const { parlayMatches, parlayLoading, loadParlayMatches } = useDesktopParlayMatches();

const listRef = ref<HTMLElement | null>(null);

onMounted(() => {
  void loadParlayMatches().then(() => {
    scrollToActive();
  });
});

const currentMatchId = computed(() => {
  const id = route.params.id;
  return Array.isArray(id) ? id[0] : id;
});

function matchesSearchKeyword(m: any, keyword: string) {
  if (!keyword) return true;
  const haystack = `${m.homeTeamName} ${m.awayTeamName} ${m.leagueName}`.toLowerCase();
  return haystack.includes(keyword);
}

const filteredMatches = computed(() => {
  const now = new Date();
  const keyword = searchQuery.value.trim().toLowerCase();
  return parlayMatches.value.filter((m) => {
    const isCurrent = String(m.id) === String(currentMatchId.value);

    // 封盘或已结算的不展示，除非是当前正在查看的赛事
    if (!isCurrent && (m.bettingOpen === false || m.matchPhase === 'settled' || m.matchPhase === 'closed_pending')) {
      return false;
    }

    if (!isCurrent && !matchesSearchKeyword(m, keyword)) return false;

    let timeMatch = true;
    if (!isCurrent) {
      if (filterState.value.time === 'today') {
        timeMatch = isInTodayMatchWindow(m.startTime, now);
      } else if (filterState.value.time === 'early') {
        timeMatch = isAfterTodayMatchWindow(m.startTime, now);
      }
    }
    return isCurrent || timeMatch;
  });
});

function goMatch(id: string) {
  router.replace(`/match/${id}`);
}

function scrollToActive() {
  nextTick(() => {
    if (!listRef.value) return;
    const activeEl = listRef.value.querySelector('.active') as HTMLElement;
    if (activeEl) {
      activeEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  });
}

watch(currentMatchId, scrollToActive);
</script>

<template>
  <div class="match-sidebar">
    <div class="search-box">
      <input
        v-model="searchQuery"
        type="text"
        :placeholder="t('nav.search')"
        class="sidebar-search-input"
      />
    </div>

    <div class="sidebar-section">
      <div class="section-hdr">{{ t('bet.filter_time') }}</div>
      <div class="time-filters">
        <button
          type="button"
          class="time-btn"
          :class="{ active: filterState.time === 'all' }"
          @click="filterState.time = 'all'"
        >
          {{ t('bet.time_all') }}
        </button>
        <button
          type="button"
          class="time-btn"
          :class="{ active: filterState.time === 'today' }"
          @click="filterState.time = 'today'"
        >
          {{ t('bet.time_today') }}
        </button>
        <button
          type="button"
          class="time-btn"
          :class="{ active: filterState.time === 'early' }"
          @click="filterState.time = 'early'"
        >
          {{ t('bet.time_early') }}
        </button>
      </div>
    </div>

    <div class="sidebar-section matches-section">
      <div class="section-hdr leagues-hdr">
        <span>{{ t('bet.tab_matches') || '赛事' }}</span>
      </div>
      <div class="matches-list" ref="listRef">
        <div v-if="parlayLoading && !filteredMatches.length" class="sidebar-loading">
          <GoldSpinner :size="24" />
        </div>
        <template v-else>
          <MatchBetCard
            v-for="m in filteredMatches"
            :key="m.id"
            :match="m"
            :no-quick-bet="true"
            :class="{ active: String(m.id) === String(currentMatchId) }"
            @bet="goMatch"
          />
          <div v-if="filteredMatches.length === 0 && !parlayLoading" class="empty-matches">
            {{ t('bet.no_matches') }}
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<style scoped>
.match-sidebar {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 12px 0;
}

.search-box {
  padding: 0 12px 10px;
  border-bottom: 1px solid var(--border);
}

.sidebar-search-input {
  width: 100%;
  background: #0d0d0d !important;
  border: 1px solid var(--border) !important;
  color: var(--text);
  padding: 6px 10px;
  font-size: 11px;
  border-radius: 4px;
}

.sidebar-search-input:focus {
  border-color: var(--border-gold-soft) !important;
  box-shadow: 0 0 0 2px rgba(212, 175, 55, 0.1) !important;
}

.sidebar-section {
  padding: 10px 12px;
  border-bottom: 1px solid var(--border);
}

.section-hdr {
  font-size: 10px;
  font-weight: 800;
  text-transform: uppercase;
  color: var(--text-muted);
  letter-spacing: 0.05em;
  margin-bottom: 8px;
}

.leagues-hdr {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-filters {
  display: flex;
  gap: 4px;
}

.time-btn {
  flex: 1;
  background: #141414;
  border: 1px solid var(--border);
  color: var(--text-muted);
  padding: 5px 2px;
  font-size: 10px;
  font-weight: 700;
  border-radius: 4px;
  text-align: center;
  transition: all 0.2s;
}

.time-btn:hover {
  border-color: var(--border-gold-soft);
  color: var(--text);
}

.time-btn.active {
  background: rgba(212, 175, 55, 0.08);
  border-color: var(--primary);
  color: var(--primary-light);
}

.matches-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.matches-list {
  flex: 1;
  overflow-y: auto;
  margin-right: -4px;
  padding-right: 4px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sidebar-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px 0;
}

.empty-matches {
  padding: 16px 0;
  text-align: center;
  font-size: 11px;
  color: var(--text-muted);
}

/* Compact overrides for MatchBetCard inside sidebar */
.matches-list :deep(.bet-btn),
.matches-list :deep(.team-flag) {
  display: none !important;
}

.matches-list :deep(.team) {
  transform: none !important;
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.matches-list :deep(.team-name) {
  font-size: 12px;
  font-weight: 700;
  color: #ffffff;
  text-align: center;
  padding: 0 4px;
  max-width: 80px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-shadow: none;
  display: block;
}

.matches-list :deep(.center-col) {
  min-width: 60px;
  gap: 2px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.matches-list :deep(.kickoff) {
  font-size: 9px;
  color: var(--text-muted);
  text-shadow: none;
  white-space: nowrap;
}

.matches-list :deep(.vs) {
  font-size: 11px;
  font-weight: 800;
  color: var(--primary-light);
  text-shadow: none;
}

.matches-list :deep(.live-score) {
  font-size: 12px;
  font-weight: 800;
  color: var(--primary-light);
}

.matches-list :deep(.status-tag) {
  font-size: 8px;
  padding: 2px 6px;
  border-radius: 0 4px 0 6px;
}

.matches-list :deep(.match-card) {
  padding: 10px 8px;
  min-height: unset;
  background: #141414;
  border: 1px solid var(--border);
  border-radius: 6px;
  gap: 6px;
}

.matches-list :deep(.match-card:hover) {
  border-color: var(--border-gold-soft);
  background: var(--bg-hover) !important;
}

.matches-list :deep(.match-card.active) {
  border-color: var(--primary) !important;
  background: rgba(212, 175, 55, 0.08) !important;
  box-shadow: 0 0 8px rgba(212, 175, 55, 0.25);
}
</style>
