<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted } from 'vue';
import { teamFlagUrl } from '../../utils/teamFlag';

const props = defineProps<{
  teamCode: string;
  teamName: string;
  odds: string;
  logoUrl?: string | null;
}>();

const emit = defineEmits<{ pick: [] }>();

const flag = computed(
  () => props.logoUrl?.trim() || teamFlagUrl(props.teamCode, props.teamName),
);
const flagFailed = ref(false);
const imgVisible = ref(false);
const cardRef = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;

function onFlagError() {
  flagFailed.value = true;
}

watch(
  () => [props.teamCode, props.teamName, props.logoUrl] as const,
  () => {
    flagFailed.value = false;
  },
);

function formatOdds(odds: string) {
  const n = parseFloat(odds);
  return Number.isFinite(n) ? n.toFixed(2) : odds;
}

onMounted(() => {
  if (!cardRef.value) return;
  observer = new IntersectionObserver(
    (entries) => {
      const entry = entries[0];
      if (entry.isIntersecting) {
        imgVisible.value = true;
        observer?.disconnect();
      }
    },
    { rootMargin: '120px' }
  );
  observer.observe(cardRef.value);
});

onUnmounted(() => {
  observer?.disconnect();
});
</script>

<template>
  <button ref="cardRef" type="button" class="option-card" @click="emit('pick')">
    <img
      v-if="imgVisible && flag && !flagFailed"
      :src="flag"
      alt=""
      class="flag"
      @error="onFlagError"
    />
    <span v-else class="flag-placeholder" aria-hidden="true">⚽</span>
    <span class="name">{{ teamName }}</span>
    <span class="odds">[ {{ formatOdds(odds) }} ]</span>
  </button>
</template>

<style scoped>
.option-card {
  position: relative;
  width: 100%;
  min-width: 0;
  padding: 8px 4px 6px;
  border-radius: 6px;
  background: linear-gradient(180deg, #1a1a1a 0%, #0d0d0d 100%);
  border: 1px solid rgba(140, 140, 140, 0.35);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  text-align: center;
  overflow: hidden;
}

.option-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(100, 100, 100, 0.08) 0%, transparent 50%, rgba(80, 80, 80, 0.05) 100%);
  pointer-events: none;
}

.option-card:active {
  border-color: var(--border-gold-soft);
}

.flag {
  width: 28px;
  height: 19px;
  object-fit: cover;
  border-radius: 2px;
}

.flag-placeholder {
  width: 28px;
  height: 19px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  opacity: 0.55;
}

.name {
  font-size: 11px;
  font-weight: 800;
  color: var(--primary-light);
  line-height: 1.2;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.odds {
  font-size: 11px;
  font-weight: 800;
  color: var(--primary-light);
}
</style>
