// 3D-feel rotating year picker. Drag, flick, or tap arrows.

function YearDrum({ value, onChange, min = 1955, max = 2025, accent }) {
  const R = window.R;
  accent = accent || R.pink;
  const ITEM_H = 56;
  const trackRef = React.useRef(null);
  const [dragging, setDragging] = React.useState(false);
  const startRef = React.useRef({ y: 0, val: value });
  const velRef = React.useRef(0);

  const VISIBLE = 7;
  const half = Math.floor(VISIBLE / 2);
  const items = [];
  for (let i = -half - 2; i <= half + 2; i++) {
    items.push({ v: value + i, offset: i });
  }

  const inc = (d) => onChange(Math.max(min, Math.min(max, value + d)));

  const onPointerDown = (e) => {
    e.preventDefault();
    e.target.setPointerCapture?.(e.pointerId);
    startRef.current = { y: e.clientY, val: value, last: e.clientY, lastT: Date.now() };
    velRef.current = 0;
    setDragging(true);
  };
  const onPointerMove = (e) => {
    if (!dragging) return;
    const dy = e.clientY - startRef.current.y;
    const newVal = Math.max(min, Math.min(max, Math.round(startRef.current.val - dy / ITEM_H)));
    if (newVal !== value) {
      onChange(newVal);
      try { navigator.vibrate?.(2); } catch (_) {}
    }
    const now = Date.now();
    const dt = now - (startRef.current.lastT || now);
    if (dt > 0) velRef.current = (startRef.current.last - e.clientY) / dt;
    startRef.current.last = e.clientY;
    startRef.current.lastT = now;
  };
  const onPointerUp = () => {
    if (!dragging) return;
    setDragging(false);
    let v = velRef.current;
    if (Math.abs(v) > 0.4) {
      let cur = value;
      const tick = () => {
        v *= 0.88;
        if (Math.abs(v) < 0.05) return;
        cur = Math.max(min, Math.min(max, cur + Math.sign(v)));
        onChange(cur);
        requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 11, color: R.muted, letterSpacing: '.18em', fontWeight: 800 }}>YOUR GUESS</span>
        <span style={{ fontSize: 11, color: R.muted, fontFamily: 'ui-monospace, monospace', fontWeight: 700 }}>{min}–{max}</span>
      </div>

      <div
        ref={trackRef}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerCancel={onPointerUp}
        style={{
          position: 'relative', height: ITEM_H * 5,
          background: R.paper2,
          border: `2px solid ${R.ink}`,
          boxShadow: `4px 4px 0 ${R.ink}`,
          overflow: 'hidden',
          touchAction: 'none', cursor: dragging ? 'grabbing' : 'grab',
          backgroundImage: window.risoTex('rgba(26,26,26,.08)', 4),
        }}
      >
        <div style={{
          position: 'absolute', left: 0, right: 0, top: '50%', height: ITEM_H,
          transform: 'translateY(-50%)',
          background: accent,
          mixBlendMode: 'multiply',
          borderTop: `2px solid ${R.ink}`, borderBottom: `2px solid ${R.ink}`,
          pointerEvents: 'none',
        }} />
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: ITEM_H * 1.6, pointerEvents: 'none',
          background: `linear-gradient(${R.paper2}, transparent)` }} />
        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: ITEM_H * 1.6, pointerEvents: 'none',
          background: `linear-gradient(transparent, ${R.paper2})` }} />
        <div style={{
          position: 'absolute', top: 0, bottom: 0, left: 0, width: 8,
          background: `repeating-linear-gradient(0deg, ${R.ink} 0 1px, transparent 1px ${ITEM_H / 4}px)`,
          opacity: .5, pointerEvents: 'none',
        }} />

        {items.map(({ v, offset }) => {
          const dist = Math.abs(offset);
          const rot = offset * 18;
          const opacity = Math.max(0, 1 - dist * 0.18);
          const scale = 1 - dist * 0.06;
          const tabular = v < min || v > max;
          return (
            <div key={offset} style={{
              position: 'absolute', left: 0, right: 0, top: '50%',
              height: ITEM_H, lineHeight: `${ITEM_H}px`,
              transform: `translateY(-50%) translateY(${offset * ITEM_H}px) perspective(420px) rotateX(${rot}deg) scale(${scale})`,
              transformOrigin: 'center',
              transition: dragging ? 'none' : 'transform .22s cubic-bezier(.2,1.4,.4,1), opacity .22s',
              textAlign: 'center', userSelect: 'none',
              fontFamily: 'ui-monospace, "SF Mono", monospace',
              fontVariantNumeric: 'tabular-nums',
              fontSize: dist === 0 ? 56 : 36 - dist * 4,
              fontWeight: dist === 0 ? 900 : 700,
              color: tabular ? R.dim : R.ink,
              opacity: tabular ? 0.2 : opacity,
              letterSpacing: '-.02em',
              pointerEvents: 'none',
              mixBlendMode: dist === 0 ? 'multiply' : 'normal',
            }}>{tabular ? '' : v}</div>
          );
        })}

        <div style={{ position: 'absolute', left: 6, top: '50%', transform: 'translateY(-50%)',
          width: 10, height: 10, background: R.ink, clipPath: 'polygon(0 0, 100% 50%, 0 100%)', pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)',
          width: 10, height: 10, background: R.ink, clipPath: 'polygon(100% 0, 0 50%, 100% 100%)', pointerEvents: 'none' }} />
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        {[-10, -1, 1, 10].map((d) => (
          <button key={d} onClick={() => inc(d)} style={{
            flex: 1, height: 40,
            background: d > 0 ? R.paper : R.paper2,
            border: `2px solid ${R.ink}`,
            boxShadow: `2px 2px 0 ${R.ink}`,
            fontFamily: 'inherit', fontWeight: 800, fontSize: 13,
            color: R.ink, cursor: 'pointer', letterSpacing: '.04em',
          }}>{d > 0 ? `+${d}` : d}</button>
        ))}
      </div>
    </div>
  );
}

window.YearDrum = YearDrum;
