<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import api from '../api';
import { formatMoney } from '../utils/localeDisplay';
import GoldSpinner from '../components/GoldSpinner.vue';
import { usePullToRefresh } from '../composables/usePullToRefresh';
import StatusWatermark from '../components/StatusWatermark.vue';
import { matchPhaseLabel, matchPhaseVariant, type MatchPhase } from '../utils/matchPhase';
import type { BetHistoryItem } from '../components/BetHistoryCard.vue';

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

const bet = ref<BetHistoryItem | null>(null);
const loading = ref(true);
const notFound = ref(false);

async function loadBet() {
  loading.value = true;
  try {
    const { data } = await api.get(`/player/bets/${route.params.betNo}`);
    if (!data.data) { notFound.value = true; return; }
    bet.value = data.data;
  } catch {
    notFound.value = true;
  } finally {
    loading.value = false;
  }
}

onMounted(loadBet);

const { pullDistance, spinning, progress } = usePullToRefresh({
  onRefresh: loadBet,
});

const pullIndicatorStyle = () => ({
  height: `${pullDistance.value}px`,
  opacity: Math.min(pullDistance.value / 48, 1),
});

const statusKey = computed(() => {
  const s = (bet.value?.status ?? '').toUpperCase();
  if (s === 'WON' || s === 'WIN') return 'won';
  if (s === 'LOST' || s === 'LOSE') return 'lost';
  if (s === 'PUSH' || s === 'VOID' || s === 'CANCELLED') return 'push';
  return 'pending';
});

const statusLabel = computed(() => t(`history.status_${statusKey.value}`));

const placedDateTime = computed(() => {
  if (!bet.value) return '';
  const d = new Date(bet.value.placedAt);
  const date = d.toLocaleDateString(locale.value, { year: 'numeric', month: 'short', day: 'numeric' });
  const time = d.toLocaleTimeString(locale.value, { hour: '2-digit', minute: '2-digit' });
  return `${date}  ${time}`;
});

const returnAmount = computed(() => {
  if (!bet.value) return '';
  if (statusKey.value === 'won') return formatMoney(bet.value.actualReturn, locale.value);
  if (statusKey.value === 'pending') return formatMoney(bet.value.potentialReturn, locale.value);
  if (statusKey.value === 'lost') return formatMoney(-parseFloat(String(bet.value.stake ?? 0)), locale.value);
  return formatMoney(bet.value.actualReturn ?? bet.value.potentialReturn, locale.value);
});

function formatOdds(v: unknown): string {
  const n = parseFloat(String(v));
  return isNaN(n) || n <= 0 ? '-' : n.toFixed(2);
}

const SEL_TRANS: Record<string, Record<string, string>> = {
  '主胜': { 'en-US': 'Home Win', 'ms-MY': 'Rumah Menang' },
  '客胜': { 'en-US': 'Away Win', 'ms-MY': 'Tandang Menang' },
  '和局': { 'en-US': 'Draw', 'ms-MY': 'Seri' },
  '主': { 'en-US': 'Home', 'ms-MY': 'Rumah' },
  '客': { 'en-US': 'Away', 'ms-MY': 'Tandang' },
  '大': { 'en-US': 'Over', 'ms-MY': 'Atas' },
  '小': { 'en-US': 'Under', 'ms-MY': 'Bawah' },
  '单': { 'en-US': 'Odd', 'ms-MY': 'Ganjil' },
  '双': { 'en-US': 'Even', 'ms-MY': 'Genap' },
  '冠军': { 'en-US': 'Winner', 'ms-MY': 'Juara' },
};

function translateSel(name: string): string {
  if (locale.value === 'zh-CN') return name;
  const exact = SEL_TRANS[name];
  if (exact) return exact[locale.value] ?? exact['en-US'] ?? name;
  const sp = name.indexOf(' ');
  if (sp > 0) {
    const head = name.slice(0, sp);
    const m = SEL_TRANS[head];
    if (m) return (m[locale.value] ?? m['en-US'] ?? head) + name.slice(sp);
  }
  return name;
}

