/* global React, window */
// Violin Lab — Lesson: standard tuning (G3 D4 A4 E5).
//
// Shows the 4 open strings with their MIDI / frequency / clef position,
// each with a Listen button that plays the open string through the
// Web Audio engine. Also includes a "Play all (low → high)" button
// so students can hear the characteristic G-D-A-E sweep.

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

  const LessonTuning = function () {
    const [playingId, setPlayingId] = React.useState(null);
    const [audioReady, setAudioReady] = React.useState(false);

    React.useEffect(function () {
      const id = setInterval(function () {
        try { setAudioReady(window.ViolinLab.audio.isReady()); } catch (e) {}
      }, 500);
      return function () { clearInterval(id); };
    }, []);

    const theory = window.ViolinLab.theory;
    const STRINGS = theory.STRINGS;

    function play(stringId) {
      const s = STRINGS.find(function (x) { return x.id === stringId; });
      if (!s) return;
      setPlayingId(s.id);
      window.ViolinLab.audio.playNote(s.midi, 1300).then(function () {
        setPlayingId(null);
      }).catch(function () { setPlayingId(null); });
    }

    function playAll() {
      setPlayingId('all');
      const midis = ['G', 'D', 'A', 'E'].map(function (id) {
        return STRINGS.find(function (s) { return s.id === id; }).midi;
      });
      window.ViolinLab.audio.playSequence(midis, { noteMs: 900, gapMs: 80 }).then(function () {
        setPlayingId(null);
      }).catch(function () { setPlayingId(null); });
    }

    function enableSound() {
      window.ViolinLab.audio.resumeContext();
    }

    return (
      <div>
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'oklch(18% 0.03 265)', marginBottom: 6 }}>Standard tuning</div>
          <div style={{ fontSize: 13.5, color: 'oklch(40% 0.04 265)', lineHeight: 1.5 }}>
            The four violin strings are tuned in <strong>perfect fifths</strong> — each string is exactly 7 semitones above the one below it.
            From lowest to highest: <strong>G</strong>, <strong>D</strong>, <strong>A</strong>, <strong>E</strong>.
          </div>
        </div>

        {!audioReady && (
          <div style={{
            background: 'oklch(96% 0.02 80)',
            border: '1px solid oklch(85% 0.07 80)',
            borderRadius: 10,
            padding: '10px 14px',
            marginBottom: 16,
            fontSize: 12.5,
            color: 'oklch(40% 0.05 80)',
            display: 'flex',
            alignItems: 'center',
            gap: 10,
          }}>
            <span>Tap below to enable sound (browsers require a click).</span>
            <button
              onClick={enableSound}
              style={{
                padding: '6px 12px',
                borderRadius: 8,
                border: 'none',
                background: 'oklch(35% 0.16 265)',
                color: '#fff',
                fontSize: 12,
                fontWeight: 700,
                cursor: 'pointer',
                fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}
            >Enable sound</button>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 18 }}>
          {STRINGS.map(function (s) {
            const isPlaying = playingId === s.id;
            const hz = (window.ViolinLab.audio.midiToFreq(s.midi)).toFixed(1);
            return (
              <div key={s.id} style={{
                background: '#fff',
                border: '1px solid oklch(92% 0.012 265)',
                borderRadius: 12,
                padding: '14px 16px',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <div style={{
                    width: 32,
                    height: 32,
                    borderRadius: '50%',
                    background: s.color,
                    color: '#fff',
                    fontSize: 14,
                    fontWeight: 800,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontFamily: "'Plus Jakarta Sans', sans-serif",
                  }}>{s.id}</div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(20% 0.04 265)' }}>{s.name}</div>
                    <div style={{ fontSize: 11, color: 'oklch(55% 0.04 265)' }}>{s.id}{s.octave} · {hz} Hz</div>
                  </div>
                </div>
                <button
                  onClick={function () { play(s.id); }}
                  disabled={isPlaying || playingId === 'all'}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    borderRadius: 8,
                    border: '1px solid ' + s.color,
                    background: isPlaying ? s.color : '#fff',
                    color: isPlaying ? '#fff' : s.color,
                    fontSize: 12.5,
                    fontWeight: 700,
                    cursor: isPlaying ? 'wait' : 'pointer',
                    fontFamily: "'Plus Jakarta Sans', sans-serif",
                  }}
                >{isPlaying ? 'Playing…' : 'Listen'}</button>
              </div>
            );
          })}
        </div>

        <div style={{
          background: 'oklch(96% 0.04 265)',
          border: '1px solid oklch(88% 0.05 265)',
          borderRadius: 12,
          padding: '14px 16px',
          display: 'flex',
          alignItems: 'center',
          gap: 14,
          flexWrap: 'wrap',
        }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'oklch(22% 0.06 265)', marginBottom: 2 }}>Hear all four strings</div>
            <div style={{ fontSize: 12, color: 'oklch(40% 0.04 265)' }}>Low to high (G → E). This is what your violin should sound like after tuning.</div>
          </div>
          <button
            onClick={playAll}
            disabled={playingId !== null}
            style={{
              padding: '10px 18px',
              borderRadius: 10,
              border: 'none',
              background: playingId === 'all' ? 'oklch(75% 0.03 265)' : 'oklch(35% 0.16 265)',
              color: '#fff',
              fontSize: 13,
              fontWeight: 700,
              cursor: playingId !== null ? 'wait' : 'pointer',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}
          >{playingId === 'all' ? 'Playing…' : 'Play all'}</button>
        </div>
      </div>
    );
  };

  window.ViolinLab.ui.LessonTuning = LessonTuning;
})();
