/* global React, window, Vex */
// Practice Lab — Key signature identification.
//
// Renders an empty treble staff with a key signature applied and asks
// the user to pick the key (major + relative minor on advanced).

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

  function vexAvailable() {
    // Coerce to a real boolean. Using && would return the Vex.Flow class
    // itself when truthy; React.useState(thatClass) would then INVOKE the
    // class as a lazy initializer (without `new`) and throw a class-
    // constructor error inside the component.
    return !!(typeof window.Vex !== 'undefined' && window.Vex && window.Vex.Flow);
  }

  // Convert our internal key ids ('Bb', 'F#m') to VexFlow's key strings.
  // VexFlow uses 'Bb' / 'F#m' shorthand directly so this is the identity
  // for everything in our pool, but we keep the layer for safety in case
  // we ever expand to enharmonic spellings.
  function vexKeySpec(id) {
    return id;
  }

  function renderKeySig(containerEl, keyId) {
    if (!vexAvailable() || !containerEl) return;
    containerEl.innerHTML = '';
    try {
      const VF = window.Vex.Flow;
      const width = 280;
      const height = 130;
      const renderer = new VF.Renderer(containerEl, VF.Renderer.Backends.SVG);
      renderer.resize(width, height);
      const ctx = renderer.getContext();
      ctx.setFont('Plus Jakarta Sans', 11);
      const stave = new VF.Stave(10, 12, width - 20);
      stave.addClef('treble');
      stave.addKeySignature(vexKeySpec(keyId));
      stave.setContext(ctx).draw();
    } catch (e) {
      // Same precaution as exercise-note-staff: never leak the answer
      // through a render-failure fallback.
      try {
        containerEl.textContent = 'Staff failed to render — pick Next for a new question.';
        containerEl.style.padding = '24px';
        containerEl.style.textAlign = 'center';
        containerEl.style.color = '#999';
        containerEl.style.fontSize = '13px';
      } catch (e2) {}
    }
  }

  const ExerciseKeySignature = 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 [vexReady, setVexReady] = React.useState(vexAvailable());
    const staffRef = React.useRef(null);
    const submittedRef = React.useRef(false);

    React.useEffect(function () {
      if (vexReady) return;
      const id = setInterval(function () {
        if (vexAvailable()) { setVexReady(true); clearInterval(id); }
      }, 100);
      return function () { clearInterval(id); };
    }, [vexReady]);

    React.useEffect(function () {
      const p = window.PracticeLab.theory.randomKeySignature(difficulty);
      const count = difficulty === 'advanced' ? 6 : 4;
      const c = window.PracticeLab.theory.choicesFor(p.correct, p.pool, count);
      setPrompt(p);
      setChoices(c);
      setPicked(null);
      submittedRef.current = false;
    }, [difficulty]);

    React.useEffect(function () {
      if (!prompt || !vexReady || !staffRef.current) return;
      renderKeySig(staffRef.current, prompt.correct.id);
    }, [prompt, vexReady]);

    function handlePick(choice) {
      if (picked || !prompt || submittedRef.current) return;
      submittedRef.current = true;
      setPicked(choice);
      const wasCorrect = choice.id === prompt.correct.id;
      onAttempt({
        exerciseType: 'key_signature',
        difficulty: difficulty,
        prompt: {
          key_id: prompt.correct.id,
          accidental_type: prompt.correct.type,
          accidental_count: prompt.correct.count,
        },
        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 }}>Key signature</div>
        <div style={{ fontSize: 18, color: 'oklch(20% 0.04 265)', fontWeight: 600, marginBottom: 18 }}>Which key signature is this?</div>

        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
          <div ref={staffRef} style={{
            background: '#fff',
            border: '1px solid oklch(92% 0.012 265)',
            borderRadius: 8,
            padding: 6,
            minHeight: 130,
            minWidth: 280,
            overflow: 'hidden',
          }}>
            {!vexReady && <div style={{ padding: 30, color: 'oklch(55% 0.04 265)', fontSize: 12 }}>Loading staff…</div>}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 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: 600,
                  cursor: picked ? 'default' : 'pointer',
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                  minHeight: 50,
                  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 — that’s {prompt.correct.label}.</div>
            ) : (
              <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(38% 0.18 25)' }}>Not quite — the answer was {prompt.correct.label} ({prompt.correct.count} {prompt.correct.type}{prompt.correct.count === 1 ? '' : 's'}).</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.PracticeLab.ui.ExerciseKeySignature = ExerciseKeySignature;
})();
