<script setup lang="ts">
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import PlayerAvatarPicker from './PlayerAvatarPicker.vue';

const props = defineProps<{
  open: boolean;
  modelValue: string | null;
}>();

const emit = defineEmits<{
  close: [];
  confirm: [value: string | null];
}>();

const { t } = useI18n();
const draft = ref<string | null>(null);

watch(
  () => props.open,
  (visible) => {
    if (visible) draft.value = props.modelValue;
  },
);

function close() {
  emit('close');
}

function confirm() {
  emit('confirm', draft.value);
}
</script>

<template>
  <Teleport to="body">
    <div v-if="open" class="overlay" @click.self="close">
      <div class="modal" role="dialog" aria-modal="true" :aria-label="t('profile.avatar')">
        <button type="button" class="close-x" :aria-label="t('bet.cancel')" @click="close">✕</button>
        <h3 class="title">{{ t('profile.avatar') }}</h3>
        <PlayerAvatarPicker v-model="draft" />
        <div class="actions">
          <button type="button" class="btn-cancel" @click="close">{{ t('bet.cancel') }}</button>
          <button type="button" class="btn-confirm btn-gold-outline" @click="confirm">
            {{ t('profile.avatar_confirm') }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.overlay {
  position: fixed;
  inset: 0;
  z-index: 210;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  backdrop-filter: blur(4px);
}

.modal {
  position: relative;
  width: 100%;
  max-width: 360px;
  max-height: 85vh;
  overflow-y: auto;
  background: var(--bg-card-elevated);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 16px 14px 14px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.close-x {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  border: 1px solid var(--border);
  background: var(--bg-elevated);
  color: var(--text-muted);
  font-size: 12px;
  line-height: 1;
  padding: 0;
}

.title {
  margin: 0 28px 12px 0;
  font-size: 15px;
  font-weight: 800;
  color: var(--primary);
}

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

.btn-cancel,
.btn-confirm {
  flex: 1;
  min-height: 40px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 800;
}

.btn-cancel {
  border: 1px solid var(--border);
  background: var(--bg-card);
  color: var(--text-muted);
}

.btn-confirm {
  border: none;
  background: var(--gradient-primary);
  color: #FFFFFF;
}
</style>
