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

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { parlayMatches, loadParlayMatches } = useDesktopParlayMatches();
const { searchQuery, filterState, toggleLeague, clearFilters } = useMatchFilters();
const { events: outrightEvents, load: loadOutrightEvents } = useOutrightEvents();

const isOutrightMode = computed(() => {
  return route.query.tab === 'outright';
});

watch(
  isOutrightMode,
  (outright) => {
    if (outright) {
      void loadOutrightEvents({ silent: outrightEvents.value.length > 0 });
    } else {
      void loadParlayMatches();
    }
  },
  { immediate: true },
);

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

const availableLeagues = computed(() => {
  const map = new Map<string, { id: string; name: string; count: number }>();
  const keyword = searchQuery.value.trim().toLowerCase();

  if (isOutrightMode.value) {
    for (const e of outrightEvents.value) {
      if (keyword) {
        const haystack = `${e.title} ${e.leagueName || ''}`.toLowerCase();
        if (!haystack.includes(keyword)) continue;
      }

      const id = e.leagueId ?? e.leagueName ?? 'unknown';
      const existing = map.get(id);
      if (existing) {
        existing.count += 1;
      } else {
        map.set(id, {
          id,
          name: normalizeLeagueName(e.leagueName || e.title),
          count: 1,
        });
      }
    }
  } else {
    const now = new Date();
    for (const m of parlayMatches.value) {
      if (keyword) {
        const haystack = `${m.homeTeamName} ${m.awayTeamName} ${m.leagueName}`.toLowerCase();
        if (!haystack.includes(keyword)) continue;
      }

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

      if (filterState.value.status === 'open' && m.matchPhase !== 'open' && m.matchPhase !== undefined) continue;
      if (filterState.value.status === 'settled' && m.matchPhase !== 'settled') continue;

      const id = m.leagueId ?? m.leagueName;
      const existing = map.get(id);
      if (existing) {
        existing.count += 1;
      } else {
        map.set(id, {
          id,
          name: normalizeLeagueName(m.leagueName),
          count: 1,
        });
      }
    }
  }

  return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
});

const isSelected = (leagueId: string) => {
  return filterState.value.leagueIds.length === 0 || filterState.value.leagueIds.includes(leagueId);
};

const handleLeagueClick = (leagueId: string) => {
  toggleLeague(leagueId);
};
</script>

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

    <div v-if="!isOutrightMode" 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 leagues-section">
      <div class="section-hdr leagues-hdr">
        <span>{{ t('bet.filter_league') }}</span>
        <button
          v-if="filterState.leagueIds.length > 0"
          type="button"
          class="clear-btn"
          @click="clearFilters"
        >
          {{ t('common.clear') }}
        </button>
      </div>
      <div class="leagues-list">
        <div
          v-for="lg in availableLeagues"
          :key="lg.id"
          class="league-item"
          :class="{ active: isSelected(lg.id) }"
          @click="handleLeagueClick(lg.id)"
        >
          <div class="checkbox" :class="{ checked: isSelected(lg.id) }"></div>
          <span class="league-name" :title="lg.name">{{ lg.name }}</span>
          <span class="league-count">{{ lg.count }}</span>
        </div>
        <div v-if="availableLeagues.length === 0" class="empty-leagues">
          {{ isOutrightMode ? t('bet.no_outright') : t('bet.no_matches') }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.league-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-body) !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(244, 162, 97, 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;
}

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

.time-btn {
  flex: 1;
  background: var(--bg-elevated);
  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(244, 162, 97, 0.08);
  border-color: var(--primary);
  color: var(--primary-light);
}

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

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

.clear-btn {
  background: transparent;
  color: var(--primary-light);
  font-size: 10px;
  font-weight: 700;
  padding: 0;
  text-transform: none;
}

.leagues-list {
  flex: 1;
  overflow-y: auto;
  margin-right: -4px;
  padding-right: 4px;
}

.league-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 8px;
  margin-bottom: 2px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.15s;
}

.league-item:hover {
  background: var(--bg-hover);
}

.league-item.active {
  background: rgba(244, 162, 97, 0.04);
}

.checkbox {
  width: 12px;
  height: 12px;
  border: 1px solid var(--border);
  border-radius: 2px;
  position: relative;
  flex-shrink: 0;
  background: var(--bg-body);
}

.checkbox.checked {
  border-color: var(--primary);
  background: var(--primary);
}

.checkbox.checked::after {
  content: '';
  position: absolute;
  top: 1px;
  left: 4px;
  width: 3px;
  height: 6px;
  border: solid var(--bg-body);
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.league-name {
  flex: 1;
  font-size: 11px;
  font-weight: 600;
  color: #ddd;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.league-item.active .league-name {
  color: var(--primary-light);
  font-weight: 700;
}

.league-count {
  font-size: 9px;
  color: var(--text-muted);
  font-weight: 700;
  background: rgba(22, 45, 54, 0.4); border: 1px solid var(--border);
  padding: 1px 5px;
  border-radius: 8px;
}

.empty-leagues {
  padding: 16px 0;
  text-align: center;
  font-size: 11px;
  color: var(--text-muted);
}
</style>
