<script setup lang="ts">
import { ref, computed, getCurrentInstance, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { teamFlagUrl } from '../utils/teamFlag';
import { matchPhaseLabel, type MatchPhase } from '../utils/matchPhase';
import { formatLocalMatchDateTime } from '@thebet365/shared';
import { useBetSlipStore } from '../stores/betSlip';
import { useDesktopBetPopover } from '../composables/useDesktopBetPopover';
import { resolveSelectionLabel } from '../utils/selectionLabel';
import MarketSelectionsPanel from './match-detail/MarketSelectionsPanel.vue';

const props = defineProps<{
  match: {
    id: string;
    homeTeamName: string;
    awayTeamName: string;
    homeTeamCode?: string;
    awayTeamCode?: string;
    homeTeamLogoUrl?: string | null;
    awayTeamLogoUrl?: string | null;
    startTime: string;
    bettingOpen?: boolean;
    matchPhase?: MatchPhase;
    score?: {
      htHome: number | null;
      htAway: number | null;
      ftHome: number | null;
      ftAway: number | null;
      homeCorners?: number | null;
      awayCorners?: number | null;
      homeYellowCards?: number | null;
      awayYellowCards?: number | null;
      homeRedCards?: number | null;
      awayRedCards?: number | null;
      homeCards?: number | null;
      awayCards?: number | null;
    } | null;
    markets?: any[];
  };
  noQuickBet?: boolean;
}>();

const emit = defineEmits<{ bet: [id: string] }>();

const { t, locale } = useI18n();
const router = useRouter();
const slip = useBetSlipStore();
const { openAt, visible: popoverVisible, pendingItem, cancelClose, scheduleClose, isActiveForCard } =
  useDesktopBetPopover();

const cardRootId = `bet-card-${props.match.id}-${getCurrentInstance()?.uid ?? 0}`;
const isCardEngaged = computed(() => isActiveForCard(cardRootId));

function formatKickoff(startTime: string) {
  return formatLocalMatchDateTime(startTime, locale.value, {
    variant: 'compact',
    todayLabel: t('bet.today'),
  });
}

const kickoffText = computed(() => formatKickoff(props.match.startTime));

const homeFlagUrl = computed(() =>
  teamFlagUrl(props.match.homeTeamCode, props.match.homeTeamName, props.match.homeTeamLogoUrl),
);
const awayFlagUrl = computed(() =>
  teamFlagUrl(props.match.awayTeamCode, props.match.awayTeamName, props.match.awayTeamLogoUrl),
);

const homeIsLogo = computed(() => Boolean(props.match.homeTeamLogoUrl?.trim()));
const awayIsLogo = computed(() => Boolean(props.match.awayTeamLogoUrl?.trim()));

const bettingOpen = computed(() => props.match.bettingOpen !== false);

const phase = computed(
  () => props.match.matchPhase ?? (bettingOpen.value ? 'open' : 'closed_pending'),
);

const phaseLabel = computed(() => matchPhaseLabel(t, phase.value));

const liveScoreText = computed(() => {
  const s = props.match.score;
  if (!s || s.ftHome == null || s.ftAway == null) return '';
  return `${s.ftHome} - ${s.ftAway}`;
});

function getHoveredSide() {
  if (!popoverVisible.value || !pendingItem.value) return '';
  if (!isActiveForCard(cardRootId)) return '';
  if (String(pendingItem.value.matchId) !== String(props.match.id)) return '';

  const selId = pendingItem.value.selectionId;
  for (const market of props.match.markets ?? []) {
    const sel = market.selections?.find((s: { id: string }) => s.id === selId);
    if (!sel) continue;
    const code = (sel.selectionCode || '').toUpperCase();
    if (code === 'HOME') return 'home';
    if (code === 'AWAY') return 'away';
    if (code === 'DRAW') return 'draw';
    if (code === 'OVER') return 'home';
    if (code === 'UNDER') return 'away';
    if (code === 'ODD' || code === 'EVEN') return 'draw';
    const selIndex = market.selections?.findIndex((s: { id: string }) => s.id === selId) ?? -1;
    if (selIndex === -1) continue;
    if (market.marketType === 'FT_1X2') {
      if (selIndex === 0) return 'home';
      if (selIndex === 1) return 'draw';
      if (selIndex === 2) return 'away';
    } else {
      if (selIndex === 0) return 'home';
      if (selIndex === 1) return 'away';
    }
  }
  return '';
}

function pickQuickBetMarkets(markets: any[] | undefined) {
  const supported = ['FT_1X2', 'FT_HANDICAP', 'FT_OVER_UNDER'];
  const byType = new Map<string, any>();
  for (const m of markets ?? []) {
    if (!supported.includes(m.marketType)) continue;
    if (!Array.isArray(m.selections) || m.selections.length === 0) continue;
    if (!byType.has(m.marketType)) byType.set(m.marketType, m);
  }
  return supported.map((type) => byType.get(type)).filter(Boolean);
}

const activeMarketType = ref('');

watch(
  () => props.match.id,
  () => {
    activeMarketType.value = '';
  },
);

const currentMarketType = computed(() => {
  const available = pickQuickBetMarkets(props.match.markets);
  if (activeMarketType.value && available.some((m) => m.marketType === activeMarketType.value)) {
    return activeMarketType.value;
  }
  if (available.some((m) => m.marketType === 'FT_1X2')) return 'FT_1X2';
  return available[0]?.marketType ?? '';
});

function isSelected(id: string) {
  return slip.isInSlip(id);
}

function getAvailableMarketsForMatch(match: typeof props.match) {
  return pickQuickBetMarkets(match.markets);
}

function getMarketTabLabel(type: string) {
  const raw = (() => {
    if (type === 'FT_1X2') return t('bet.market_ft_1x2');
    if (type === 'FT_HANDICAP') return t('bet.market_ft_handicap');
    if (type === 'FT_OVER_UNDER') return t('bet.market_ft_ou');
    return type;
  })();
  return raw.replace(/全场\s*|FT\s*|Penuh\s*/gi, '').trim();
}

function getSelLabel(sel: { selectionCode?: string; selectionName: string }, _marketType: string, lineValue?: string | number | null) {
  return resolveSelectionLabel(t, sel.selectionCode || '', sel.selectionName || '', { lineValue });
}

function isMarketLocked(match: any, market?: { status?: string; allowSingle?: boolean; allowParlay?: boolean }) {
  if (!market) return true;
  if (match.bettingOpen === false) return true;
  const status = (market.status ?? 'OPEN').toUpperCase();
  if (status !== 'OPEN') return true;
  return market.allowSingle !== true && market.allowParlay !== true;
}

function getActiveMarket() {
  const type = currentMarketType.value;
  if (!type) return undefined;
  return pickQuickBetMarkets(props.match.markets).find((m) => m.marketType === type);
}

function handleOddsClick(match: any, market: any, selId: string, event?: MouseEvent) {
  if (isMarketLocked(match, market)) return;
  const sel = market.selections?.find((s: { id: string }) => s.id === selId);
  if (!sel || !event) return;

  openAt(event, {
    selectionId: sel.id,
    oddsVersion: String(sel.oddsVersion),
    matchId: match.id,
    matchName: `${match.homeTeamName} vs ${match.awayTeamName}`,
    marketId: market.id,
    marketName: market.marketDisplayName?.trim() || market.marketType || '',
    selectionName: getSelLabel(sel, market.marketType, market.lineValue),
    odds: parseFloat(sel.odds),
    marketType: market.marketType,
    lineValue:
      market.lineValue != null && market.lineValue !== ''
        ? parseFloat(String(market.lineValue))
        : null,
    allowSingle: market.allowSingle,
    allowParlay: market.allowParlay,
  });
}

function goMatchDetail() {
  router.push(`/match/${props.match.id}`);
}
</script>

<template>
  <article
    class="match-card"
    :data-bet-card-root="cardRootId"
    :class="{
      'match-card--phase': phase !== 'open',
      'no-quick-bet': noQuickBet,
      'match-card--engaged': isCardEngaged,
    }"
    @click="emit('bet', match.id)"
    @mouseenter="cancelClose"
    @mouseleave="scheduleClose()"
  >
    <span v-if="phase === 'open'" class="status-tag status-tag--open">{{ t('bet.status_open') }}</span>
    <span v-else-if="phase === 'settled'" class="status-tag status-tag--settled">{{ phaseLabel }}</span>
    <span v-else class="status-tag status-tag--pending">{{ phaseLabel }}</span>

    <div class="teams-row" :class="getHoveredSide()">
      <div class="team">
        <span class="team-name">{{ match.homeTeamName }}</span>
        <img
          v-if="homeFlagUrl"
          :src="homeFlagUrl"
          class="team-flag"
          :class="{ 'flag-logo': homeIsLogo }"
          alt=""
          loading="lazy"
          decoding="async"
        />
      </div>

      <div class="center-col">
        <span class="kickoff">{{ kickoffText }}</span>
        <span v-if="phase !== 'open' && liveScoreText" class="live-score">{{ liveScoreText }}</span>
        <span v-else class="vs">VS</span>
      </div>

      <div class="team">
        <span class="team-name">{{ match.awayTeamName }}</span>
        <img
          v-if="awayFlagUrl"
          :src="awayFlagUrl"
          class="team-flag"
          :class="{ 'flag-logo': awayIsLogo }"
          alt=""
          loading="lazy"
          decoding="async"
        />
      </div>
    </div>

    <button
      type="button"
      class="bet-btn"
      :class="bettingOpen ? 'btn-gold-outline' : 'bet-btn--view'"
      @click.stop="emit('bet', match.id)"
    >
      {{ bettingOpen ? t('bet.place_bet_short') : t('bet.view_match') }}
    </button>

    <div v-if="!noQuickBet" class="card-quick-bet" @click.stop>
      <div v-if="getAvailableMarketsForMatch(match).length" class="quick-bet-tabs">
        <button
          v-for="m in getAvailableMarketsForMatch(match)"
          :key="m.marketType"
          type="button"
          class="quick-bet-tab-btn"
          :class="{ active: currentMarketType === m.marketType }"
          @click="activeMarketType = m.marketType"
        >
          {{ getMarketTabLabel(m.marketType) }}
        </button>
        <span class="quick-bet-all-link" @click="goMatchDetail">{{ t('bet.all') }} →</span>
      </div>

      <div class="quick-bet-odds">
        <template v-if="getActiveMarket()">
          <MarketSelectionsPanel
            desktop-card
            compact
            :locked="isMarketLocked(match, getActiveMarket())"
            :line-value="getActiveMarket()?.lineValue"
            :selections="(getActiveMarket()?.selections || []).map((s: any) => ({
              ...s,
              odds: String(s.odds),
            }))"
            :is-selected="isSelected"
            @pick="(selId, ev) => handleOddsClick(match, getActiveMarket()!, selId, ev)"
          />
        </template>
        <div v-else class="quick-bet-no-odds">
          {{ t('bet.no_market_odds') }}
        </div>
      </div>
    </div>
  </article>
