<template>
  <div class="layout-language">
    <span class="layout-language__title _to-sm">{{ $t('language') }}:</span>
    <details
      class="layout-language__details"
      name="layout-language"
    >
      <summary class="layout-language__summary">
        <UiIcon
          :size="iconSize"
          class="layout-language__icon"
          name="earth"
        />
        <span class="layout-language__current">
          <span class="_from-sm">{{ $t('language') }}:&nbsp;</span>
          <span class="layout-language__text">{{ localeName }}</span>
        </span>
        <UiIcon
          class="layout-language__angle"
          name="angle-down"
          size="16"
        />
      </summary>
      <div class="layout-language__details-wrapper">
        <button
          v-for="(item, index) in enabledLocales"
          :key="`language-${index}`"
          :class="{'--current': item.code === selectedLocale}"
          :lang="item.language"
          class="layout-language__details-item"
          type="button"
          @click="changeLocale(item.code)"
        >{{ item.name }}
        </button>
      </div>
    </details>
    <span class="layout-language__title _to-sm">{{ $t('country') }}:</span>
    <details
      class="layout-language__details"
      name="layout-language"
      @toggle="onCountryToggle($event)"
    >
      <summary class="layout-language__summary">
        <img
          v-if="clientCountryFlag"
          :alt="clientCountryName"
          :src="clientCountryFlag"
          class="layout-language__icon"
          width="20"
          height="20"
        >
        <UiIcon
          v-else
          :size="iconSize"
          class="layout-language__icon"
          name="earth"
        />
        <span class="layout-language__current">
          <span class="_from-sm">{{ $t('country') }}:&nbsp;</span>
          <span class="layout-language__text">{{ clientCountryName }}</span></span>
        <UiIcon
          class="layout-language__angle"
          name="angle-down"
          size="16"
        />
      </summary>
      <div class="layout-language__details-wrapper">
        <UiInput
          v-model="countryValue"
          :icon="countryValue.length > 0 ? 'close' : ''"
          :placeholder="$t('search')"
          pre-icon="search"
          class="layout-language__input"
          pre-icon-size="16"
          size="s"
          @icon-click="countryValue = ''"
        />
        <p class="layout-language__description">{{ $t('country_description') }}</p>
        <div
          v-if="isCountryOpen"
          class="layout-language__buttons"
        >
          <button
            v-for="(item, index) in filteredCountries"
            :key="`language-${index}`"
            :class="{'--current': item.icon === clientCountryIcon}"
            class="layout-language__details-item --country"
            type="button"
            @click="changeCountry(item)"
          >
            <img
              :alt="item.title"
              :src="`/icons/flags/${item.icon}.svg`"
              width="20"
              height="20"
              loading="lazy"
            >
            {{ item.title }}
          </button>
          <p
            v-if="countryValue && !filteredCountries.length"
            class="layout-language__empty"
          >{{ $t('nothing_found') }}</p>
        </div>
      </div>
    </details>
  </div>
</template>

<script setup lang="ts">
import type { ISelectItem } from '../../types';

const { locale, locales } = useI18n();
const switchLocalePath = useSwitchLocalePath();

defineProps<{
  iconSize: string
}>();

const {
  icon: clientCountryIcon,
  name: clientCountryName,
  flagSrc: clientCountryFlag,
  countriesItems,
  setCountry,
  loadCountries,
} = useClientCountry();

const isCountryOpen = ref(false);
const countryValue = ref('');
const filteredCountries = computed(() => {
  if (!countryValue.value) return countriesItems.value;
  const query = countryValue.value.toLowerCase();
  return countriesItems.value.filter(item => item.title.toLowerCase().includes(query));
});

function onCountryToggle(e: Event) {
  isCountryOpen.value = (e.target as HTMLDetailsElement).open;
  if (isCountryOpen.value) loadCountries();
}

const enabledLocales = useEnabledLocales();

const selectedLocale = ref(locale.value);

watch(locale, (val) => {
  selectedLocale.value = val;
});

const localeName = computed(() => locales.value.find(item => item.code === locale.value)?.name || 'English');

const emit = defineEmits<{
  (e: 'change', locale: string): void
}>();

const localeCookie = useCookie('i18n_redirected', { path: '/', secure: true, sameSite: 'lax' as const });

function changeLocale(locale: string) {
  emit('change', locale);
  localeCookie.value = locale;
  window.location.href = switchLocalePath(locale);
}

async function changeCountry(item: ISelectItem) {
  setCountry(item);
  // куку пишет вотчер useCookie — ждём флаш, иначе навигация может срезать запись
  await nextTick();
  window.location.href = '/';
}
</script>

<style lang="scss">
.layout-language {
  display: grid;
}

.layout-language__title {
  @include to-br(sm) {
    @include font-xs;

    padding: 8px 16px;
    font-weight: 500;
    color: $language-title;
    text-transform: uppercase;
  }
}

.layout-language__current {
  display: grid;
  grid-template-columns: auto 1fr;
  color: $language--current;
  width: 100%;

  @include from-br(sm) {
    @include font-sm;
  }
}

.layout-language__summary {
  position: relative;
  display: grid;
  grid-template-columns: auto 1fr 16px;
  flex-wrap: nowrap;
  padding: 10px 16px;
  column-gap: 16px;
  align-items: center;
  color: $language-text;
  user-select: none;

  @include from-br(sm) {
    padding: 12px 16px;
    column-gap: 12px;
  }
}

.layout-language__details:not(:last-child) .layout-language__summary {
  @include from-br(sm) {
    border-bottom: 1px solid $language-border;
  }
}

.layout-language__angle {
  color: $language-angle;
  pointer-events: none;
  transition: var(--transition) transform;
}

.layout-language__icon {
  color: $language-icon;
}

.layout-language__details-wrapper {
  display: grid;

  @include from-br(sm) {
    padding: 12px 16px;
  }
}

.layout-language__details-item {
  @include font-sm;

  display: grid;
  margin-bottom: 4px;
  column-gap: 12px;
  align-items: center;
  color: $language-item-text;
  padding: 10px 16px;
  text-align: start;
  border-radius: $radius-lg;

  @include hover(background-color) {
    background-color: $language-item-bg--hover;
  }
}

.layout-language__details-item.--country {
  @include from-br(sm) {
    padding: 8px 10px;
  }
}

.layout-language__details-item:has(img) {
  grid-template-columns: 20px 1fr;
}

.layout-language__details-item.--current {
  color: $language-item-text--current;
  background-color: $language-item-bg--current;
}

.layout-language__details-item:last-child {
  margin-bottom: 0;
}

.layout-language__details:not(:last-child) {
  @include to-br(sm) {
    margin-bottom: 12px;
  }
}

.layout-language__details[open] .layout-language__angle {
  transform: rotate(180deg);
}

.layout-language__text {
  color: $language-value-text;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
  text-align: center;
  font-weight: 500;
}

.layout-language__description {
  @include font-xs;

  margin-bottom: 12px;
  color: $language-description;
  padding-inline: 16px;

  @include from-br(sm) {
    padding-inline: 4px;
    margin-bottom: 8px;
  }
}

.layout-language__input {
  margin-bottom: 8px;

  @include to-br(sm) {
    padding-inline: 16px;
  }
}

.layout-language__buttons {
  display: grid;
  max-height: 300px;
  overflow-y: auto;
}

.layout-language__empty {
  @include font-sm;

  color: $language-empty-text;
  padding: 8px;
}

.layout-language__details[open] .layout-language__summary {
  border-bottom-color: transparent;
}
</style>
