import { DEFAULT_LOCALE, LOCALES, type Locale } from "@/lib/i18n/config";

interface LanguageSwitcherProps {
  /** Currently active locale. */
  currentLocale: Locale;
  /** Current URL path *without* any locale prefix (e.g. "/about"). */
  pathname: string;
  /** Active search string (e.g. "?service=events"); appended to the target so
   *  the user lands on the exact same page in the other locale, with their
   *  filters and prefilled params intact. */
  search?: string;
  /** Optional layout variant for styling. */
  variant?: "header" | "mobile";
}

const LABELS: Record<Locale, string> = {
  ar: "عربي",
  en: "English",
};

/**
 * Two-language toggle (AR/EN). The active locale renders as a non-link span;
 * the inactive one is a plain `<a>` (not next/link) so switching languages
 * forces a full document reload. That guarantees the root layout, the
 * `<html lang>` / `<html dir>` attributes, and every server-fetched piece of
 * chrome (header, footer, site labels) come back fresh in the new locale —
 * client-side navigation would reuse the cached layout shell and leave the
 * previous locale's chrome on screen.
 */
export function LanguageSwitcher({
  currentLocale,
  pathname,
  search = "",
  variant = "header",
}: LanguageSwitcherProps) {
  const normalizedPath = pathname === "" ? "/" : pathname;

  return (
    <div
      className={`lang-switch lang-switch--${variant}`}
      role="group"
      aria-label="Language"
    >
      {LOCALES.map((locale) => {
        const isActive = locale === currentLocale;
        const href = hrefFor(locale, normalizedPath) + search;
        const label = LABELS[locale];

        if (isActive) {
          return (
            <span key={locale} className="lang-switch__item is-active" aria-current="true">
              {label}
            </span>
          );
        }

        return (
          <a
            key={locale}
            href={href}
            hrefLang={locale}
            className="lang-switch__item"
            data-lang-switch={locale}
          >
            {label}
          </a>
        );
      })}
    </div>
  );
}

function hrefFor(locale: Locale, pathWithoutLocale: string): string {
  if (locale === DEFAULT_LOCALE) {
    return pathWithoutLocale === "/" ? "/" : pathWithoutLocale;
  }
  return pathWithoutLocale === "/" ? `/${locale}` : `/${locale}${pathWithoutLocale}`;
}
