<script setup lang="ts">
import { computed, onMounted, ref, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useMatchFilters } from '../../composables/useMatchFilters';
import { useOutrightEvents } from '../../composables/useOutrightEvents';
import GoldSpinner from '../GoldSpinner.vue';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { searchQuery } = useMatchFilters();
const { events: outrightEvents, loading, load: loadOutrightEvents } = useOutrightEvents();

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

onMounted(() => {
  void loadOutrightEvents({ silent: outrightEvents.value.length > 0 }).then(() => {
    scrollToActive();
  });
});

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

function normalizeLeagueName(name: string): string {
  return name
    .replace(/\.unit$/i, '')
    .replace(/[-_]+/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();
}

const filteredEvents = computed(() => {
  const keyword = searchQuery.value.trim().toLowerCase();
  return outrightEvents.value.filter((e) => {
    // If it's the active event, always show it
    const isCurrent = String(e.id) === String(currentOutrightId.value);
    if (isCurrent) return true;

    if (keyword) {
      const haystack = `${e.title} ${e.leagueName || ''}`.toLowerCase();
      if (!haystack.includes(keyword)) return false;
    }
    return true;
  });
});

function goOutright(id: string) {
  router.replace(`/outright/${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(currentOutrightId, scrollToActive);
</script>

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

    <div class="sidebar-section outrights-section">
      <div class="section-hdr">
        <span>{{ t('bet.tab_outright') || '优胜冠军' }}</span>
      </div>
      <div class="outrights-list" ref="listRef">
        <div v-if="loading && !filteredEvents.length" class="sidebar-loading">
          <GoldSpinner :size="24" />
        </div>
        <template v-else>
          <div
            v-for="e in filteredEvents"
            :key="e.id"
            class="outright-card"
            :class="{ active: String(e.id) === String(currentOutrightId) }"
            @click="goOutright(e.id)"
          >
            <div class="card-header">
              <span class="league-tag" :title="e.leagueName">{{ normalizeLeagueName(e.leagueName || e.title) }}</span>
            </div>
            <div class="event-title" :title="e.title">{{ e.title }}</div>
            <div class="card-footer">
              <span class="selections-badge">
                {{ e.selections?.length || 0 }} {{ t('bet.selections') || '项' }}
              </span>
            </div>
          </div>
          <div v-if="filteredEvents.length === 0 && !loading" class="empty-outrights">
            {{ t('bet.no_outright') }}
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<style scoped>
.outright-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: var(--bg-card) !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-active) !important;
  box-shadow: 0 0 0 2px rgba(0, 102, 204, 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;
}

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

.outrights-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-outrights {
  padding: 16px 0;
  text-align: center;
  font-size: 11px;
  color: var(--text-muted);
}

.outright-card {
  padding: 12px 10px;
  background: var(--bg-body);
  border: 1px solid var(--border);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  gap: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.outright-card:hover {
  border-color: var(--border-active);
  background: var(--bg-hover) !important;
}

.outright-card.active {
  border-color: var(--primary) !important;
  background: rgba(0, 102, 204, 0.08) !important;
  box-shadow: 0 0 8px rgba(0, 102, 204, 0.25);
}

.card-header {
  display: flex;
  align-items: center;
}

.league-tag {
  font-size: 9px;
  color: var(--primary-light);
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

.event-title {
  font-size: 12px;
  font-weight: 700;
  color: var(--text);
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.outright-card.active .event-title {
  color: var(--primary-light);
}

.card-footer {
  display: flex;
  justify-content: flex-start;
}

.selections-badge {
  font-size: 9px;
  color: var(--text-muted);
  font-weight: 700;
  background: var(--bg-card);
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.03);
}

.outright-card.active .selections-badge {
  background: rgba(0, 102, 204, 0.15);
  color: var(--primary-light);
  border-color: rgba(0, 102, 204, 0.3);
}
</style>
