/* global React, window */
// Guitar Lab — Fret-note exercise.
//
// Mark a single fret on the fretboard with a "?". The user picks the
// note name (C, C#, D, etc.) from the chromatic answer grid.

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

  const STRING_NAMES = ['Low E', 'A', 'D', 'G', 'B', 'High E'];

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

    const [prompt, setPrompt] = React.useState(null);
    const [choices, setChoices] = 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.GuitarLab.theory.randomFretNote(difficulty);
      // Use the whole pool as the choices (7 naturals for beginner, 12
      // chromatic for harder). No further sampling.
      setPrompt(p);
      setChoices(p.pool);
      setPicked(null);
      submittedRef.current = false;
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [difficulty]);

    function playFret() {
      if (!prompt) return;
      setPlaying(true);
      window.GuitarLab.audio.playNote(prompt.midi, 1200)
        .then(function () { setPlaying(false); })
        .catch(function () { setPlaying(false); });
    }

    function handlePick(choice) {
      if (picked || !prompt || submittedRef.current) return;
      submittedRef.current = true;
      setPicked(choice);
      const wasCorrect = choice.id === prompt.correct.id;
      onAttempt({
        exerciseType: 'fret_note',
        difficulty: difficulty,
        prompt: { string_index: prompt.stringIndex, fret: prompt.fret, midi: prompt.midi },
        userAnswer: choice.id,
        correctAnswer: prompt.correct.id,
        wasCorrect: wasCorrect,
      });
    }

    if (!prompt) return null;
    const Fretboard = window.GuitarLab.ui.Fretboard;
    const highlight = {
      stringIndex: prompt.stringIndex,
      fret: prompt.fret,
      label: picked ? prompt.correct.label : '?',
      color: 'oklch(50% 0.2 50)',
    };
    const maxFret = difficulty === 'beginner' ? 5 : (difficulty === 'intermediate' ? 8 : 12);

    return (
      <div>
        <div style={{ fontSize: 14, color: 'oklch(45% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Fret note</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 8 }}>What note is the highlighted fret?</div>
        <div style={{ fontSize: 13, color: 'oklch(50% 0.04 265)', marginBottom: 16 }}>
          {STRING_NAMES[prompt.stringIndex]} string · fret {prompt.fret}
        </div>

        <div style={{ background: 'oklch(98% 0.005 265)', border: '1px solid oklch(92% 0.012 265)', borderRadius: 12, padding: 14, marginBottom: 14 }}>
          {Fretboard && <Fretboard frets={maxFret} highlight={highlight} width={560} />}
        </div>

        <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
          <button
            onClick={playFret}
            disabled={playing}
            style={{
              padding: '8px 14px',
              borderRadius: 999,
              border: '1px solid oklch(35% 0.16 265)',
              background: playing ? 'oklch(95% 0.02 265)' : '#fff',
              color: playing ? 'oklch(45% 0.04 265)' : 'oklch(28% 0.1 265)',
              fontSize: 12,
              fontWeight: 700,
              cursor: playing ? 'wait' : 'pointer',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}
          >{playing ? 'Playing…' : '▶ Hear it'}</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(70px, 1fr))', gap: 8, marginBottom: 20 }}>
          {choices.map(function (c) {
            const isPicked = picked && picked.id === c.id;
            const isCorrect = c.id === prompt.correct.id;
            let bg = '#fff';
            let border = 'oklch(88% 0.02 265)';
            let color = 'oklch(20% 0.04 265)';
            if (picked) {
              if (isCorrect) { bg = 'oklch(94% 0.07 145)'; border = 'oklch(60% 0.16 145)'; color = 'oklch(28% 0.14 145)'; }
              else if (isPicked) { bg = 'oklch(95% 0.07 25)'; border = 'oklch(60% 0.18 25)'; color = 'oklch(32% 0.16 25)'; }
              else { bg = 'oklch(98% 0.005 265)'; color = 'oklch(55% 0.04 265)'; }
            }
            return (
              <button
                key={c.id}
                onClick={function () { handlePick(c); }}
                disabled={!!picked}
                style={{
                  padding: '12px 8px',
                  borderRadius: 10,
                  border: '1px solid ' + border,
                  background: bg,
                  color: color,
                  fontSize: 14,
                  fontWeight: 700,
                  cursor: picked ? 'default' : 'pointer',
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                  textAlign: 'center',
                  transition: 'all 0.14s',
                }}
              >{c.label}</button>
            );
          })}
        </div>

        {picked && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            {picked.id === prompt.correct.id ? (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(35% 0.16 145)' }}>Correct — fret {prompt.fret} on the {STRING_NAMES[prompt.stringIndex]} string is {prompt.correct.label}.</div>
            ) : (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>Not quite — that's {prompt.correct.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.GuitarLab.ui.ExerciseFretNote = ExerciseFretNote;
})();