function legStatusKey(rs: string | null | undefined) {
  if (!rs) return 'pending';
  const s = rs.toUpperCase();
  if (s === 'WON' || s === 'WIN') return 'won';
  if (s === 'LOST' || s === 'LOSE') return 'lost';
  return 'push';
}

const matchTitle = computed(() => {
  if (!bet.value) return '';
  if (bet.value.isParlay) {
    const n = bet.value.legCount ?? bet.value.legs?.length ?? 0;
    return t('history.parlay_title', { n });
  }
  return bet.value.matchTitle;
});

const myPick = computed(() => {
  if (!bet.value || bet.value.isParlay) return '';
  const raw = bet.value.pickLabel ?? '';
  if (locale.value === 'zh-CN' || !raw) return raw;
  const ci = raw.indexOf(': ');
  if (ci < 0) return raw;
  return raw.slice(0, ci + 2) + translateSel(raw.slice(ci + 2));
});

const matchPhase = computed(
  (): MatchPhase | null => bet.value?.matchPhase ?? null,
);

const matchPhaseText = computed(() => matchPhaseLabel(t, matchPhase.value));
</script>

<template>
  <div class="detail-page">
    <div
      class="pull-indicator"
      :style="pullIndicatorStyle()"
    >
      <GoldSpinner v-if="spinning" :size="28" :progress="progress" :active="spinning" />
    </div>

    <!-- back bar -->
    <div class="top-bar">
      <button class="back-btn" @click="router.back()">‹ {{ t('history.back') }}</button>
    </div>

    <div v-if="loading" class="state">
      <GoldSpinner :size="36" />
    </div>
    <div v-else-if="notFound || !bet" class="state">{{ t('history.not_found') }}</div>

    <template v-else>
      <!-- status hero -->
      <div class="hero" :class="statusKey">
        <span class="hero-status">{{ statusLabel }}</span>
        <span class="hero-return">{{ returnAmount }}</span>
        <span class="hero-return-label">
          {{ statusKey === 'pending' ? t('history.est_return') : t('history.return') }}
        </span>
      </div>

      <!-- match / parlay title -->
      <section class="section">
        <div class="section-head">
          <span class="league-tag">
            {{ bet.isParlay ? t('history.parlay_league') : (bet.leagueName || t('history.league_default')) }}
          </span>
          <span class="placed-time">{{ placedDateTime }}</span>
        </div>
        <div class="match-name">{{ matchTitle }}</div>

        <!-- single bet: score comparison -->
        <div v-if="!bet.isParlay" class="score-block" :class="{ 'score-block--phase': matchPhase && matchPhase !== 'open' }">
          <StatusWatermark
            v-if="matchPhase && matchPhase !== 'open'"
            :label="matchPhaseText"
            :variant="matchPhaseVariant(matchPhase)"
            size="md"
          />
          <!-- my pick row -->
          <div class="row-label-val">
            <span class="row-label">{{ t('history.my_pick') }}</span>
            <span class="row-val pick">{{ myPick }}</span>
          </div>
          <!-- scores -->
          <div v-if="bet.matchScore?.ft || bet.matchScore?.ht" class="score-chips">
            <div v-if="bet.matchScore.ft" class="score-item">
              <span class="score-period">{{ t('history.ft') }}</span>
              <span class="score-value">{{ bet.matchScore.ft }}</span>
            </div>
            <div v-if="bet.matchScore.ht" class="score-item">
              <span class="score-period">{{ t('history.ht') }}</span>
              <span class="score-value muted">{{ bet.matchScore.ht }}</span>
            </div>
          </div>
          <div v-else-if="statusKey === 'pending'" class="no-score">{{ t('history.awaiting_result') }}</div>
        </div>
      </section>

      <!-- parlay legs -->
      <section v-if="bet.isParlay && bet.legs?.length" class="section">
        <div class="section-title">{{ t('history.legs') }}</div>
        <div class="legs-list">
          <div v-for="(leg, i) in bet.legs" :key="i" class="leg-row" :class="legStatusKey(leg.resultStatus)">
            <div class="leg-left">
              <span class="leg-num" :class="legStatusKey(leg.resultStatus)">{{ i + 1 }}</span>
              <div class="leg-body">
                <span class="leg-match">{{ leg.matchTitle }}</span>
                <span class="leg-pick-line">
                  {{ leg.marketLabel }}: {{ translateSel(leg.selectionName) }}
                </span>
                <div v-if="leg.score?.ft || leg.score?.ht" class="leg-scores">
                  <span v-if="leg.score.ft">{{ t('history.ft') }} {{ leg.score.ft }}</span>
                  <span v-if="leg.score.ht" class="muted-score">{{ t('history.ht') }} {{ leg.score.ht }}</span>
                </div>
              </div>
            </div>
            <div class="leg-right">
              <span class="leg-odds-val">{{ formatOdds(leg.odds) }}</span>
              <span v-if="leg.resultStatus" class="leg-result-badge" :class="legStatusKey(leg.resultStatus)">
                {{ t(`history.status_${legStatusKey(leg.resultStatus)}`) }}
              </span>
            </div>
          </div>
        </div>
      </section>

      <!-- bet summary -->
      <section class="section">
        <div class="section-title">{{ t('history.summary') }}</div>
        <div class="summary-rows">
          <div class="sum-row">
            <span>{{ t('history.stake') }}</span>
            <span>{{ formatMoney(bet.stake, locale) }}</span>
          </div>
          <div v-if="bet.totalOdds" class="sum-row">
            <span>{{ t('history.odds') }}</span>
            <span class="odds-val">{{ formatOdds(bet.totalOdds) }}</span>
          </div>
          <div class="sum-row">
            <span>{{ statusKey === 'pending' ? t('history.est_return') : t('history.return') }}</span>
            <span :class="{ 'amt-won': statusKey === 'won', 'amt-pending': statusKey === 'pending', 'amt-lost': statusKey === 'lost' }">
              {{ returnAmount }}
            </span>
          </div>
          <div class="sum-row muted">
            <span>{{ t('history.bet_no') }}</span>
            <span class="bet-no-val">{{ bet.betNo }}</span>
          </div>
        </div>
      </section>
    </template>
  </div>
