/* global React, window */
// Drums Lab — Count-the-hits exercise.
//
// Plays a 1-bar beat (twice). The user counts how many times the target
// piece (kick or snare) was hit and types the number. Trains ears for
// isolating a single voice inside a groove.

(function () {
  'use strict';
  window.DrumsLab = window.DrumsLab || {};
  window.DrumsLab.ui = window.DrumsLab.ui || {};

  const PIECE_LABEL = { kick: 'kick', snare: 'snare' };

  const ExerciseCountHits = function (props) {
    const difficulty = props.difficulty || 'beginner';
    const onAttempt = props.onAttempt || function () {};
    const onNext = props.onNext || function () {};

    const [prompt, setPrompt] = React.useState(null);
    const [input, setInput] = React.useState('');
    const [picked, setPicked] = React.useState(null);
    const [playing, setPlaying] = React.useState(false);
    const submittedRef = React.useRef(false);

    React.useEffect(function () {
      const p = window.DrumsLab.theory.randomCountTarget(difficulty);
      setPrompt(p);
      setInput('');
      setPicked(null);
      submittedRef.current = false;
      const id = setTimeout(function () { play(p); }, 350);
      return function () { clearTimeout(id); };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [difficulty]);

    function play(p) {
      const data = p || prompt;
      if (!data) return;
      setPlaying(true);
      // Play twice with a short gap so the user gets a second chance.
      window.DrumsLab.audio
        .playBeat(data.beat, { bars: 2, bpm: data.beat.bpm })
        .then(function () { setPlaying(false); })
        .catch(function () { setPlaying(false); });
    }

    function handleSubmit() {
      if (picked || !prompt || submittedRef.current) return;
      const n = parseInt(input, 10);
      if (isNaN(n) || n < 0 || n > 32) return;
      submittedRef.current = true;
      setPicked(n);
      const wasCorrect = n === prompt.count;
      onAttempt({
        exerciseType: 'count_hits',
        difficulty: difficulty,
        prompt: {
          beat_id: prompt.beat.id,
          which: prompt.which,
          bpm: prompt.beat.bpm,
        },
        userAnswer: String(n),
        correctAnswer: String(prompt.count),
        wasCorrect: wasCorrect,
      });
    }

    function handleKey(e) {
      if (e.key === 'Enter') handleSubmit();
    }

    if (!prompt) return null;
    const whichLabel = PIECE_LABEL[prompt.which] || prompt.which;

    return (
      <div>
        <div style={{ fontSize: 14, color: 'oklch(45% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Count hits</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 8 }}>
          How many <span style={{ color: 'oklch(38% 0.18 25)' }}>{whichLabel}</span> hits in one bar?
        </div>
        <div style={{ fontSize: 12.5, color: 'oklch(55% 0.04 265)', marginBottom: 18 }}>The beat plays twice. Count only the {whichLabel}.</div>

        <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap', alignItems: 'center' }}>
          <button
            onClick={function () { play(); }}
            disabled={playing}
            style={{
              padding: '10px 18px',
              borderRadius: 10,
              border: '1px solid oklch(35% 0.16 265)',
              background: playing ? 'oklch(95% 0.02 265)' : 'oklch(35% 0.16 265)',
              color: playing ? 'oklch(45% 0.04 265)' : '#fff',
              fontSize: 13,
              fontWeight: 700,
              cursor: playing ? 'wait' : 'pointer',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}
          >{playing ? 'Playing…' : 'Replay'}</button>
          <span style={{ fontSize: 11.5, color: 'oklch(55% 0.04 265)' }}>{prompt.beat.bpm} BPM</span>
        </div>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 18, flexWrap: 'wrap' }}>
          <label style={{ fontSize: 13, fontWeight: 600, color: 'oklch(35% 0.04 265)' }}>Your answer:</label>
          <input
            type="number"
            min="0"
            max="32"
            value={input}
            onChange={function (e) { setInput(e.target.value); }}
            onKeyDown={handleKey}
            disabled={picked != null}
            style={{
              width: 80,
              padding: '9px 12px',
              borderRadius: 8,
              border: '1px solid oklch(85% 0.02 265)',
              fontSize: 16,
              fontWeight: 700,
              textAlign: 'center',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}
          />
          <button
            onClick={handleSubmit}
            disabled={picked != null || input === ''}
            style={{
              padding: '9px 18px',
              borderRadius: 8,
              border: 'none',
              background: (picked != null || input === '') ? 'oklch(75% 0.03 265)' : 'oklch(35% 0.16 265)',
              color: '#fff',
              fontSize: 13,
              fontWeight: 700,
              cursor: (picked != null || input === '') ? 'not-allowed' : 'pointer',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}
          >Submit</button>
        </div>

        {picked != null && (
          <>
            <div style={{ marginBottom: 14 }}>
              <window.DrumsLab.ui.BeatGrid
                beat={prompt.beat}
                emphasizeLane={prompt.which === 'kick' ? 'kick' : 'snare'}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              {picked === prompt.count ? (
                <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(35% 0.16 145)' }}>Correct — {prompt.count} {whichLabel} hits.</div>
              ) : (
                <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>Not quite — that was {prompt.count} {whichLabel} hits.</div>
              )}
              <button
                onClick={onNext}
                style={{
                  marginLeft: 'auto',
                  padding: '10px 22px',
                  borderRadius: 10,
                  border: 'none',
                  background: 'oklch(35% 0.16 265)',
                  color: '#fff',
                  fontSize: 13,
                  fontWeight: 700,
                  cursor: 'pointer',
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                }}
              >Next</button>
            </div>
          </>
        )}
      </div>
    );
  };

  window.DrumsLab.ui.ExerciseCountHits = ExerciseCountHits;
})();
