"use client";

/**
 * LanguageToggle — EN | ES segmented pill.
 *
 * A compact two-button control that switches the active language.
 * Used in both the mobile app (header of the headgate list) and
 * the admin client (settings page).
 *
 * ARIA: implemented as a `radiogroup` with two `radio` items. We
 * intentionally avoid the `aria-pressed` toggle pattern because the
 * two buttons are mutually exclusive — pressing one deselects the
 * other. The `radiogroup` pattern communicates that to assistive
 * tech and matches the segmented visual intent.
 *
 * The pill is intentionally narrow so it can fit in a sticky nav bar
 * next to the logout icon. The active button has the brand-green
 * background; the inactive is a subtle pill outline.
 */

import { useLang } from "@/lib/water-log/lang-context";
import type { Lang } from "@/lib/water-log/i18n";

type Props = {
  /** Visual size. `sm` fits inside a 44pt iOS-style nav bar. */
  size?: "sm" | "md";
};

const LANG_OPTIONS: ReadonlyArray<{ lang: Lang; label: string }> = [
  { lang: "en", label: "EN" },
  { lang: "es", label: "ES" },
];

export function LanguageToggle({ size = "sm" }: Props) {
  const { lang, setLang, t } = useLang();

  const isSmall = size === "sm";
  const containerStyle: React.CSSProperties = {
    display: "inline-flex",
    alignItems: "stretch",
    borderRadius: 999,
    background: "rgba(120,120,128,0.14)",
    padding: 2,
    height: isSmall ? 28 : 32,
  };

  const baseButton: React.CSSProperties = {
    appearance: "none",
    border: 0,
    borderRadius: 999,
    padding: isSmall ? "0 9px" : "0 12px",
    fontSize: isSmall ? 12 : 13,
    fontWeight: 700,
    letterSpacing: "0.06em",
    cursor: "pointer",
    transition: "background-color 160ms, color 160ms",
    minWidth: isSmall ? 30 : 36,
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
  };

  const activeStyle: React.CSSProperties = {
    ...baseButton,
    background: "#14532d",
    color: "#ffffff",
    boxShadow: "0 1px 2px rgba(20,83,45,0.20)",
  };

  const inactiveStyle: React.CSSProperties = {
    ...baseButton,
    background: "transparent",
    color: "rgba(60,60,67,0.65)",
  };

  return (
    <div
      role="radiogroup"
      aria-label={t.common.a11yLanguage}
      data-testid="language-toggle"
      style={containerStyle}
    >
      {LANG_OPTIONS.map((opt) => (
        <button
          key={opt.lang}
          type="button"
          role="radio"
          aria-checked={lang === opt.lang}
          onClick={() => setLang(opt.lang)}
          style={lang === opt.lang ? activeStyle : inactiveStyle}
        >
          {opt.label}
        </button>
      ))}
    </div>
  );
}

export default LanguageToggle;