<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
  PHONE_COUNTRIES,
  getPhoneCountryLabel,
  searchPhoneCountries,
  findPhoneCountryByIso,
  defaultPhoneIsoForLocale,
} from '@thebet365/shared';

const model = defineModel<string>({ required: true });
const { t, locale } = useI18n();

const open = ref(false);
const query = ref('');
const root = ref<HTMLElement | null>(null);

const options = computed(() =>
  searchPhoneCountries(query.value, locale.value).map((country) => ({
    iso: country.iso,
    dial: country.dial,
    code: `+${country.dial}`,
    name: getPhoneCountryLabel(country, locale.value),
    flag: country.flag,
  })),
);

const current = computed(() => {
  const matched = findPhoneCountryByIso(model.value)
    ?? PHONE_COUNTRIES.find((c) => c.dial === model.value);
  if (matched) {
    return {
      iso: matched.iso,
      code: `+${matched.dial}`,
      name: getPhoneCountryLabel(matched, locale.value),
    };
  }
  return { iso: '--', code: '+--', name: '' };
});

function pick(iso: string) {
  model.value = iso;
  open.value = false;
  query.value = '';
}

function toggle() {
  open.value = !open.value;
  if (open.value) query.value = '';
}

function onOutsideClick(e: Event) {
  if (!root.value?.contains(e.target as Node)) {
    open.value = false;
    query.value = '';
  }
}

watch(open, (isOpen) => {
  if (!isOpen) query.value = '';
});

onMounted(() => {
  if (!findPhoneCountryByIso(model.value)) {
    model.value = defaultPhoneIsoForLocale(locale.value);
  }
  document.addEventListener('click', onOutsideClick);
  document.addEventListener('touchend', onOutsideClick);
});
onUnmounted(() => {
  document.removeEventListener('click', onOutsideClick);
  document.removeEventListener('touchend', onOutsideClick);
});
</script>

<template>
  <div ref="root" class="country-switch" :class="{ open }">
    <button
      type="button"
      class="country-trigger"
      :aria-expanded="open"
      aria-haspopup="listbox"
      :title="current.name"
      @click.stop="toggle"
    >
      <span class="country-iso">{{ current.iso }}</span>
      <span class="country-sep">·</span>
      <span class="country-dial">{{ current.code }}</span>
    </button>
    <div v-show="open" class="country-panel">
      <input
        v-model="query"
        class="country-search"
        type="search"
        :placeholder="t('auth.country_search')"
        autocomplete="off"
        @click.stop
      />
      <ul class="country-menu" role="listbox">
        <li
          v-for="opt in options"
          :key="opt.iso"
          role="option"
          :aria-selected="model === opt.iso"
          class="country-option"
          :class="{ active: model === opt.iso }"
          @click="pick(opt.iso)"
        >
          <span class="country-iso">{{ opt.iso }}</span>
          <span class="country-dial">{{ opt.code }}</span>
          <span class="country-name">{{ opt.name }}</span>
        </li>
        <li v-if="options.length === 0" class="country-empty">{{ t('auth.country_not_found') }}</li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.country-switch {
  position: relative;
  flex: 0 0 auto;
}

.country-trigger {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  height: 36px;
  padding: 0 8px;
  border: 1px solid #E5E7EB;
  border-radius: 6px;
  background: #FFFFFF;
  color: #1A1A2E;
  font-family: inherit;
  font-size: 12px;
  line-height: 1;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.country-trigger:active {
  background: #F5F7FA;
}

.country-iso {
  font-weight: 700;
  letter-spacing: 0.03em;
}

.country-sep {
  color: #6B7280;
  font-size: 10px;
}

.country-dial {
  color: #6B7280;
  font-weight: 600;
}

.country-panel {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  z-index: 60;
  width: min(260px, calc(100vw - 48px));
  padding: 4px;
  background: #FFFFFF;
  border: 1px solid #E5E7EB;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.country-search {
  width: 100%;
  margin-bottom: 4px;
  padding: 6px 8px;
  border: 1px solid #E5E7EB;
  border-radius: 4px;
  background: #F5F7FA;
  color: #1A1A2E;
  font-size: 12px;
  font-family: inherit;
}

.country-search::placeholder {
  color: #6B7280;
}

.country-search:focus {
  outline: none;
  border-color: #003D6B;
}

.country-menu {
  max-height: 180px;
  margin: 0;
  padding: 0;
  list-style: none;
  overflow-y: auto;
}

.country-option {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.country-option:hover,
.country-option.active {
  background: #F5F7FA;
}

.country-option .country-iso {
  flex-shrink: 0;
  width: 26px;
  font-weight: 700;
  color: #1A1A2E;
}

.country-option .country-dial {
  flex-shrink: 0;
  width: 38px;
  color: #6B7280;
}

.country-name {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #6B7280;
}

.country-option:hover .country-name,
.country-option.active .country-name {
  color: #1A1A2E;
}

.country-empty {
  padding: 10px 8px;
  color: #6B7280;
  font-size: 11px;
  text-align: center;
}
</style>
