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

const props = withDefaults(
  defineProps<{
    teamCode?: string;
    teamName?: string;
    logoUrl?: string | null;
    size?: 'sm' | 'md' | 'lg';
  }>(),
  { size: 'md' },
);

function isCustomLogo(url?: string | null) {
  const value = url?.trim();
  return Boolean(value && !value.includes('flagcdn.com'));
}

const useCustomLogo = computed(() => isCustomLogo(props.logoUrl));
const src = computed(() =>
  teamFlagUrl(props.teamCode, props.teamName, props.logoUrl),
);
const failed = ref(false);

function onError() {
  failed.value = true;
}

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

<template>
  <img
    v-if="src && !failed"
    :src="src"
    alt=""
    class="team-emblem"
    :class="[`team-emblem--${size}`, { 'team-emblem--logo': useCustomLogo }]"
    loading="lazy"
    @error="onError"
  />
  <span
    v-else
    class="team-emblem team-emblem--placeholder"
    :class="`team-emblem--${size}`"
    aria-hidden="true"
  >⚽</span>
</template>

<style scoped>
.team-emblem {
  flex-shrink: 0;
  display: block;
}

/* 队徽（非国旗）：圆角 + 投影 */
.team-emblem--logo {
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35);
}

.team-emblem--sm {
  width: 24px;
  height: 24px;
}

.team-emblem--md {
  width: 36px;
  height: 36px;
}

.team-emblem--lg {
  width: 52px;
  height: 52px;
}

/* 国旗：横向比例 + 铺满 */
.team-emblem:not(.team-emblem--logo) {
  object-fit: cover;
  border-radius: 3px;
  background: transparent;
}

.team-emblem--sm:not(.team-emblem--logo) {
  width: 28px;
  height: 20px;
}

.team-emblem--md:not(.team-emblem--logo) {
  width: 40px;
  height: 28px;
}

.team-emblem--lg:not(.team-emblem--logo) {
  width: 54px;
  height: 36px;
}

/* 队徽：正方形容器 + 完整显示 */
.team-emblem--logo {
  object-fit: contain;
  background: transparent;
}

.team-emblem--placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  color: var(--text-muted);
  opacity: 0.55;
  box-shadow: none;
}

.team-emblem--sm.team-emblem--placeholder {
  font-size: 12px;
}

.team-emblem--md.team-emblem--placeholder {
  font-size: 16px;
}

.team-emblem--lg.team-emblem--placeholder {
  font-size: 22px;
}
</style>
