import { useRef } from "react";

/** Left-thumb virtual stick. x/y in −1..1, +y is forward. */
export function TouchStick({
  onChange,
  label = "Move",
}: {
  onChange: (x: number, y: number) => void;
  label?: string;
}) {
  const root = useRef<HTMLDivElement>(null);
  const pid = useRef<number | null>(null);

  function setFromEvent(e: React.PointerEvent) {
    const el = root.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const cx = r.left + r.width / 2;
    const cy = r.top + r.height / 2;
    const nx = (e.clientX - cx) / (r.width * 0.42);
    const ny = (cy - e.clientY) / (r.height * 0.42);
    const m = Math.hypot(nx, ny);
    const s = m > 1 ? 1 / m : 1;
    onChange(Math.max(-1, Math.min(1, nx * s)), Math.max(-1, Math.min(1, ny * s)));
  }

  return (
    <div
      ref={root}
      className="stadium-stick"
      role="slider"
      aria-label={label}
      onPointerDown={(e) => {
        pid.current = e.pointerId;
        e.currentTarget.setPointerCapture(e.pointerId);
        setFromEvent(e);
      }}
      onPointerMove={(e) => {
        if (pid.current !== e.pointerId) return;
        setFromEvent(e);
      }}
      onPointerUp={(e) => {
        if (pid.current !== e.pointerId) return;
        pid.current = null;
        onChange(0, 0);
      }}
      onPointerCancel={() => {
        pid.current = null;
        onChange(0, 0);
      }}
    >
      <span className="stadium-stick-knob" />
    </div>
  );
}
