<template>
  <div class="flex items-center gap-1 text-sm">
    <button
      @click="switchLang('tr')"
      :class="
        currentLang === 'tr' ? 'text-dark' : 'text-dark/40 hover:text-dark'
      "
    >
      TR
    </button>

    <span class="text-dark/20">/</span>

    <button
      @click="switchLang('en')"
      :class="
        currentLang === 'en' ? 'text-dark' : 'text-dark/40 hover:text-dark'
      "
    >
      EN
    </button>
  </div>
</template>

<script setup lang="ts">
import { computed, Ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter, useRoute } from "vue-router";

const { locale } = useI18n();
const router = useRouter();
const route = useRoute();

// aktif dil
const currentLang = computed(() => locale.value);

// dil değiştir
const switchLang = (lang: string) => {
  (locale as Ref<string>).value = lang;

  try {
    localStorage.setItem("lang", lang);
  } catch {}

  if (typeof document !== "undefined") {
    document.documentElement.lang = lang;
  }

  // URL prefix yönetimi
  const currentPath = route.path || "/";

  const withEn = (p: string) => {
    if (p === "/en") return "/en";
    return p.startsWith("/en/") ? p : p === "/" ? "/en" : `/en${p}`;
  };

  const withoutEn = (p: string) => {
    if (p === "/en") return "/";
    return p.startsWith("/en/") ? p.slice(3) : p;
  };

  const targetPath =
    lang === "en" ? withEn(currentPath) : withoutEn(currentPath);

  if (targetPath !== currentPath) {
    router
      .replace({ path: targetPath, query: route.query, hash: route.hash })
      .catch(() => {});
  }
};
</script>