</template>

<style scoped>
.match-card {
  position: relative;
  background: #ffffff;
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 10px 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  min-width: 0;
  min-height: 130px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
  transition: border-color 0.2s, box-shadow 0.2s, transform 0.15s;
}

.match-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(0, 61, 107, 0.03) 0%, transparent 50%, rgba(0, 91, 159, 0.03) 100%);
  pointer-events: none;
  z-index: 0;
}

.teams-row {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  width: 100%;
  gap: 4px;
  transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1), padding 0.3s ease;
}

.team {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  min-width: 0;
  transform: translateY(8px);
  transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.team-name {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 800;
  color: var(--text);
  line-height: 1.2;
  word-break: break-word;
  text-align: center;
  padding: 0 4px;
  align-self: stretch;
  transition: font-size 0.25s ease;
}

.match-card--phase .team-name {
  color: #4b5563;
}

.team-flag {
  width: 56px;
  height: 38px;
  object-fit: cover;
  border-radius: 3px;
  display: block;
  transition: transform 0.25s ease, opacity 0.2s ease, height 0.25s ease, width 0.25s ease;
}

.team-flag.flag-logo {
  width: 38px;
  height: 38px;
  object-fit: contain;
}

.center-col {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  min-width: 48px;
}

.kickoff {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-muted);
  line-height: 1.15;
  white-space: normal;
  text-align: center;
  max-width: 80px;
  overflow-wrap: anywhere;
  transition: opacity 0.2s ease, height 0.2s ease, margin 0.2s ease;
}

