"use client";

import { useRouter } from "next/navigation";
import { Check, Globe } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { MARKETING_LOCALE_COOKIE } from "@/lib/marketing-locale-cookie";
import type { Locale } from "@/lib/i18n/provider";
import { FlagGB, FlagFR } from "./flag-icons";

const OPTIONS: { code: Locale; Flag: typeof FlagGB; label: string }[] = [
  { code: "en", Flag: FlagGB, label: "English" },
  { code: "fr", Flag: FlagFR, 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();
  const CurrentFlag = OPTIONS.find((o) => o.code === current)?.Flag ?? Globe;

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

  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
        aria-label="Change language"
      >
        <CurrentFlag className="h-4 w-5 rounded-[2px]" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        {OPTIONS.map(({ code, Flag, label }) => (
          <DropdownMenuItem key={code} onClick={() => select(code)} className="gap-2">
            <Flag className="h-3.5 w-[1.15rem] rounded-[2px] shrink-0" />
            <span className="flex-1">{label}</span>
            {current === code && <Check className="h-3.5 w-3.5" />}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
