"use client"

import { useLocale } from "next-intl"
import { usePathname, useRouter } from "next/navigation"

function removeLeadingLocale(pathname: string) {
  return pathname.replace(/^\/(fr|en)(?=\/|$)/, "") || "/"
}

function addLocale(pathnameNoLocale: string, locale: "fr" | "en") {
  // ✅ toujours préfixer
  return `/${locale}${pathnameNoLocale === "/" ? "" : pathnameNoLocale}`
}

export function LocaleSwitcher() {
  const router = useRouter()
  const pathname = usePathname()
  const locale = useLocale()

  const nextLocale: "fr" | "en" = locale === "fr" ? "en" : "fr"

  return (
    <button
      type="button"
      className="text-sm px-3 py-2 rounded-xl border bg-background hover:bg-muted"
      onClick={() => {
        const noLocale = removeLeadingLocale(pathname)
        const nextPath = addLocale(noLocale, nextLocale)
        router.replace(nextPath)
      }}
    >
      {locale === "fr" ? "EN" : "FR"}
    </button>
  )
}
