/* global React, window */
// Piano Lab — Exercise: Find the named key.
//
// Inverse of exercise-key-name. The user is shown a letter (e.g. "F#4")
// and must click that key on the keyboard.

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

  const ExerciseFindKey = 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 submittedRef = React.useRef(false);

    React.useEffect(function () {
      const p = window.PianoLab.theory.randomKey(difficulty);
      setPrompt(p);
      setPicked(null);
      submittedRef.current = false;
    }, [difficulty]);

    function handleKey(midi) {
      if (submittedRef.current || !prompt) return;
      submittedRef.current = true;
      setPicked(midi);
      const wasCorrect = midi === prompt.midi;
      // Play the clicked key so the user hears feedback.
      window.PianoLab.audio.playNote(midi, 600);
      onAttempt({
        exerciseType: 'find_key',
        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;
    const r = window.PianoLab.theory.rangeFor(difficulty);

    return (
      <div>
        <div style={{ fontSize: 14, color: 'oklch(45% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Find the key</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 18 }}>
          Click the key called <span style={{ display: 'inline-block', padding: '4px 12px', borderRadius: 8, background: 'oklch(96% 0.04 80)', color: 'oklch(28% 0.14 80)', fontWeight: 800, marginLeft: 4 }}>{prompt.label}</span>
        </div>

        <div style={{ marginBottom: 18 }}>
          <Keyboard
            loMidi={r.lo}
            hiMidi={r.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)' }}>Nice — that’s {prompt.label}.</div>
            ) : (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>Not quite — {prompt.label} is the key 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.ExerciseFindKey = ExerciseFindKey;
})();
