<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, parseAmount } 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 isSettled = computed(() => statusKey.value !== 'pending');

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(-parseAmount(bet.value.stake), locale.value);
  return formatMoney(bet.value.actualReturn ?? bet.value.potentialReturn, locale.value);
});

const profitAmount = computed(() => {
  if (!bet.value || statusKey.value !== 'won') return '';
  const profit = parseAmount(bet.value.actualReturn) - parseAmount(bet.value.stake);
  return `+${formatMoney(profit, locale.value)}`;
});

const heroAmount = computed(() => {
  if (statusKey.value === 'won') return profitAmount.value;
  return returnAmount.value;
});

const heroTitle = computed(() => {
  if (statusKey.value === 'won') return t('history.profit');
  if (statusKey.value === 'pending') return t('history.est_return');
  return statusLabel.value;
});

const formulaText = computed(() => {
  if (!bet.value || !oddsText.value || statusKey.value === 'pending') return '';
  return t('history.stake_to_return', {
    stake: stakeAmount.value,
    odds: oddsText.value,
    amount: returnAmount.value,
  });
});

const stakeAmount = computed(() =>
  bet.value ? formatMoney(bet.value.stake, locale.value) : '',
);

const oddsText = computed(() => {
  const o = bet.value?.totalOdds;
  if (o == null || o === '' || o === 0) return '';
  const n = parseFloat(String(o));
  return Number.isFinite(n) ? n.toFixed(2) : String(o);
});

const betTypeLabel = computed(() => {
  if (!bet.value) return '';
  if (bet.value.isParlay) return t('bet.parlay');
  return bet.value.betType || '';
});

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 pickMarket = computed(() => {
  if (!bet.value || bet.value.isParlay) return '';
  const raw = bet.value.pickLabel ?? '';
  const ci = raw.indexOf(': ');
  return ci >= 0 ? raw.slice(0, ci) : raw;
});

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

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

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