.live-score,
.vs {
  font-size: 18px;
  font-weight: 900;
  color: var(--primary);
  line-height: 1;
}

.status-tag {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 3;
  font-size: 10px;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 0 6px 0 8px;
  line-height: 1.3;
  white-space: nowrap;
}

.status-tag--open {
  background: #fef3c7;
  color: #92400e;
  border-bottom: 1px solid #fde68a;
  border-left: 1px solid #fde68a;
}

.status-tag--settled {
  background: #e8edf2;
  color: #4b5563;
  border-bottom: 1px solid #d1d5db;
  border-left: 1px solid #d1d5db;
}

.status-tag--pending {
  background: #fef3c7;
  color: #d97706;
  border-bottom: 1px solid #fde68a;
  border-left: 1px solid #fde68a;
}

.bet-btn {
  position: relative;
  z-index: 2;
  width: auto;
  min-width: 72px;
  padding: 4px 20px;
  border-radius: 6px;
  font-size: 12px;
  line-height: 1.2;
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.bet-btn--view {
  background: var(--bg-body);
  border: 1px solid var(--border);
  color: var(--text-muted);
}

.card-quick-bet {
  position: absolute;
  left: 8px;
  right: 8px;
  bottom: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
  opacity: 0;
  pointer-events: none;
  transform: translateY(12px);
  transition: opacity 0.2s ease, transform 0.2s cubic-bezier(0.25, 0.8, 0.25, 1);
  z-index: 5;
}

@media (hover: hover) {
  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) {
    border-color: var(--border-active);
    box-shadow: 0 4px 12px rgba(0, 61, 107, 0.1);
    transform: translateY(-1px);
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .teams-row {
    transform: translateY(0);
    padding: 0 28px;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .team {
    transform: translateY(0);
    gap: 3px;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .team-flag {
    width: 40px;
    height: 28px;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .team-flag.flag-logo {
    width: 28px;
    height: 28px;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .team-name {
    font-size: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .kickoff {
    opacity: 0;
    height: 0;
    margin: 0;
    overflow: hidden;
    pointer-events: none;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .vs,
  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .live-score {
    font-size: 16px;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .bet-btn {
    opacity: 0;
    pointer-events: none;
  }

  .match-card:not(.no-quick-bet):is(:hover, .match-card--engaged) .card-quick-bet {
    opacity: 1;
    pointer-events: auto;
    transform: translateY(0);
  }

  .match-card.no-quick-bet:hover {
    border-color: var(--border-active);
    box-shadow: 0 4px 12px rgba(0, 61, 107, 0.1);
  }
}

.quick-bet-tabs {
  display: flex;
  align-items: center;
  border-bottom: 1px solid var(--border);
  padding-bottom: 4px;
  margin-bottom: 2px;
}

.quick-bet-tab-btn {
  padding: 2px 6px;
  font-size: 9px;
  font-weight: 700;
  color: var(--text-muted);
  background: transparent;
  border: none;
  cursor: pointer;
  border-radius: 3px;
  transition: all 0.15s;
}

.quick-bet-tab-btn:hover,
.quick-bet-tab-btn.active {
  color: var(--primary-light);
  background: rgba(0, 102, 204, 0.08);
}

.quick-bet-all-link {
  margin-left: auto;
  font-size: 9px;
  font-weight: 700;
  color: var(--primary-light);
  cursor: pointer;
  padding: 2px 4px;
}

.quick-bet-odds {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.quick-bet-odds :deep(.odds-btn) {
  min-height: 26px !important;
  padding: 1px 4px !important;
}

.quick-bet-odds :deep(.odds) {
  font-size: 11px !important;
}

.quick-bet-odds :deep(.label) {
  font-size: 8px !important;
}

.quick-bet-no-odds {
  font-size: 10px;
  color: var(--text-muted);
}

.teams-row .team {
  transition: transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s ease, filter 0.3s ease;
}

.teams-row.home .team:first-child {
  transform: scale(1.08);
  filter: brightness(1.08) saturate(1.15);
  z-index: 2;
}

.teams-row.home .team:last-child {
  opacity: 0.35 !important;
  transform: scale(0.94);
  filter: grayscale(0.6) brightness(0.7);
}

.teams-row.away .team:last-child {
  transform: scale(1.08);
  filter: brightness(1.08) saturate(1.15);
  z-index: 2;
}

.teams-row.away .team:first-child {
  opacity: 0.35 !important;
  transform: scale(0.94);
  filter: grayscale(0.6) brightness(0.7);
}

.teams-row.draw .team {
  transform: scale(1.05);
  filter: brightness(1.08) saturate(1.1);
}
</style>
