/* global React, window */
// Piano Lab — Exercise: Name the highlighted key.
//
// Highlights one key on the keyboard. The user picks the letter name
// from a 7-button row (C D E F G A B). Difficulty controls whether
// black keys appear in the prompt (intermediate and above), and the
// keyboard range.

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

  const ExerciseKeyName = 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;
      // Optional: play the key once on mount so the user also hears it.
      const id = setTimeout(function () { window.PianoLab.audio.playNote(p.midi, 600); }, 250);
      return function () { clearTimeout(id); };
    }, [difficulty]);

    function submitAnswer(letter, accidental) {
      if (submittedRef.current || !prompt) return;
      submittedRef.current = true;
      setPicked({ letter: letter, accidental: accidental });
      // For black keys, accept either # spelling. Our random picker
      // always spells with #, so wasCorrect is letter+accidental match.
      const wasCorrect = (
        letter === prompt.letter
        && (prompt.isBlack ? accidental === '#' : !accidental)
      );
      onAttempt({
        exerciseType: 'key_name',
        difficulty: difficulty,
        prompt: {
          midi: prompt.midi,
          label: prompt.label,
          is_black: prompt.isBlack,
        },
        userAnswer: letter + (accidental || ''),
        correctAnswer: prompt.letter + (prompt.isBlack ? '#' : ''),
        wasCorrect: wasCorrect,
      });
    }

    function handleLetterPick(letter) {
      if (picked) return;
      // For beginner (white keys only) we submit immediately.
      // For intermediate/advanced we wait for accidental too.
      if (difficulty === 'beginner') {
        submitAnswer(letter, null);
        return;
      }
      // Stash the letter, wait for natural / sharp choice.
      setPicked({ letter: letter, accidental: 'pending' });
    }

    function handleAccidentalPick(acc) {
      if (!picked || picked.accidental !== 'pending') return;
      submitAnswer(picked.letter, acc);
    }

    if (!prompt) return null;
    const isPending = picked && picked.accidental === 'pending';
    const isAnswered = picked && picked.accidental !== 'pending';
    const correctAnswerString = prompt.letter + (prompt.isBlack ? '#' : '');
    const wasCorrect = isAnswered && (picked.letter + (picked.accidental || '')) === correctAnswerString;

    return (
      <div>
        <div style={{ fontSize: 14, color: 'oklch(45% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Name the key</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 18 }}>What is the highlighted key called?</div>

        <div style={{ marginBottom: 18 }}>
          <Keyboard
            loMidi={prompt.midi <= 60 ? 48 : 60}
            hiMidi={prompt.midi >= 72 ? 83 : 72}
            highlight={!isAnswered ? prompt.midi : null}
            correctMidi={isAnswered ? prompt.midi : null}
            disabled={true}
          />
        </div>

        {!isPending && !isAnswered && (
          <>
            <div style={{ fontSize: 11, color: 'oklch(55% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 8 }}>Pick the letter</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(80px, 1fr))', gap: 8, marginBottom: 20 }}>
              {window.PianoLab.theory.NOTE_LETTERS.map(function (L) {
                return (
                  <button
                    key={L}
                    onClick={function () { handleLetterPick(L); }}
                    style={{
                      padding: '14px 0',
                      borderRadius: 10,
                      border: '1px solid oklch(88% 0.02 265)',
                      background: '#fff',
                      color: 'oklch(20% 0.04 265)',
                      fontSize: 18, fontWeight: 700, cursor: 'pointer',
                      fontFamily: "'Plus Jakarta Sans', sans-serif",
                    }}
                  >{L}</button>
                );
              })}
            </div>
          </>
        )}

        {isPending && (
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 18 }}>
            <button
              onClick={function () { handleAccidentalPick(null); }}
              style={{
                padding: '14px 22px', borderRadius: 10,
                border: '1px solid oklch(88% 0.02 265)',
                background: '#fff', color: 'oklch(20% 0.04 265)',
                fontSize: 16, fontWeight: 700, cursor: 'pointer',
                fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}
            >{picked.letter} <span style={{ color: 'oklch(55% 0.04 265)', fontWeight: 500, fontSize: 12 }}>(white key)</span></button>
            <button
              onClick={function () { handleAccidentalPick('#'); }}
              style={{
                padding: '14px 22px', borderRadius: 10,
                border: '1px solid oklch(88% 0.02 265)',
                background: '#fff', color: 'oklch(20% 0.04 265)',
                fontSize: 16, fontWeight: 700, cursor: 'pointer',
                fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}
            >{picked.letter}♯ <span style={{ color: 'oklch(55% 0.04 265)', fontWeight: 500, fontSize: 12 }}>(black key)</span></button>
            <button
              onClick={function () { setPicked(null); }}
              style={{
                padding: '12px 18px', borderRadius: 10,
                border: '1px solid oklch(88% 0.02 265)',
                background: 'oklch(98% 0.005 265)', color: 'oklch(40% 0.04 265)',
                fontSize: 12, fontWeight: 600, cursor: 'pointer',
                fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}
            >← Pick a different letter</button>
          </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)' }}>Correct — that’s {prompt.label}.</div>
            ) : (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>Not quite — the answer was {prompt.label}.</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.ExerciseKeyName = ExerciseKeyName;
})();
