"use client";

import { useEffect, useRef, useState } from "react";
import { UI_SCALES } from "@/lib/ui-scale";

/**
 * Text-size picker. Controlled: AppShell owns the value and handles applying
 * and persisting it, because the same setting is edited from two places (the
 * appbar popover and the mobile drawer) and reconciled against the account on
 * load.
 *
 * `variant="menu"` is the compact appbar popover; `variant="inline"` is the
 * flat row used inside the mobile drawer, where a popover inside a popover
 * would be awkward.
 */
export function FontScaleControl({
  value,
  onChange,
  variant = "menu",
}: {
  value: number;
  onChange: (scale: number) => void;
  variant?: "menu" | "inline";
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    function onPointerDown(event: MouseEvent) {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        setOpen(false);
      }
    }
    function onKeyDown(event: KeyboardEvent) {
      if (event.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  function choose(next: number) {
    onChange(next);
    setOpen(false);
  }

  const options = UI_SCALES.map((option) => ({
    ...option,
    selected: Math.abs(value - option.value) < 0.001,
  }));

  if (variant === "inline") {
    return (
      <div className="scale-inline" role="radiogroup" aria-label="Tamaño de texto">
        <span className="appbar-drawer-heading">Tamaño de texto</span>
        <div className="scale-inline-options">
          {options.map((option) => (
            <button
              key={option.value}
              type="button"
              role="radio"
              aria-checked={option.selected}
              className={`scale-chip${option.selected ? " active" : ""}`}
              style={{ fontSize: `${option.value}em` }}
              onClick={() => choose(option.value)}
            >
              {option.short}
              <span className="sr-only"> {option.label}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="appbar-menu" ref={ref}>
      <button
        type="button"
        className="appbar-scale-trigger"
        aria-expanded={open}
        aria-haspopup="true"
        aria-label="Tamaño de texto"
        title="Tamaño de texto"
        onClick={() => setOpen((v) => !v)}
      >
        <span aria-hidden="true">
          A<span className="appbar-scale-big">A</span>
        </span>
      </button>
      {open && (
        <div className="appbar-dropdown appbar-dropdown-right" role="menu">
          {options.map((option) => (
            <button
              key={option.value}
              type="button"
              role="menuitemradio"
              aria-checked={option.selected}
              className={`appbar-dropdown-link scale-option${option.selected ? " active" : ""}`}
              onClick={() => choose(option.value)}
            >
              <span style={{ fontSize: `${option.value}em` }}>{option.short}</span>
              <span className="scale-option-label">{option.label}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
