<script setup>
const props = defineProps({
  modelValue: Boolean,
  countries: { type: Array, default: () => [] },
  currentCountryCode: { type: String, default: '' }
})

const emit = defineEmits(['update:modelValue', 'select'])

const showModal = ref(props.modelValue || false)
const search = ref('')
const searchInputRef = ref(null)

watch(() => props.modelValue, (val) => {
  showModal.value = val
  if (val) {
    search.value = ''
    nextTick(() => searchInputRef.value?.focus())
  }
})

const closeModal = () => {
  showModal.value = false
  emit('update:modelValue', false)
}

const filteredCountries = computed(() => {
  if (!props.countries?.length) return []
  const q = search.value.toLowerCase().trim()
  if (!q) return props.countries
  return props.countries.filter(c => {
    const code = (c.CountryCode || '').toLowerCase()
    const name = (c.Name || c.identifier || '').toLowerCase()
    return code.includes(q) || name.includes(q)
  })
})

const selectCountry = (country) => {
  emit('select', {
    id: country.id,
    CountryCode: country.CountryCode,
    Name: country.Name || country.identifier || ''
  })
  closeModal()
}

onMounted(() => {
  const handleKeyDown = (e) => {
    if (e.key === 'Escape' && showModal.value) {
      closeModal()
    }
  }
  window.addEventListener('keydown', handleKeyDown)
  onUnmounted(() => window.removeEventListener('keydown', handleKeyDown))
})
</script>

<template>
  <div class="modal" :class="{ active: showModal }" :style="{ display: showModal ? 'block' : 'none' }">
    <div class="modalDialog modalCenter" @click.self="closeModal">
      <div class="modalContent country-picker-content">
        <div class="modalHeader country-picker-header">
          <h3 class="modalTitle">Select Country</h3>
          <div class="cursor-pointer" @click="closeModal">
            <span class="tf-icon ti ti-x ti-sm"></span>
          </div>
        </div>

        <div class="modalBody country-picker-body">
          <div class="country-search-wrap">
            <i class="ti ti-search country-search-icon"></i>
            <input
              ref="searchInputRef"
              v-model="search"
              type="text"
              class="input country-search-input"
              placeholder="Search by name or code..."
            />
          </div>

          <div class="country-list">
            <div
              v-for="country in filteredCountries"
              :key="country.id"
              class="country-item"
              :class="{ 'country-item--active': country.CountryCode === currentCountryCode }"
              @click="selectCountry(country)"
            >
              <img
                :src="`/flags/${country.CountryCode}.svg`"
                :alt="country.CountryCode"
                class="country-item-flag"
              />
              <span class="country-item-code">{{ country.CountryCode }}</span>
              <span class="country-item-name">{{ country.Name || country.identifier }}</span>
            </div>
            <div v-if="filteredCountries.length === 0" class="country-empty">
              No countries found
            </div>
          </div>
        </div>

        <div class="modalFooter">
          <div></div>
          <button type="button" class="button" @click="closeModal">Close</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.country-picker-content {
  max-width: 420px;
  width: 100%;
  border-radius: 12px;
  overflow: hidden;
}

.country-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.country-picker-body {
  padding: 0 !important;
  display: flex;
  flex-direction: column;
  max-height: 60vh;
}

.country-search-wrap {
  position: relative;
  padding: 12px;
  border-bottom: 1px solid var(--theme-border, #e2e5ea);
}

.country-search-icon {
  position: absolute;
  left: 22px;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
  font-size: 14px;
  pointer-events: none;
}

.country-search-input {
  padding-left: 32px !important;
  font-size: 0.9rem;
}

.country-list {
  overflow-y: auto;
  max-height: 50vh;
  padding: 4px 0;
}

.country-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 14px;
  cursor: pointer;
  transition: background 0.15s ease;
  border-left: 3px solid transparent;
}

.country-item:hover {
  background: var(--theme-bg-secondary, #f5f7fa);
  border-left-color: #3273dc;
}

.country-item--active {
  background: #eef3ff;
  border-left-color: #3273dc;
  font-weight: 600;
}

.country-item-flag {
  width: 28px;
  height: auto;
  flex-shrink: 0;
}

.country-item-code {
  font-weight: 600;
  font-size: 0.85rem;
  min-width: 28px;
  color: var(--theme-text-primary, #374151);
}

.country-item-name {
  font-size: 0.85rem;
  color: var(--theme-text-primary, #555);
}

.country-empty {
  padding: 20px;
  text-align: center;
  color: #9ca3af;
  font-size: 0.85rem;
}

/* Dark mode */
.dark .country-picker-content {
  background: var(--theme-modal-bg, #1e293b);
}

.dark .country-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.dark .country-item--active {
  background: rgba(50, 115, 220, 0.15);
}
</style>
