import { useEffect, useRef, useState } from "react";
import { input } from "@/lib/world-input";

export function Joystick() {
  const baseRef = useRef<HTMLDivElement>(null);
  const [knob, setKnob] = useState({ x: 0, y: 0 });
  const [show, setShow] = useState(false);

  useEffect(() => {
    const mq = window.matchMedia("(pointer: coarse)");
    const sync = () => setShow(mq.matches || window.innerWidth < 720);
    sync();
    mq.addEventListener("change", sync);
    window.addEventListener("resize", sync);
    return () => {
      mq.removeEventListener("change", sync);
      window.removeEventListener("resize", sync);
    };
  }, []);

  useEffect(() => {
    if (!show) {
      input.joyX = 0;
      input.joyY = 0;
    }
  }, [show]);

  if (!show) return null;

  const radius = 36;

  function bind(clientX: number, clientY: number) {
    const el = baseRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    let dx = clientX - cx;
    let dy = clientY - cy;
    const len = Math.hypot(dx, dy);
    if (len > radius) {
      dx = (dx / len) * radius;
      dy = (dy / len) * radius;
    }
    setKnob({ x: dx, y: dy });
    input.joyX = dx / radius;
    input.joyY = -dy / radius;
  }

  function end() {
    setKnob({ x: 0, y: 0 });
    input.joyX = 0;
    input.joyY = 0;
  }

  return (
    <div
      ref={baseRef}
      className="pointer-events-auto absolute bottom-[max(1.25rem,env(safe-area-inset-bottom))] left-4 z-20 size-[88px] rounded-full border border-border bg-bg/55"
      onPointerDown={(e) => {
        e.currentTarget.setPointerCapture(e.pointerId);
        bind(e.clientX, e.clientY);
      }}
      onPointerMove={(e) => {
        if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
        bind(e.clientX, e.clientY);
      }}
      onPointerUp={end}
      onPointerCancel={end}
      aria-hidden
    >
      <div
        className="absolute left-1/2 top-1/2 size-11 -translate-x-1/2 -translate-y-1/2 rounded-full bg-accent/90"
        style={{ transform: `translate(calc(-50% + ${knob.x}px), calc(-50% + ${knob.y}px))` }}
      />
    </div>
  );
}
