/* global React, window */
// Piano Lab — Exercise: Hear a note, click the key.
//
// Plays a single note and asks the user to click the matching key on
// the keyboard.

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

  const ExerciseNoteByEar = function (props) {
    const Keyboard = window.PianoLab.ui.Keyboard;
    const difficulty = props.difficulty || 'beginner';
    const onAttempt = props.onAttempt || function () {};
    const onNext = props.onNext || function () {};

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

    React.useEffect(function () {
      const p = window.PianoLab.theory.randomNoteForEar(difficulty);
      setPrompt(p);
      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);
      window.PianoLab.audio
        .playNote(data.midi, 900)
        .then(function () { setPlaying(false); })
        .catch(function () { setPlaying(false); });
    }

    function handleKey(midi) {
      if (submittedRef.current || !prompt) return;
      submittedRef.current = true;
      setPicked(midi);
      const wasCorrect = midi === prompt.midi;
      // Play whichever key the user picked so they can compare.
      window.PianoLab.audio.playNote(midi, 600);
      onAttempt({
        exerciseType: 'note_by_ear',
        difficulty: difficulty,
        prompt: {
          target_midi: prompt.midi,
          target_label: prompt.label,
        },
        userAnswer: String(midi),
        correctAnswer: String(prompt.midi),
        wasCorrect: wasCorrect,
      });
    }

    if (!prompt) return null;
    const isAnswered = picked != null;
    const wasCorrect = isAnswered && picked === prompt.midi;

    return (
      <div>
        <div style={{ fontSize: 14, color: 'oklch(45% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Note by ear</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 18 }}>Click the key that matches the note you hear.</div>

        <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
          <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 sound'}</button>
        </div>

        <div style={{ marginBottom: 18 }}>
          <Keyboard
            loMidi={prompt.range.lo}
            hiMidi={prompt.range.hi}
            onKey={isAnswered ? null : handleKey}
            correctMidi={isAnswered ? prompt.midi : null}
            wrongMidi={isAnswered && !wasCorrect ? picked : null}
            disabled={isAnswered}
          />
        </div>

        {isAnswered && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            {wasCorrect ? (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(35% 0.16 145)' }}>Spot on — that was {prompt.label}.</div>
            ) : (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>Close — the note was {prompt.label} (now outlined in green).</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.PianoLab.ui.ExerciseNoteByEar = ExerciseNoteByEar;
})();
