/* global React, window */
// Violin Lab — Exercise: tuning ear training.
//
// Plays two tones: a reference (the target open-string pitch), then a
// candidate that's either in-tune, flat, or sharp by a difficulty-
// dependent number of cents. The student decides which.

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

  const ExerciseTuning = 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.ViolinLab.theory.randomTuning(difficulty);
      setPrompt(p);
      setChoices(p.pool);
      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.ViolinLab.audio
        .playTuningPair(data.targetMidi, data.cents)
        .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: 'tuning',
        difficulty: difficulty,
        prompt: {
          string: prompt.string.id,
          target_midi: prompt.targetMidi,
          cents: prompt.cents,
        },
        userAnswer: choice.id,
        correctAnswer: prompt.correct.id,
        wasCorrect: wasCorrect,
      });
    }

    if (!prompt) return null;

    return (
      <div>
        <div style={{ fontSize: 14, color: 'oklch(45% 0.04 265)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Tune by ear</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 6 }}>Compare the two tones — is the second one in tune?</div>
        <div style={{ fontSize: 12.5, color: 'oklch(55% 0.04 265)', marginBottom: 18, lineHeight: 1.4 }}>
          You'll hear the <strong>{prompt.string.name}</strong> played twice. The first is correct. Decide if the second is flat (lower), in tune, or sharp (higher).
        </div>

        <div style={{ display: 'flex', gap: 10, marginBottom: 20, 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 both tones'}</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 10, 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: '14px 16px',
                  borderRadius: 10,
                  border: '1px solid ' + border,
                  background: bg,
                  color: color,
                  fontSize: 14,
                  fontWeight: 700,
                  cursor: picked ? 'default' : 'pointer',
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                  minHeight: 50,
                  textAlign: 'left',
                  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 — the second {prompt.string.id} was {prompt.correct.label.toLowerCase()}.
              </div>
            ) : (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>
                Not quite — the second tone was {prompt.correct.label.toLowerCase()}{prompt.cents !== 0 ? ` (by ${Math.abs(prompt.cents)} cents)` : ''}.
              </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.ViolinLab.ui.ExerciseTuning = ExerciseTuning;
})();