</template>

<style scoped>
.detail-page {
  padding-bottom: 32px;
}

.pull-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transition: height 0.15s ease;
}

.top-bar {
  margin-bottom: 4px;
}

.back-btn {
  background: none;
  border: none;
  color: var(--primary);
  font-size: 15px;
  font-weight: 700;
  padding: 4px 0 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 2px;
}

.state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-muted);
  font-size: 14px;
  font-weight: 600;
}

/* ─ hero ── */
.hero {
  border-radius: 12px;
  padding: 20px 20px 18px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  margin-bottom: 12px;
  text-align: center;
}

.hero.won    { background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.25); }
.hero.lost   { background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.25); }
.hero.pending { background: rgba(255, 179, 0, 0.1); border: 1px solid rgba(255, 179, 0, 0.25); }
.hero.push   { background: var(--bg-card); border: 1px solid var(--border); }

.hero-status {
  font-size: 11px;
  font-weight: 800;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  opacity: 0.85;
}
.hero.won    .hero-status  { color: var(--success); }
.hero.lost   .hero-status  { color: var(--danger); }
.hero.pending .hero-status { color: var(--warning); }
.hero.push   .hero-status  { color: var(--text-muted); }

.hero-return {
  font-size: 36px;
  font-weight: 900;
  letter-spacing: -0.01em;
  line-height: 1.1;
}
.hero.won    .hero-return  { color: var(--success); }
.hero.lost   .hero-return  { color: var(--danger); }
.hero.pending .hero-return { color: var(--warning); }
.hero.push   .hero-return  { color: var(--text-muted); }

.hero-return-label {
  font-size: 10.5px;
  color: var(--text-muted);
  font-weight: 600;
  letter-spacing: 0.04em;
}

/* ── sections ── */
.section {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 14px 16px;
  margin-bottom: 10px;
  box-shadow: var(--shadow);
}

.section-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.league-tag {
  font-size: 11px;
  color: var(--text-muted);
  font-weight: 700;
}

