"use client";

import { useState } from "react";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";
import { useRouter, usePathname } from "next/navigation";

const languages = [
  { code: 'en', label: 'English', flag: '🇺🇸' },
  { code: 'fa', label: 'فارسی', flag: '🇮🇷' },
  { code: 'ar', label: 'العربية', flag: '🇸🇦' },
  { code: 'zh', label: '中文', flag: '🇨🇳' },
  { code: 'hi', label: 'हिन्दी', flag: '🇮🇳' },
  { code: 'es', label: 'Español', flag: '🇪🇸' },
  { code: 'fr', label: 'Français', flag: '🇫🇷' },
  { code: 'ru', label: 'Русский', flag: '🇷🇺' },
  { code: 'bn', label: 'বাংলা', flag: '🇧🇩' },
  { code: 'pt', label: 'Português', flag: '🇧🇷' },
  { code: 'id', label: 'Bahasa', flag: '🇮🇩' },
  { code: 'de', label: 'Deutsch', flag: '🇩🇪' },
  { code: 'ja', label: '日本語', flag: '🇯🇵' },
  { code: 'te', label: 'తెలుగు', flag: '🇮🇳' },
  { code: 'tr', label: 'Türkçe', flag: '🇹🇷' },
  { code: 'sw', label: 'Swahili', flag: '🇰🇪' },
  { code: 'el', label: 'Ελληνικά', flag: '🇬🇷' },
  { code: 'sr', label: 'Српски', flag: '🇷🇸' },
]

export default function LanguageSwitcher() {
  const [open, setOpen] = useState(false);
  const { i18n } = useTranslation();
  const router = useRouter();
  const pathname = usePathname();

  const currentLang = i18n.language;

  const toggleDropdown = () => setOpen(!open);

  const changeLanguage = (langCode: string) => {
   
    i18n.changeLanguage(langCode);

    
    const segments = pathname.split("/");
    if (segments[1] && languages.find(l => l.code === segments[1])) {
      segments[1] = langCode;
    } else {
      segments.splice(1, 0, langCode);
    }
    const newPath = segments.join("/") || "/";
    router.push(newPath);

    setOpen(false);
  };

  const current = languages.find((lang) => lang.code === currentLang) || languages[0];

  return (
    <div className="relative inline-block text-left">
      <button
        onClick={toggleDropdown}
        className="inline-flex max-Wide-mobile-s:text-xs rtl:flex-row-reverse items-center px-4 py-2 dark:border-white dark:text-white font-medium border rounded-xl shadow transition-all"
      >
        <BoldIcon name="global" size={18} tinted className="mr-2 text-current" />
        {current.flag} {current.label}
      </button>

      {open && (
        <div className="absolute z-10 mt-2  rounded-md bg-white dark:bg-neutral-800 shadow-lg ring-1 ring-black ring-opacity-5">
          <div className="py-1">
            {languages.map((lang) => (
              <button
                key={lang.code}
                onClick={() => changeLanguage(lang.code)}
                className="w-full rtl:flex-row-reverse flex items-center px-4 py-2 text-sm text-gray-700 dark:text-white/60 dark:hover:bg-gray-600 hover:bg-gray-100"
              >
                <span className="mr-2 flex">{lang.flag}</span> {lang.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}