const showPhaseWatermark = computed(
  () => !isSettled.value && matchPhase.value && matchPhase.value !== 'open',
);
</script>

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

    <div class="top-bar">
      <button type="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>

    <article v-else class="receipt">
      <!-- result strip -->
      <div class="receipt-result" :class="statusKey">
        <div class="result-icon" :class="statusKey">
          <svg v-if="statusKey === 'won'" viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="11" fill="none" stroke="currentColor" stroke-width="1.5" />
            <path d="M7 12.5l3 3 7-7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
          </svg>
          <svg v-else-if="statusKey === 'lost'" viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="11" fill="none" stroke="currentColor" stroke-width="1.5" />
            <path d="M8 8l8 8M16 8l-8 8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          </svg>
          <svg v-else-if="statusKey === 'pending'" viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="11" fill="none" stroke="currentColor" stroke-width="1.5" />
            <path d="M12 7v5l3 2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          </svg>
          <svg v-else viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="11" fill="none" stroke="currentColor" stroke-width="1.5" />
            <path d="M8 12h8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          </svg>
        </div>
        <div class="result-text">
          <span class="result-label">{{ heroTitle }}</span>
          <span class="result-amount">{{ heroAmount }}</span>
          <span v-if="statusKey === 'won'" class="result-sub">
            {{ t('history.return_incl_stake', { amount: returnAmount }) }}
          </span>
          <span v-else-if="formulaText && statusKey !== 'pending'" class="result-sub">{{ formulaText }}</span>
          <span v-else-if="statusKey === 'pending' && oddsText" class="result-sub">
            {{ stakeAmount }} × {{ oddsText }}
          </span>
        </div>
      </div>

      <div class="receipt-perforation" aria-hidden="true" />

      <!-- body -->
      <div class="receipt-body">
        <div class="receipt-meta">
          <div class="meta-tags">
            <span v-if="betTypeLabel" class="meta-tag">{{ betTypeLabel }}</span>
            <span v-if="oddsText" class="meta-tag dim">@{{ oddsText }}</span>
            <span v-if="bet.isCashbacked" class="meta-tag cashback">{{ t('history.cashbacked') }}</span>
          </div>
          <span class="meta-time">{{ placedDateTime }}</span>
        </div>

        <h2 class="match-title">{{ matchTitle }}</h2>

        <!-- single pick -->
        <div v-if="!bet.isParlay" class="pick-block">
          <StatusWatermark
            v-if="showPhaseWatermark"
            :label="matchPhaseText"
            :variant="matchPhaseVariant(matchPhase!)"
            size="md"
          />
          <span class="pick-market">{{ pickMarket }}</span>
          <div class="pick-line">
            <span class="pick-selection">{{ pickSelection }}</span>
            <span v-if="oddsText" class="pick-odds">@{{ oddsText }}</span>
          </div>
          <div v-if="bet.matchScore?.ft || bet.matchScore?.ht" class="score-row">
            <span v-if="bet.matchScore.ft" class="score-pill">
              <em>{{ t('history.ft') }}</em>{{ bet.matchScore.ft }}
            </span>
            <span v-if="bet.matchScore.ht" class="score-pill dim">
              <em>{{ t('history.ht') }}</em>{{ bet.matchScore.ht }}
            </span>
          </div>
          <p v-else-if="statusKey === 'pending'" class="awaiting">{{ t('history.awaiting_result') }}</p>
        </div>

        <!-- parlay legs -->
        <div v-if="bet.isParlay && bet.legs?.length" class="legs-list">
          <div
            v-for="(leg, i) in bet.legs"
            :key="i"
            class="leg-item"
            :class="legStatusKey(leg.resultStatus)"
          >
            <div class="leg-status-dot" :class="legStatusKey(leg.resultStatus)">
              <svg v-if="legStatusKey(leg.resultStatus) === 'won'" viewBox="0 0 12 12"><path d="M2 6l3 3 5-5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" /></svg>
              <svg v-else-if="legStatusKey(leg.resultStatus) === 'lost'" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
              <span v-else>{{ i + 1 }}</span>
            </div>
            <div class="leg-content">
              <div class="leg-head">
                <span class="leg-match">{{ leg.matchTitle }}</span>
                <span class="leg-odds">@{{ formatOdds(leg.odds) }}</span>
              </div>
              <span class="leg-pick">{{ leg.marketLabel }} · {{ translateSel(leg.selectionName) }}</span>
              <div v-if="leg.score?.ft || leg.score?.ht" class="score-row compact">
                <span v-if="leg.score.ft" class="score-pill sm"><em>{{ t('history.ft') }}</em>{{ leg.score.ft }}</span>
                <span v-if="leg.score.ht" class="score-pill sm dim"><em>{{ t('history.ht') }}</em>{{ leg.score.ht }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="receipt-perforation" aria-hidden="true" />

      <!-- footer -->
      <div class="receipt-foot">
        <div class="foot-row">
          <span>{{ t('history.stake') }}</span>
          <span>{{ stakeAmount }}</span>
        </div>
        <div v-if="bet.totalOdds" class="foot-row">
          <span>{{ t('history.odds') }}</span>
          <span class="gold">{{ formatOdds(bet.totalOdds) }}</span>
        </div>
        <div class="foot-row id">
          <span>{{ t('history.bet_no') }}</span>
          <span class="mono">{{ bet.betNo }}</span>
        </div>
      </div>
    </article>
  </div>
</template>

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

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

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

.back-btn {
  background: none;
  border: none;
  color: var(--primary-light);
  font-size: 15px;
  font-weight: 700;
  padding: 4px 0 8px;
  cursor: pointer;
}

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

/* ── receipt ticket ── */
.receipt {
  position: relative;
  border-radius: var(--radius);
  background: rgba(18, 18, 18, 0.96);
  border: 1px solid var(--border);
  box-shadow: var(--shadow);
  overflow: hidden;
}

/* result strip */
.receipt-result {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 18px 18px;
}

.receipt-result.won {
  background: linear-gradient(135deg, rgba(52, 199, 89, 0.1) 0%, transparent 70%);
}

.receipt-result.lost {
  background: linear-gradient(135deg, rgba(255, 69, 58, 0.08) 0%, transparent 70%);
}

.receipt-result.pending {
  background: linear-gradient(135deg, rgba(212, 175, 55, 0.08) 0%, transparent 70%);
}

.result-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
}

.result-icon svg {
  width: 100%;
  height: 100%;
}

