"use client";

import { useRouter } from "next/navigation";
import { MARKETING_LOCALE_COOKIE } from "@/lib/marketing-locale-cookie";
import type { Locale } from "@/lib/i18n/provider";

const OPTIONS: { code: Locale; flag: string; label: string }[] = [
  { code: "en", flag: "🇬🇧", label: "English" },
  { code: "fr", flag: "🇫🇷", label: "Français" },
];

// Plain module-level function, not part of the component body — setting a
// cookie is a real side effect (fine inside an event handler), but the
// React Compiler's purity lint flags any direct `document.cookie =`
// assignment written inline in a component/hook.
function setMarketingLocaleCookie(code: Locale) {
  document.cookie = `${MARKETING_LOCALE_COOKIE}=${code}; path=/; max-age=31536000; samesite=lax`;
}

/**
 * Cookie-based language switcher for the public marketing pages — sets
 * `marketing_locale` (read server-side by `getMarketingLocale`) and
 * refreshes, rather than reusing the authenticated app's `useLocale`/
 * `setLocale` (that persists to `users.locale` via a PATCH that would just
 * 401 for a logged-out visitor and revert the change).
 */
export function LanguageSwitcher({ current }: { current: Locale }) {
  const router = useRouter();

  function select(code: Locale) {
    if (code === current) return;
    setMarketingLocaleCookie(code);
    router.refresh();
  }

  return (
    <div className="flex items-center gap-0.5" role="group" aria-label="Language">
      {OPTIONS.map(({ code, flag, label }) => (
        <button
          key={code}
          type="button"
          onClick={() => select(code)}
          aria-label={label}
          aria-pressed={current === code}
          title={label}
          className={`text-base leading-none p-1.5 rounded-md transition-opacity ${
            current === code ? "opacity-100" : "opacity-40 hover:opacity-70"
          }`}
        >
          {flag}
        </button>
      ))}
    </div>
  );
}
