/* global React, window */
// Drums Lab — Lesson: The basic rock backbeat.
//
// Walks through the universal 4/4 backbeat one layer at a time, with a
// Play button for each layer so the user hears how it's built up. The
// running BeatGrid below shows the playhead step-by-step as the audio
// fires.

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

  function copyBeat(beat, omitLanes) {
    var omit = omitLanes || [];
    var lanes = {};
    Object.keys(beat.lanes).forEach(function (k) {
      lanes[k] = (omit.indexOf(k) === -1) ? beat.lanes[k] : [];
    });
    return { id: beat.id, label: beat.label, bpm: beat.bpm, lanes: lanes };
  }

  function laneOnly(beat, only) {
    var lanes = { kick: [], snare: [], hh: [], crash: [], tom: [] };
    lanes[only] = beat.lanes[only];
    return { id: beat.id, label: beat.label, bpm: beat.bpm, lanes: lanes };
  }

  const Layer = function (props) {
    return (
      <div style={{
        border: '1px solid oklch(92% 0.012 265)',
        borderRadius: 12,
        padding: 14,
        background: '#fff',
        marginBottom: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8, gap: 10, flexWrap: 'wrap' }}>
          <strong style={{ fontWeight: 700, fontSize: 14, color: 'oklch(20% 0.04 265)' }}>{props.title}</strong>
          <button onClick={props.onPlay} style={{
            padding: '7px 14px',
            borderRadius: 999,
            border: '1px solid oklch(35% 0.16 265)',
            background: 'oklch(35% 0.16 265)',
            color: '#fff',
            fontSize: 12,
            fontWeight: 700,
            cursor: 'pointer',
            fontFamily: "'Plus Jakarta Sans', sans-serif",
          }}>▶ Play 1 bar</button>
        </div>
        <div style={{ fontSize: 12.5, color: 'oklch(40% 0.04 265)', lineHeight: 1.5, marginBottom: 10 }}>{props.blurb}</div>
        <window.DrumsLab.ui.BeatGrid beat={props.beat} compact />
      </div>
    );
  };

  const LessonBasicBeat = function () {
    const theory = window.DrumsLab.theory;
    const baseBeat = theory.BEAT_PATTERNS.filter(function (b) { return b.id === 'rock_basic'; })[0];
    const [playheadStep, setPlayheadStep] = React.useState(null);
    const playheadInterval = React.useRef(null);

    function clearPlayhead() {
      if (playheadInterval.current) {
        clearInterval(playheadInterval.current);
        playheadInterval.current = null;
      }
      setPlayheadStep(null);
    }

    function playWithHead(beat, bars) {
      clearPlayhead();
      const bpm = beat.bpm || 100;
      const stepMs = (60 / bpm) / 4 * 1000;
      const totalSteps = (bars || 1) * 16;
      let i = 0;
      setPlayheadStep(0);
      playheadInterval.current = setInterval(function () {
        i += 1;
        if (i >= totalSteps) {
          clearPlayhead();
          return;
        }
        setPlayheadStep(i % 16);
      }, stepMs);
      window.DrumsLab.audio.playBeat(beat, { bars: bars || 1, bpm: bpm })
        .then(function () { /* clearPlayhead via interval timeout */ })
        .catch(function () { clearPlayhead(); });
    }

    React.useEffect(function () { return clearPlayhead; }, []);

    return (
      <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
        <h2 style={{ fontSize: 22, fontWeight: 700, color: 'oklch(18% 0.03 265)', margin: '0 0 8px' }}>The basic rock beat</h2>
        <p style={{ fontSize: 14.5, color: 'oklch(40% 0.04 265)', margin: '0 0 18px', lineHeight: 1.55, maxWidth: 720 }}>
          Almost every pop, rock, and hip-hop song uses some version of the same 4/4 backbeat. Build it up one layer at a time — hi-hat → kick → snare — and you can play 80% of recorded music.
        </p>

        <Layer
          title="Step 1 — Hi-hat on every eighth note"
          blurb='Right hand ticks evenly: "one and, two and, three and, four and." This is the train track that holds the groove together.'
          beat={laneOnly(baseBeat, 'hh')}
          onPlay={function () { playWithHead(laneOnly(baseBeat, 'hh'), 1); }}
        />

        <Layer
          title="Step 2 — Add kick on 1 and 3"
          blurb='Right foot hits beat 1 and beat 3 — the BIG downbeats. Don’t look at the foot, feel it: "ONE and two and THREE and four and."'
          beat={copyBeat(baseBeat, ['snare', 'crash', 'tom'])}
          onPlay={function () { playWithHead(copyBeat(baseBeat, ['snare', 'crash', 'tom']), 1); }}
        />

        <Layer
          title="Step 3 — Add snare on 2 and 4"
          blurb='Left hand hits beat 2 and beat 4 — the BACKBEAT. This is the "bap" of "boom-bap." When a crowd claps along, this is where they clap.'
          beat={copyBeat(baseBeat, ['crash', 'tom'])}
          onPlay={function () { playWithHead(copyBeat(baseBeat, ['crash', 'tom']), 1); }}
        />

        <div style={{
          border: '1px solid oklch(85% 0.06 145)',
          borderRadius: 12,
          padding: 14,
          background: 'oklch(96% 0.04 145)',
          marginTop: 18,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8, gap: 10, flexWrap: 'wrap' }}>
            <strong style={{ fontWeight: 700, fontSize: 14, color: 'oklch(22% 0.14 145)' }}>Step 4 — Put it together (2 bars)</strong>
            <button onClick={function () { playWithHead(copyBeat(baseBeat, ['crash', 'tom']), 2); }} style={{
              padding: '7px 14px',
              borderRadius: 999,
              border: '1px solid oklch(28% 0.14 145)',
              background: 'oklch(28% 0.14 145)',
              color: '#fff',
              fontSize: 12,
              fontWeight: 700,
              cursor: 'pointer',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}>▶ Play 2 bars</button>
          </div>
          <div style={{ fontSize: 12.5, color: 'oklch(28% 0.1 145)', lineHeight: 1.5, marginBottom: 10 }}>
            Hi-hat eighth notes + kick on 1, 3 + snare on 2, 4. Every limb has a job. Watch the highlighted step to see where the groove is in time.
          </div>
          <window.DrumsLab.ui.BeatGrid
            beat={copyBeat(baseBeat, ['crash', 'tom'])}
            playheadStep={playheadStep}
          />
        </div>
      </div>
    );
  };

  window.DrumsLab.ui.LessonBasicBeat = LessonBasicBeat;
})();
