<% if (i18nEnabled) { %>
'use client';

import { usePathname } from 'next/navigation';
import { supportedLocales } from '@/i18n';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

const LOCALE_NAMES: Record<string, string> = {
  en: 'English',
  he: 'עברית',
  ar: 'العربية',
  es: 'Español',
  fr: 'Français',
  de: 'Deutsch',
  it: 'Italiano',
  pt: 'Português',
  nl: 'Nederlands',
  ja: '日本語',
  ko: '한국어',
  zh: '中文',
  ru: 'Русский',
  tr: 'Türkçe',
  pl: 'Polski',
  sv: 'Svenska',
  da: 'Dansk',
  no: 'Norsk',
  fi: 'Suomi',
  cs: 'Čeština',
  th: 'ไทย',
  vi: 'Tiếng Việt',
};

const defaultLocale = '<%= defaultLocale %>';

export function LanguageSwitcher() {
  const pathname = usePathname();
  const firstSeg = pathname.split('/')[1];
  const currentLocale = supportedLocales.includes(firstSeg as (typeof supportedLocales)[number])
    ? firstSeg
    : defaultLocale;

  function switchLocale(newLocale: string) {
    // Strip any existing locale segment, then re-add only if the new one
    // isn't the default — matches the as-needed prefix scheme in middleware.
    const segments = pathname.split('/');
    if (supportedLocales.includes(segments[1] as (typeof supportedLocales)[number])) {
      segments.splice(1, 1);
    }
    const bare = segments.join('/') || '/';
    window.location.href =
      newLocale === defaultLocale ? bare : `/${newLocale}${bare === '/' ? '' : bare}`;
  }

  if (supportedLocales.length <= 1) return null;

  return (
    <Select value={currentLocale} onValueChange={switchLocale}>
      <SelectTrigger
        className="h-8 w-auto gap-1 rounded border bg-transparent px-2 py-1 text-sm"
        aria-label="Select language"
      >
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {supportedLocales.map((locale) => (
          <SelectItem key={locale} value={locale}>
            {LOCALE_NAMES[locale] || locale}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
<% } %>
