<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useOutrightEvents } from '../../composables/useOutrightEvents';
import type { OutrightEvent, OutrightSelection } from '../../components/outright/OutrightEventSection.vue';
import OutrightOptionCard from '../../components/outright/OutrightOptionCard.vue';
import OutrightBetModal, { type OutrightPick } from '../../components/outright/OutrightBetModal.vue';
import { useAuthStore } from '../../stores/auth';
import GoldSpinner from '../../components/GoldSpinner.vue';
import saishiImg from '../../assets/images/generated/saishi-gold-trophy-v1.webp';
import outrightDetailBg from '../../assets/images/generated/pc-outright-detail-bg-v1.webp';
import { useDesktopBetLocate, scrollToBetSelection } from '../../composables/useDesktopBetLocate';

const matchCardBg = `url(${outrightDetailBg})`;
const ODDS_POLL_MS = 15000;

const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const auth = useAuthStore();
const { loading, loadError, events, load } = useOutrightEvents();
const { pendingLocate, clearLocate } = useDesktopBetLocate();

const modalOpen = ref(false);
const activePick = ref<OutrightPick | null>(null);
let pollTimer: ReturnType<typeof setInterval> | null = null;

const event = computed<OutrightEvent | null>(() =>
  events.value.find((e) => e.id === String(route.params.id)) ?? null,
);

const headTitle = computed(() => {
  if (!event.value) return '';
  const raw = event.value.title.replace(/^\*+/, '').trim();
  return raw || event.value.leagueName || t('bet.tab_outright');
});

const teamCount = computed(() =>
  event.value ? (event.value.selectionCount ?? event.value.selections.length) : 0,
);

const isSettled = computed(
  () => event.value?.bettingOpen === false || event.value?.status === 'SETTLED',
);

function goBack() {
  router.push({ path: '/bet', query: { tab: 'outright' } });
}

function openBet(sel: OutrightSelection) {
  if (!event.value || isSettled.value) return;
  if (!auth.token) {
    auth.showLoginPrompt(route.fullPath);
    return;
  }
  activePick.value = {
    selectionId: sel.id,
    oddsVersion: sel.oddsVersion,
    teamCode: sel.teamCode,
    teamName: sel.teamName,
    odds: sel.odds,
    eventTitle: event.value.title,
  };
  modalOpen.value = true;
}

function closeModal() {
  modalOpen.value = false;
  activePick.value = null;
}

function startPolling() {
  stopPolling();
  pollTimer = setInterval(() => {
    void load({ silent: true });
  }, ODDS_POLL_MS);
}

function stopPolling() {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
}

watch(
  () => event.value?.id,
  (id) => {
    if (id) startPolling();
    else stopPolling();
  },
);

watch(
  [pendingLocate, () => event.value?.id, loading],
  async ([target, eventId, isLoading]) => {
    if (!target || isLoading || !eventId) return;
    if (String(eventId) !== String(target.matchId)) return;
    const found = await scrollToBetSelection(target.selectionId);
    if (found) clearLocate();
  },
  { flush: 'post' },
);

onMounted(() => {
  if (event.value) startPolling();
});

onUnmounted(stopPolling);
</script>

<template>
  <div class="desktop-outright-detail">
    <div class="detail-breadcrumbs">
      <button type="button" class="back-btn" @click="goBack">← {{ t('bet.back') }}</button>
      <span class="sep">/</span>
      <span class="curr">{{ t('bet.tab_outright') }}</span>
    </div>

    <div class="detail-main">
    <div v-if="loading && !event" class="loading-state">
      <GoldSpinner :active="true" />
    </div>

    <template v-else-if="event">
      <header class="event-hero" :class="{ settled: isSettled }">
        <div class="hero-text">
          <div class="title-row">
            <h1 class="hero-title">{{ headTitle }}</h1>
            <span v-if="isSettled" class="settled-tag">{{ t('bet.outright_settled') }}</span>
          </div>
          <p v-if="event.leagueName && event.leagueName !== headTitle" class="hero-league">
            {{ event.leagueName }}
          </p>
          <p class="hero-meta">{{ t('bet.outright_teams_count', { n: teamCount }) }}</p>
          <p v-if="isSettled" class="hero-hint">{{ t('bet.outright_settled_hint') }}</p>
        </div>
        <img :src="saishiImg" alt="" class="hero-icon" />
      </header>

      <div class="teams-grid">
        <OutrightOptionCard
          v-for="sel in event.selections"
          :key="sel.id"
          :team-code="sel.teamCode"
          :team-name="sel.teamName"
          :logo-url="sel.logoUrl"
          :odds="sel.odds"
          :selection-id="sel.id"
          :disabled="isSettled"
          :is-winner="Boolean(sel.isWinner)"
          @pick="openBet(sel)"
        />
      </div>
    </template>

    <div v-else class="empty-state">
      <p>{{ loadError || t('bet.no_outright') }}</p>
      <button type="button" class="back-link" @click="goBack">{{ t('bet.back') }}</button>
    </div>
    </div>

    <OutrightBetModal :open="modalOpen" :pick="activePick" @close="closeModal" />
  </div>
</template>

<style scoped>
.desktop-outright-detail {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.detail-breadcrumbs {
  position: sticky;
  top: 0;
  z-index: 30;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  font-size: 12px;
  color: var(--text-muted);
  background: #0c0c0c;
  border-bottom: 1px solid var(--border);
  flex-shrink: 0;
}

.detail-main {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px 16px 14px;
}

.detail-breadcrumbs .sep {
  flex-shrink: 0;
}

.detail-breadcrumbs .curr {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--text);
  font-weight: 700;
}

.back-btn {
  flex-shrink: 0;
  background: transparent;
  color: var(--primary-light);
  font-weight: 700;
  border: none;
  padding: 0;
  cursor: pointer;
}

.back-btn:hover {
  text-decoration: underline;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 240px;
}

.event-hero {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 14px 16px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: rgba(18, 18, 18, 0.98);
  overflow: hidden;
}

.event-hero::before {
  content: '';
  position: absolute;
  inset: 0;
  background: v-bind(matchCardBg) center / cover no-repeat;
  opacity: 0.36;
  pointer-events: none;
}

.hero-text {
  position: relative;
  z-index: 1;
  min-width: 0;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.hero-title {
  margin: 0;
  font-size: 15px;
  font-weight: 800;
  color: var(--primary-light);
  line-height: 1.35;
}

.settled-tag {
  font-size: 10px;
  font-weight: 800;
  color: #c9a227;
  border: 1px solid rgba(201, 162, 39, 0.45);
  border-radius: 999px;
  padding: 1px 7px;
}

.hero-league {
  margin: 4px 0 0;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-muted);
}

.hero-meta {
  margin: 4px 0 0;
  font-size: 11px;
  font-weight: 600;
  color: #666;
}

.hero-hint {
  margin: 8px 0 0;
  font-size: 11px;
  font-weight: 600;
  color: #c9a227;
  line-height: 1.45;
}

.hero-icon {
  position: relative;
  z-index: 1;
  flex-shrink: 0;
  height: 48px;
  width: auto;
  max-width: 44px;
  object-fit: contain;
}

.teams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 48px 16px;
  color: var(--text-muted);
  font-size: 13px;
}

.back-link {
  margin-top: 12px;
  background: transparent;
  color: var(--primary-light);
  font-weight: 700;
}
</style>
