<% if (i18nEnabled) { %>
'use client';

import { useEffect, useRef, useState } from 'react';
import { usePathname } from 'next/navigation';
import { supportedLocales } from '@/i18n';

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 %>';

/**
 * DESIGN ME — locale switcher in the header; reads supported locales from
 * `@/i18n` and swaps the URL prefix. Keep the aria-label and the redirect
 * logic exactly as-is.
 */
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}`;
  }

  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  // Close on outside click / Escape — a native <select> looks cheap next to
  // the rest of the header, so this is a small styled popover instead.
  useEffect(() => {
    if (!open) return;
    function onDown(e: MouseEvent) {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
    }
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') setOpen(false);
    }
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  if (supportedLocales.length <= 1) return null;

  return (
    <div ref={rootRef} className="relative">
      <button
        type="button"
        aria-label="Select language"
        aria-expanded={open}
        aria-haspopup="listbox"
        onClick={() => setOpen((v) => !v)}
        className="text-foreground/70 hover:text-foreground hover:bg-secondary/60 inline-flex h-9 items-center gap-1.5 rounded-full px-3 text-sm font-medium transition-colors"
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.6} className="h-4 w-4" aria-hidden="true">
          <circle cx="12" cy="12" r="9" />
          <path d="M3 12h18M12 3c2.5 2.6 3.8 5.7 3.8 9S14.5 18.4 12 21c-2.5-2.6-3.8-5.7-3.8-9S9.5 5.6 12 3z" />
        </svg>
        {LOCALE_NAMES[currentLocale] || currentLocale}
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className={`h-3.5 w-3.5 transition-transform ${open ? 'rotate-180' : ''}`} aria-hidden="true">
          <path d="M6 9l6 6 6-6" />
        </svg>
      </button>

      {open && (
        <ul
          role="listbox"
          aria-label="Select language"
          className="border-border/60 bg-background absolute end-0 top-full z-50 mt-2 min-w-36 overflow-hidden rounded-xl border py-1 shadow-lg"
        >
          {supportedLocales.map((locale) => (
            <li key={locale}>
              <button
                type="button"
                role="option"
                aria-selected={locale === currentLocale}
                onClick={() => {
                  setOpen(false);
                  if (locale !== currentLocale) switchLocale(locale);
                }}
                className={`hover:bg-secondary/70 flex w-full items-center justify-between px-4 py-2 text-sm transition-colors ${
                  locale === currentLocale ? 'text-primary font-semibold' : 'text-foreground/80'
                }`}
              >
                {LOCALE_NAMES[locale] || locale}
                {locale === currentLocale && (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.2} className="h-4 w-4" aria-hidden="true">
                    <path d="M5 13l4 4L19 7" />
                  </svg>
                )}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

<% } %>
