"use client";

import { useState } from "react";
import { Languages } from "lucide-react";
import type { Locale } from "@/lib/i18n";

export function LanguageToggle({ locale }: { locale: Locale }) {
  const [pending, setPending] = useState(false);
  const nextLocale: Locale = locale === "ar" ? "en" : "ar";

  async function switchLocale() {
    setPending(true);
    await fetch("/api/locale", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ locale: nextLocale })
    });
    window.location.reload();
  }

  return (
    <button
      aria-label={locale === "ar" ? "Switch to English" : "التبديل إلى العربية"}
      className="focus-ring inline-flex h-9 items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/[0.04] px-3 text-xs font-medium text-muted-white hover:text-warm-white hover:bg-white/[0.08] disabled:opacity-60 transition-all"
      disabled={pending}
      onClick={switchLocale}
      type="button"
    >
      <Languages size={14} />
      {locale === "ar" ? "EN" : "AR"}
    </button>
  );
}
