// Knob — rotary amplifier-style control.
// Drag vertically (or scroll wheel) to change value.
// Visual: chunky retro pot with notch indicator and arc track.

function Knob({ value, min = 0, max = 10, step = 1, onChange, size = 84, label, unit, hint, color = '#E75002', accent = '#3FA890' }) {
  const ratio = (value - min) / (max - min); // 0..1
  const startAngle = -135;
  const endAngle = 135;
  const angle = startAngle + ratio * (endAngle - startAngle);

  const dragRef = React.useRef({ active: false, startY: 0, startVal: value });

  const onPointerDown = (e) => {
    e.preventDefault();
    dragRef.current = { active: true, startY: e.clientY, startVal: value };
    document.body.style.cursor = 'ns-resize';
    document.body.style.userSelect = 'none';
  };

  React.useEffect(() => {
    const onMove = (e) => {
      if (!dragRef.current.active) return;
      const dy = dragRef.current.startY - e.clientY; // up = increase
      const range = max - min;
      const delta = (dy / 140) * range;
      let v = dragRef.current.startVal + delta;
      v = Math.round(v / step) * step;
      v = Math.max(min, Math.min(max, v));
      onChange(v);
    };
    const onUp = () => {
      if (!dragRef.current.active) return;
      dragRef.current.active = false;
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    };
    window.addEventListener('pointermove', onMove);
    window.addEventListener('pointerup', onUp);
    return () => {
      window.removeEventListener('pointermove', onMove);
      window.removeEventListener('pointerup', onUp);
    };
  }, [min, max, step, onChange]);

  const onWheel = (e) => {
    e.preventDefault();
    const dir = e.deltaY < 0 ? 1 : -1;
    let v = value + dir * step;
    v = Math.max(min, Math.min(max, v));
    onChange(v);
  };

  // Arc path for the track (uses SVG)
  const r = size * 0.42;
  const cx = size / 2, cy = size / 2;
  const polar = (deg) => {
    const rad = (deg - 90) * Math.PI / 180;
    return [cx + r * Math.cos(rad), cy + r * Math.sin(rad)];
  };
  const [sx, sy] = polar(startAngle);
  const [ex, ey] = polar(endAngle);
  const [vx, vy] = polar(angle);
  // background full arc
  const bigBg = (endAngle - startAngle) > 180 ? 1 : 0;
  const bgPath = `M ${sx} ${sy} A ${r} ${r} 0 ${bigBg} 1 ${ex} ${ey}`;
  // value arc
  const sweep = angle - startAngle;
  const bigVal = sweep > 180 ? 1 : 0;
  const valPath = `M ${sx} ${sy} A ${r} ${r} 0 ${bigVal} 1 ${vx} ${vy}`;

  // Tick marks around
  const ticks = 11;
  const tickArr = [];
  for (let i = 0; i < ticks; i++) {
    const t = i / (ticks - 1);
    const a = startAngle + t * (endAngle - startAngle);
    const [tx, ty] = polar(a);
    const [tx2, ty2] = polar(a);
    const inner = r - 4;
    const ax = cx + (inner) * Math.cos((a - 90) * Math.PI / 180);
    const ay = cy + (inner) * Math.sin((a - 90) * Math.PI / 180);
    const active = t <= ratio + 0.001;
    tickArr.push({ x1: ax, y1: ay, x2: tx, y2: ty, active });
  }

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flex: 1, minWidth: 0,
    }}>
      {label && (
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: 2,
          color: 'var(--dim)', textAlign: 'center',
        }}>{label}</div>
      )}
      <div
        onPointerDown={onPointerDown}
        onWheel={onWheel}
        style={{
          width: size, height: size, position: 'relative',
          cursor: 'ns-resize', touchAction: 'none',
        }}
      >
        <svg width={size} height={size} style={{ position: 'absolute', inset: 0 }}>
          {/* tick marks */}
          {tickArr.map((t, i) => (
            <line key={i} x1={t.x1} y1={t.y1} x2={t.x2} y2={t.y2}
              stroke={t.active ? color : 'rgba(238,228,218,0.18)'}
              strokeWidth={t.active ? 2 : 1.2}
              strokeLinecap="round"
            />
          ))}
        </svg>

        {/* knob body */}
        <div style={{
          position: 'absolute', inset: size * 0.16,
          borderRadius: '50%',
          background: `radial-gradient(circle at 30% 28%, #1a1a1a, #000)`,
          border: `2px solid ${color}`,
          boxShadow: `
            0 4px 0 #000,
            0 6px 14px rgba(0,0,0,0.6),
            inset 0 0 0 2px #000,
            inset 0 -3px 8px rgba(0,0,0,0.7),
            inset 0 3px 6px rgba(255,255,255,0.05)
          `,
          transform: `rotate(${angle}deg)`,
          transition: dragRef.current.active ? 'none' : 'transform 0.12s cubic-bezier(.4,1.4,.5,1)',
        }}>
          {/* notch indicator pointing up */}
          <div style={{
            position: 'absolute', top: 4, left: '50%', transform: 'translateX(-50%)',
            width: 4, height: '32%', borderRadius: 2,
            background: color,
            boxShadow: `0 0 6px ${color}`,
          }} />
          {/* center dot */}
          <div style={{
            position: 'absolute', top: '50%', left: '50%',
            width: 8, height: 8, borderRadius: 4,
            background: color, transform: 'translate(-50%, -50%)',
          }} />
        </div>
      </div>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 16, fontWeight: 700,
        color: color, letterSpacing: 1,
      }}>{unit ?? value}</div>
      {hint && (
        <div style={{ fontSize: 10, color: 'var(--dim)', fontFamily: 'var(--mono)', letterSpacing: 1, textAlign: 'center', minHeight: 12 }}>
          {hint}
        </div>
      )}
    </div>
  );
}

window.Knob = Knob;
