"use client";

/**
 * Locale picker for the landing page.
 *
 * The choice is stored in a `lang` cookie and the server component re-reads it,
 * so the URL stays `/` in every language. That keeps the root route untouched:
 * no `[locale]` segment, no middleware rewrite, nothing for `proxy.ts` to know
 * about. Switching costs one server round trip via `router.refresh()`.
 */

import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { GlobeIcon } from "lucide-react";
import { LOCALES, type Locale } from "./landing-messages";

export function LanguageSwitcher({
  current,
  label,
  className,
}: {
  current: Locale;
  label: string;
  className?: string;
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  const change = (next: string) => {
    // One year, site-wide, so the choice survives navigation and return visits.
    document.cookie = `lang=${next}; path=/; max-age=31536000; samesite=lax`;
    startTransition(() => router.refresh());
  };

  return (
    <label className={className} style={{ opacity: pending ? 0.6 : 1 }}>
      <GlobeIcon size={15} aria-hidden />
      <span className="sr-only">{label}</span>
      <select
        value={current}
        onChange={(e) => change(e.target.value)}
        aria-label={label}
      >
        {Object.entries(LOCALES).map(([code, meta]) => (
          <option key={code} value={code}>
            {meta.label}
          </option>
        ))}
      </select>
    </label>
  );
}
