<template>
  <div class="locale-flags row items-center no-wrap">
    <button
      v-for="lang in languages"
      :key="lang.code"
      type="button"
      class="locale-flags__btn"
      :class="{ 'locale-flags__btn--active': currentLocaleBase === lang.code }"
      :title="lang.label"
      :aria-label="lang.label"
      @click="changeLocale(lang.code)"
    >
      <svg viewBox="0 0 24 16" class="locale-flags__flag">
        <template v-if="lang.code === 'pt'">
          <rect width="24" height="16" fill="#009b3a" />
          <polygon points="12,1.8 22.2,8 12,14.2 1.8,8" fill="#fedf00" />
          <circle cx="12" cy="8" r="3.4" fill="#002776" />
        </template>

        <template v-else-if="lang.code === 'en'">
          <rect width="24" height="16" fill="#fff" />
          <rect v-for="i in 7" :key="i" :y="(i - 1) * 2.46" width="24" height="1.23" fill="#b22234" />
          <rect width="10" height="8.6" fill="#3c3b6e" />
        </template>

        <template v-else>
          <rect width="24" height="16" fill="#aa151b" />
          <rect y="4" width="24" height="8" fill="#f1bf00" />
        </template>
      </svg>
    </button>
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useI18n } from "vue-i18n";

const { locale } = useI18n();

const languages = [
  { code: "pt", label: "Português" },
  { code: "en", label: "English" },
  { code: "es", label: "Español" },
];

const currentLocaleBase = computed(() =>
  locale.value?.split("-")[0].toLowerCase()
);

const changeLocale = (code) => {
  locale.value = code;
};
</script>

<style lang="scss" scoped>
.locale-flags {
  position: fixed;
  top: calc(16px + env(safe-area-inset-top));
  right: 16px;
  z-index: 2000;
  gap: 8px;
}

.locale-flags__btn {
  padding: 0;
  border: 2px solid rgba(255, 255, 255, 0.7);
  border-radius: 4px;
  background: transparent;
  line-height: 0;
  cursor: pointer;
  opacity: 0.65;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
  transition: opacity 0.2s, transform 0.2s, border-color 0.2s;

  &:hover {
    opacity: 1;
    transform: scale(1.08);
  }

  &--active {
    opacity: 1;
    border-color: #fff;
  }
}

.locale-flags__flag {
  display: block;
  width: 30px;
  height: 20px;
}
</style>
