"use client";

import {
  useCallback,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { FOCUS_RING } from "./focus-ring";
import { TAP_TARGET } from "./tap-target";

// A single-selection segmented picker: a row of pill options inside a muted
// track, where exactly one option is selected at a time. The active option
// inverts to the foreground colour for a strong selected look against the
// muted track — the same pattern the set editor uses for "Set type" and
// "Tracked side" rows. Generic over the option value so callers keep their
// own domain type (boolean, string union, id, …) without stringifying.
//
// A pill is 26 px high. On a touch screen each takes a tap in an invisible
// area of at least 44 × 44 px around it (`TAP_TARGET`); the picker is drawn
// at the same size. A `scrollable` track clips what reaches out of it, so
// its pills keep their own size as the area.
//
// The selected background is one "thumb" behind the pills that slides to the
// selected pill. It is placed from the pills' measured boxes (re-measured by
// a ResizeObserver on font load, text scaling, resizes and label changes).
// Until it is measured — server render, first client render — the selected
// pill paints the same background itself, so nothing flashes; the thumb then
// takes over in place, and only a change of selection animates.
export type SegmentedPickerOption<T> = {
  value: T;
  label: string;
  /** Overrides the visible `label` for screen readers when it needs more context. */
  ariaLabel?: string;
  /** A small mark after the label, in the label's colour (decorative: say what it means in `ariaLabel`). */
  mark?: ReactNode;
};

export function SegmentedPicker<T>({
  value,
  onChange,
  options,
  ariaLabel,
  scrollable = false,
  fullWidth = false,
  track = true,
}: {
  value: T;
  onChange: (value: T) => void;
  options: ReadonlyArray<SegmentedPickerOption<T>>;
  ariaLabel?: string;
  /**
   * Let the pill track scroll horizontally when the options don't fit (e.g. five
   * long labels on a narrow screen). Options stop shrinking so their labels never
   * wrap or truncate; the scrollbar is hidden. Off by default so the fixed
   * two/three-option consumers keep their equal-width row.
   */
  scrollable?: boolean;
  /**
   * Stretch the options to share the track equally (each pill `flex-1`,
   * centred). For a picker that IS the row — a drawer's top-level segment
   * switch — where the default content-sized pills would leave the muted track
   * trailing off empty beside them. Mutually exclusive with `scrollable`.
   */
  fullWidth?: boolean;
  /**
   * The muted track behind the options. Off: only the active option's pill
   * shows — for a picker that already sits on its own surface (the tracking
   * app's floating Insights chip). Off also sizes each option like the chip's
   * other pills (`py-1.5` and a transparent 1px border), so every selection in
   * the chip has one height.
   */
  track?: boolean;
}) {
  const trackRef = useRef<HTMLDivElement>(null);
  const optionRefs = useRef<Array<HTMLButtonElement | null>>([]);
  const [thumb, setThumb] = useState<ThumbPlacement | null>(null);
  const activeIndex = options.findIndex((option) => option.value === value);
  const labelsKey = options.map((option) => option.label).join("\u0000");
  const valuesKey = options.map((option) => String(option.value)).join("\u0000");

  const measure = useCallback(() => {
    const element = activeIndex >= 0 ? optionRefs.current[activeIndex] : null;
    if (!element) {
      setThumb(null);
      return;
    }
    // offset* ignores ancestor transforms (a drawer scaling in), unlike
    // getBoundingClientRect; the track is the offsetParent (it is `relative`).
    const box: ThumbBox = {
      x: element.offsetLeft,
      y: element.offsetTop,
      width: element.offsetWidth,
      height: element.offsetHeight,
    };
    setThumb((previous) => nextThumbPlacement(previous, activeIndex, box));
  }, [activeIndex]);

  useLayoutEffect(() => {
    measure();
    if (typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(() => measure());
    if (trackRef.current) observer.observe(trackRef.current);
    for (const element of optionRefs.current) {
      if (element) observer.observe(element);
    }
    return () => observer.disconnect();
  }, [measure, options.length, labelsKey, valuesKey]);

  return (
    <div
      ref={trackRef}
      role="radiogroup"
      aria-label={ariaLabel}
      className={`relative flex gap-1 rounded-full ${track ? "bg-surface-base-muted p-0.5" : ""} ${
        scrollable ? "w-fit max-w-full scrollbar-none overflow-x-auto" : ""
      }`}
    >
      {thumb ? (
        <span
          aria-hidden="true"
          className={`pointer-events-none absolute left-0 top-0 rounded-full bg-foreground-default ${
            thumb.animate
              ? "transition-[transform,width] duration-200 ease-out motion-reduce:transition-none"
              : "transition-none"
          }`}
          style={{
            width: thumb.width,
            height: thumb.height,
            transform: `translate(${thumb.x}px, ${thumb.y}px)`,
          }}
        />
      ) : null}
      {options.map((option, index) => {
        const active = index === activeIndex;
        return (
          <button
            key={String(option.value)}
            ref={(element) => {
              optionRefs.current[index] = element;
            }}
            type="button"
            role="radio"
            aria-checked={active}
            aria-label={option.ariaLabel ?? option.label}
            onClick={() => onChange(option.value)}
            className={`clickable-small relative rounded-full px-3 ${track ? "py-1" : "border border-transparent py-1.5"} transition-colors duration-200 ease-out motion-reduce:transition-none ${FOCUS_RING} ${
              scrollable ? "shrink-0 whitespace-nowrap" : TAP_TARGET
            } ${fullWidth ? "flex-1 text-center" : ""} ${
              active
                ? `text-surface-base ${thumb ? "" : "bg-foreground-default"}`
                : "text-foreground-muted hover:text-foreground-default"
            }`}
          >
            {option.mark ? (
              <span className="flex items-center gap-1.5">
                {option.label}
                {option.mark}
              </span>
            ) : (
              option.label
            )}
          </button>
        );
      })}
    </div>
  );
}

export type ThumbBox = { x: number; y: number; width: number; height: number };
export type ThumbPlacement = ThumbBox & { index: number; animate: boolean };

/**
 * The thumb's next placement after a measurement. It slides only when the
 * selection moved to another option; the first placement and re-measurements
 * of the same option that moved it (resize, font load) land in place.
 * Returns `previous` itself when nothing changed, so a re-measurement does not
 * re-render or cut a running slide short.
 */
export function nextThumbPlacement(
  previous: ThumbPlacement | null,
  index: number,
  box: ThumbBox,
): ThumbPlacement {
  const animate = previous !== null && previous.index !== index;
  if (
    previous &&
    previous.index === index &&
    previous.x === box.x &&
    previous.y === box.y &&
    previous.width === box.width &&
    previous.height === box.height
  ) {
    return previous;
  }
  return { ...box, index, animate };
}