.result-icon.won { color: #34c759; }
.result-icon.lost { color: var(--danger); }
.result-icon.pending { color: var(--primary-light); }
.result-icon.push { color: var(--text-muted); }

.result-text {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.result-label {
  font-size: 12px;
  font-weight: 700;
  color: var(--text-muted);
  letter-spacing: 0.04em;
  text-transform: uppercase;
}

.result-amount {
  font-size: 32px;
  font-weight: 900;
  letter-spacing: -0.02em;
  line-height: 1.1;
}

.receipt-result.won .result-amount { color: #34c759; }
.receipt-result.lost .result-amount { color: var(--danger); }
.receipt-result.pending .result-amount { color: var(--primary-light); }
.receipt-result.push .result-amount { color: var(--text-muted); }

.result-sub {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-muted);
  margin-top: 2px;
}

/* perforated divider */
.receipt-perforation {
  height: 1px;
  margin: 0 14px;
  background: repeating-linear-gradient(
    90deg,
    transparent 0,
    transparent 4px,
    rgba(255, 255, 255, 0.08) 4px,
    rgba(255, 255, 255, 0.08) 8px
  );
  position: relative;
}

.receipt-perforation::before,
.receipt-perforation::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: var(--bg-body, #000);
  transform: translateY(-50%);
}

.receipt-perforation::before { left: -20px; }
.receipt-perforation::after { right: -20px; }

/* body */
.receipt-body {
  padding: 16px 18px;
}

.receipt-meta {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 10px;
  margin-bottom: 10px;
}

.meta-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.meta-tag {
  font-size: 10px;
  font-weight: 800;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  padding: 3px 8px;
  border-radius: 4px;
  color: var(--primary-light);
  background: rgba(212, 175, 55, 0.1);
  border: 1px solid var(--border-gold-soft);
}

.meta-tag.dim {
  color: var(--text-muted);
  background: rgba(255, 255, 255, 0.04);
  border-color: var(--border);
}

.meta-tag.cashback {
  color: #f0b90b;
  background: rgba(240, 185, 11, 0.1);
  border-color: rgba(240, 185, 11, 0.25);
}

.meta-time {
  flex-shrink: 0;
  font-size: 11px;
  color: #555;
  font-weight: 600;
}

.match-title {
  font-size: 16px;
  font-weight: 800;
  color: var(--text);
  line-height: 1.35;
  margin-bottom: 14px;
}

/* pick block */
.pick-block {
  position: relative;
  overflow: hidden;
  padding: 14px;
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: var(--radius-sm);
}

.pick-market {
  display: block;
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  letter-spacing: 0.04em;
  margin-bottom: 6px;
}

.pick-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.pick-selection {
  font-size: 16px;
  font-weight: 800;
  color: var(--primary-light);
}

.pick-odds {
  font-size: 14px;
  font-weight: 900;
  color: var(--text-muted);
}

.score-row {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.score-row.compact {
  margin-top: 8px;
}

.score-pill {
  font-size: 13px;
  font-weight: 800;
  color: var(--text);
  padding: 5px 10px;
  background: rgba(255, 255, 255, 0.04);
  border-radius: 6px;
}

.score-pill em {
  font-style: normal;
  font-size: 9px;
  font-weight: 800;
  color: var(--text-muted);
  letter-spacing: 0.06em;
  text-transform: uppercase;
  margin-right: 5px;
}

.score-pill.dim { color: var(--text-muted); }
.score-pill.sm { font-size: 11px; padding: 3px 8px; }

.awaiting {
  margin-top: 10px;
  font-size: 12px;
  color: var(--text-muted);
  font-style: italic;
}

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

.leg-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.leg-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.leg-status-dot {
  flex-shrink: 0;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: 900;
  background: rgba(255, 255, 255, 0.05);
  border: 1.5px solid var(--border);
  color: var(--text-muted);
  margin-top: 2px;
}

.leg-status-dot svg {
  width: 12px;
  height: 12px;
}

.leg-status-dot.won {
  background: rgba(52, 199, 89, 0.12);
  border-color: rgba(52, 199, 89, 0.45);
  color: #34c759;
}

.leg-status-dot.lost {
  background: rgba(255, 69, 58, 0.1);
  border-color: rgba(255, 69, 58, 0.35);
  color: var(--danger);
}

.leg-content {
  flex: 1;
  min-width: 0;
}

.leg-head {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 4px;
}

.leg-match {
  font-size: 13px;
  font-weight: 800;
  color: var(--text);
  line-height: 1.35;
}

.leg-odds {
  flex-shrink: 0;
  font-size: 13px;
  font-weight: 900;
  color: var(--text-muted);
}

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

/* footer */
.receipt-foot {
  padding: 14px 18px 16px;
}

.foot-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 7px 0;
  font-size: 13px;
  color: var(--text-muted);
  font-weight: 600;
}

.foot-row span:last-child {
  color: var(--text);
  font-weight: 700;
}

.foot-row .gold {
  color: var(--primary-light);
  font-weight: 800;
}

.foot-row.id {
  margin-top: 4px;
  padding-top: 10px;
  border-top: 1px solid rgba(255, 255, 255, 0.05);
  font-size: 11px;
}

.foot-row.id span:last-child {
  color: #555;
  font-weight: 600;
}

.mono {
  font-family: ui-monospace, monospace;
  letter-spacing: 0.02em;
}
</style>
