<template>
  <client-only>
    <div :key="sortedLanguages.length" class="language-selector language-selector--row">
      <template v-for="language in sortedLanguages" :key="`${language.code}-${language.selected}`">
        <a
          tabindex="0"
          role="button"
          :aria-label="language.code.toUpperCase()"
          :class="[
            'language-selector-link',
            { 'language-selector-link--active': language.selected },
          ]"
          @click="navigateToTranslationPage(language)"
        >
          {{ language.code.toUpperCase() }}
        </a>
      </template>
    </div>
  </client-only>
</template>

<script setup lang="ts">
import { useVueBaseProps } from '@lightspeed/crane';
import { computed } from 'vue';
import { Design } from '../../headers/example-header/type.ts';

const baseProps = useVueBaseProps<unknown, Design>();
const siteContent = computed(() => baseProps.site?.value satisfies SiteContent);
const isPreviewMode = computed(() => siteContent.value?.isPreviewMode ?? false);
const sortedLanguages = computed(() => (siteContent.value?.languages
  ? [...siteContent.value.languages].sort((a, b) => {
    if (a.main && !b.main) return -1;
    if (!a.main && b.main) return 1;
    return 0;
  })
  : []));

const navigateToTranslationPage = (language: Language) => {
  if (language.selected || isPreviewMode.value) {
    return;
  }
  if (language.url !== undefined) {
    window.open(language.url, '_self');
  }
};
</script>

<style scoped lang="scss">
.language-selector {
  display: flex;
}

.language-selector-link {
  padding: 8px;
  color: black;
  cursor: pointer;
  text-decoration: none;
  letter-spacing: 0.5px;
}

.language-selector-link--active {
  cursor: default;
  font-weight: bold;
  color: black;
  text-decoration: underline;
}

.language-selector-link:not(:last-child)::after {
  content: " ·";
  position: absolute;
  width: 0;
  padding-left: 5px;
  font-family: unset;
}
</style>
