/* clock.jsx — Big interactive analog clock for teaching time.
   Globals: ClockToolModal
*/

(function () {
const { useState, useRef } = React;

// ===========================================================
// ClockToolModal — drag hour + minute hands, optional digital readout
// ===========================================================
function ClockToolModal({ onCancel }) {
  const [hour, setHour]     = useState(10);
  const [minute, setMinute] = useState(10);
  const [showDigital, setShowDigital] = useState(true);
  const svgRef = useRef(null);

  const VB = 400;
  const C = VB / 2;
  const FACE_R = 180;

  // Convert hour+minute to display angles in degrees, 0 = 12 o'clock, clockwise positive
  const hourAngle   = ((hour % 12) + minute / 60) * 30;
  const minuteAngle = minute * 6;

  // Endpoint helper: angle in degrees (0 = up), radius in viewBox units
  const tip = (angleDeg, r) => {
    const rad = (angleDeg - 90) * Math.PI / 180;
    return { x: C + r * Math.cos(rad), y: C + r * Math.sin(rad) };
  };

  // Begin drag on a hand. `steps` = 12 or 60. `setVal(stepped)` sets the state.
  const beginDrag = (steps, setVal) => (e) => {
    e.preventDefault();
    e.stopPropagation();
    const svg = svgRef.current;
    if (!svg) return;

    const handle = (ev) => {
      const rect = svg.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;
      const dx = ev.clientX - cx;
      const dy = ev.clientY - cy;
      // atan2 returns angle from +x (3 o'clock), clockwise positive because y grows downward.
      // Add PI/2 to make 12 o'clock = 0, then normalize to [0, 2PI).
      const angleFrom12 = (Math.atan2(dy, dx) + Math.PI / 2 + 2 * Math.PI) % (2 * Math.PI);
      const stepped = Math.round(angleFrom12 / (2 * Math.PI) * steps) % steps;
      setVal(stepped);
    };
    const up = () => {
      window.removeEventListener('pointermove', handle);
      window.removeEventListener('pointerup', up);
      window.removeEventListener('pointercancel', up);
    };
    handle(e);
    window.addEventListener('pointermove', handle);
    window.addEventListener('pointerup', up);
    window.addEventListener('pointercancel', up);
  };

  const hourTip   = tip(hourAngle, 95);
  const minuteTip = tip(minuteAngle, 150);

  // 12 hour numerals
  const numerals = [];
  for (let h = 1; h <= 12; h++) {
    const p = tip(h * 30, 145);
    numerals.push(
      <text key={h} x={p.x} y={p.y}
        textAnchor="middle" dominantBaseline="central"
        fontFamily="VT323, monospace" fontSize="34" fill="var(--ink)">
        {h}
      </text>
    );
  }

  // 60 minute ticks
  const ticks = [];
  for (let i = 0; i < 60; i++) {
    const big = i % 5 === 0;
    const outer = tip(i * 6, FACE_R - 4);
    const inner = tip(i * 6, FACE_R - (big ? 18 : 10));
    ticks.push(
      <line key={i} x1={inner.x} y1={inner.y} x2={outer.x} y2={outer.y}
        stroke="var(--ink)" strokeWidth={big ? 3 : 1.5} strokeLinecap="round" />
    );
  }

  return (
    <div className="modal-overlay" onClick={onCancel}>
      <div className="modal wide" onClick={(e) => e.stopPropagation()} style={{ width: 'min(640px, 96%)' }}>
        <div className="modal-inner">
          <h3 style={{ textAlign: 'center', marginBottom: 6 }}>Klok</h3>
          <p style={{ textAlign: 'center', marginTop: 0 }}>Sleep aan de wijzers om de tijd in te stellen.</p>

          <div style={{ width: '100%', maxWidth: 520, margin: '0 auto', aspectRatio: '1 / 1' }}>
            <svg ref={svgRef} viewBox={`0 0 ${VB} ${VB}`} width="100%" height="100%"
              style={{ display: 'block', touchAction: 'none', userSelect: 'none' }}>
              {/* Face */}
              <circle cx={C} cy={C} r={FACE_R} fill="var(--bg-card)" stroke="var(--line-strong)" strokeWidth="4" />
              {ticks}
              {numerals}

              {/* Hour hand — wide invisible hit line behind visible line for easy grabbing */}
              <line x1={C} y1={C} x2={hourTip.x} y2={hourTip.y}
                stroke="transparent" strokeWidth="32" strokeLinecap="round"
                style={{ cursor: 'grab' }}
                onPointerDown={beginDrag(12, setHour)} />
              <line x1={C} y1={C} x2={hourTip.x} y2={hourTip.y}
                stroke="var(--ender)" strokeWidth="12" strokeLinecap="round"
                pointerEvents="none" />

              {/* Minute hand */}
              <line x1={C} y1={C} x2={minuteTip.x} y2={minuteTip.y}
                stroke="transparent" strokeWidth="28" strokeLinecap="round"
                style={{ cursor: 'grab' }}
                onPointerDown={beginDrag(60, setMinute)} />
              <line x1={C} y1={C} x2={minuteTip.x} y2={minuteTip.y}
                stroke="var(--ink)" strokeWidth="7" strokeLinecap="round"
                pointerEvents="none" />

              {/* Center hub */}
              <circle cx={C} cy={C} r="10" fill="var(--ender)" stroke="var(--ink)" strokeWidth="2" pointerEvents="none" />
            </svg>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, marginTop: 14 }}>
            {showDigital && (
              <div style={{
                fontFamily: 'var(--font-disp)', fontSize: 56, letterSpacing: 2,
                color: 'var(--ender-hi)', textAlign: 'center',
              }}>
                {String(hour).padStart(2, '0')}:{String(minute).padStart(2, '0')}
              </div>
            )}
            <button className="btn-pixel ghost" style={{ padding: '8px 14px', fontSize: 11 }}
              onClick={() => setShowDigital(v => !v)}>
              {showDigital ? 'Verberg tijd' : 'Toon tijd'}
            </button>
          </div>

          <div className="modal-actions" style={{ marginTop: 20 }}>
            <button className="btn-pixel ghost" onClick={onCancel}>Sluit</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClockToolModal });
})();