.placed-time {
  font-size: 11px;
  color: var(--text-muted);
  font-weight: 600;
}

.match-name {
  font-size: 17px;
  font-weight: 900;
  color: var(--text);
  line-height: 1.3;
  margin-bottom: 10px;
}

/* score block */
.score-block {
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.score-block--phase {
  padding: 8px 0 4px;
}

.row-label-val {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.row-label {
  font-size: 11px;
  color: var(--text-muted);
  font-weight: 600;
}

.row-val {
  font-size: 13px;
  font-weight: 700;
  color: var(--text);
}

.row-val.pick {
  color: var(--primary);
}

.score-chips {
  display: flex;
  gap: 8px;
}

.score-item {
  display: flex;
  align-items: center;
  gap: 5px;
  background: var(--bg-body);
  border: 1px solid var(--border);
  border-radius: 7px;
  padding: 5px 10px;
}

.score-period {
  font-size: 10px;
  color: var(--text-muted);
  font-weight: 700;
  letter-spacing: 0.05em;
  text-transform: uppercase;
}

.score-value {
  font-size: 16px;
  font-weight: 900;
  color: var(--text);
}

.score-value.muted {
  color: var(--text-muted);
  font-size: 13px;
}

.no-score {
  font-size: 11.5px;
  color: var(--text-muted);
  font-style: italic;
}

/* section title */
.section-title {
  font-size: 10.5px;
  color: var(--text-muted);
  font-weight: 800;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  margin-bottom: 10px;
}

/* parlay legs */
.legs-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.leg-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 10px;
  background: var(--bg-body);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 10px 12px;
}

.leg-row.won  { border-color: rgba(16, 185, 129, 0.3); }
.leg-row.lost { border-color: rgba(239, 68, 68, 0.3); }

.leg-left {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.leg-num {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: var(--secondary);
  color: var(--text-muted);
  font-size: 10px;
  font-weight: 800;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 1px;
}

.leg-num.won  { background: rgba(16, 185, 129, 0.15); color: var(--success); }
.leg-num.lost { background: rgba(239, 68, 68, 0.15); color: var(--danger); }

.leg-body {
  display: flex;
  flex-direction: column;
  gap: 3px;
  min-width: 0;
}

.leg-match {
  font-size: 12.5px;
  font-weight: 800;
  color: var(--text);
}

.leg-pick-line {
  font-size: 11.5px;
  color: var(--text-muted);
  font-weight: 600;
}

.leg-scores {
  display: flex;
  gap: 8px;
  margin-top: 2px;
}

.leg-scores span {
  font-size: 11px;
  font-weight: 700;
  color: var(--text);
}

.leg-scores .muted-score {
  color: var(--text-muted);
}

.leg-right {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.leg-odds-val {
  font-size: 15px;
  font-weight: 900;
  color: var(--primary);
}

.leg-result-badge {
  font-size: 9px;
  font-weight: 800;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  padding: 2px 6px;
  border-radius: 10px;
}

.leg-result-badge.won   { color: var(--success); background: rgba(16, 185, 129, 0.12); }
.leg-result-badge.lost  { color: var(--danger); background: rgba(239, 68, 68, 0.12); }
.leg-result-badge.push  { color: var(--text-muted); background: var(--secondary); }
.leg-result-badge.pending { color: var(--text-muted); background: var(--bg-body); }

/* summary */
.summary-rows {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.sum-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--border);
  font-size: 13px;
  color: var(--text);
  font-weight: 600;
}

.sum-row:last-child {
  border-bottom: none;
}

.sum-row.muted {
  color: var(--text-muted);
  font-size: 11px;
}

.odds-val {
  color: var(--warning);
  font-weight: 800;
}

.amt-won {
  color: var(--success);
  font-weight: 900;
  font-size: 15px;
}

.amt-pending {
  color: var(--warning);
  font-weight: 900;
}

.amt-lost {
  color: var(--danger);
  font-weight: 900;
  font-size: 15px;
}

.bet-no-val {
  font-family: monospace;
  letter-spacing: 0.04em;
  color: var(--text-secondary);
}
</style>
