// atelier-screens-i.jsx — Drill screens (Block C, slices C.1 + C.2).
//
// DrillsHubScreen     — /#drills          — four-card grid
// DrillSessionScreen  — /#drill:<drillId> — 20 questions per session
//
// Per the design-review revision: NO green flash, NO auto-advance.
// After each answer the question dims and a brass mark appears; the
// learner taps "Next" to proceed. Time per question is recorded
// (via /api/attempt durationMs) but never surfaced as an avg.

const { useState: useSI, useEffect: useEI, useMemo: useMI, useRef: useRI } = React;

const DRILL_META = {
  'square-color':  { name: 'Square colour',  prompt: (q) => 'Is ' + q.square.toUpperCase() + ' a light or dark square?' },
  'coordinate':    { name: 'Coordinate',     prompt: (q) => 'What square is ' + q.dist + ' ' + q.dir + ' of ' + q.start.toUpperCase() + '?' },
  'diagonal':      { name: 'Diagonal',       prompt: (q) => 'Which a1-h8 diagonal does ' + q.square.toUpperCase() + ' sit on? (Give the bottom-left square.)' },
  'knight-vision': { name: 'Knight vision',  prompt: (q) => 'From ' + q.from.toUpperCase() + ', can a knight reach ' + q.to.toUpperCase() + ' in one move?' },
};
const DRILL_ORDER = ['square-color', 'coordinate', 'diagonal', 'knight-vision'];
const SESSION_LEN = 20;

let _drillCache = null;
async function loadDrills() {
  if (_drillCache) return _drillCache;
  try {
    const res = await fetch('/drills.json', { credentials: 'same-origin' });
    if (!res.ok) return null;
    _drillCache = await res.json();
    return _drillCache;
  } catch (_) { return null; }
}

// === Drills hub ============================================================
function DrillsHubScreen({ palette, setRoute }) {
  const C = palette;
  const isMobile = window.useBreakpoint().isMobile;
  const [drills, setDrills] = useSI(null);

  useEI(() => {
    let cancelled = false;
    loadDrills().then((d) => { if (!cancelled) setDrills(d); });
    return () => { cancelled = true; };
  }, []);

  return (
    <div style={{ flex: 1, height: '100%', overflow: 'auto', background: C.bone }}>
      <section className="atelier-section-pad" style={{ padding: isMobile ? '40px 20px 12px' : '56px 48px 12px' }}>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase', opacity: 0.55, color: C.umberSoft, marginBottom: 8,
        }}>Geometry warm-ups</div>
        <h1 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: isMobile ? 36 : 48, lineHeight: 1.05, color: C.umber, letterSpacing: -0.5,
        }}>Drills.</h1>
        <p style={{ marginTop: 14, fontFamily: window.ATELIER_TYPE.display, fontSize: 17, lineHeight: 1.5, color: C.umberSoft, maxWidth: 600 }}>
          Short reps that build the muscle of reading the board. Each session is twenty questions. There's no clock.
        </p>
      </section>

      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 48px' : '32px 48px 56px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 18 }}>
          {DRILL_ORDER.map((id) => {
            const meta = DRILL_META[id];
            const count = drills && drills.drills && drills.drills[id] ? drills.drills[id].length : 0;
            return (
              <button
                key={id}
                onClick={() => setRoute('drill:' + id)}
                disabled={!count}
                style={{
                  appearance: 'none', textAlign: 'left', cursor: count ? 'pointer' : 'default',
                  background: C.cream, border: '0.6px solid ' + C.umberHair, borderRadius: 14,
                  padding: 22, fontFamily: 'inherit',
                  opacity: count ? 1 : 0.5,
                  boxShadow: '0 14px 28px -22px rgba(42,34,27,0.35)',
                  transition: 'border-color 220ms ' + window.ATELIER_EASE,
                }}
                onMouseEnter={(e) => { if (count) e.currentTarget.style.borderColor = C.brassDeep; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = C.umberHair; }}
              >
                <div style={{
                  fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', fontWeight: 300,
                  fontSize: 22, color: C.umber, letterSpacing: -0.2, lineHeight: 1.15,
                }}>{meta.name}</div>
                <div style={{
                  marginTop: 10, fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 2,
                  textTransform: 'uppercase', color: C.umberFaint,
                }}>{count ? count + ' questions in the bank' : 'Loading…'}</div>
              </button>
            );
          })}
        </div>
      </section>
    </div>
  );
}

// === Drill session =========================================================
function DrillSessionScreen({ palette, setRoute, lessonId }) {
  // lessonId is the route arg — for /#drill:<drillId> it actually carries
  // the drill id. (The app.jsx route parsing sets lessonId for any
  // composite route whose screenName matches a known lesson screen; we
  // pass it through here as the drill id.) Pulls the drill id from
  // window.location.hash as a fallback in case of confusion.
  const drillId = useMI(() => {
    if (lessonId) return lessonId;
    const m = (window.location.hash || '').match(/^#drill:([\w-]+)/);
    return m ? m[1] : null;
  }, [lessonId]);

  const C = palette;
  const isMobile = window.useBreakpoint().isMobile;
  const [drills, setDrills] = useSI(null);
  const [questions, setQuestions] = useSI(null);
  const [idx, setIdx] = useSI(0);
  const [answered, setAnswered] = useSI(null);  // null = not yet; otherwise the picked answer
  const [results, setResults] = useSI([]);      // array of { question, picked, correct }
  const [finished, setFinished] = useSI(false);
  const questionStartRef = useRI(Date.now());

  useEI(() => {
    let cancelled = false;
    loadDrills().then((d) => {
      if (cancelled) return;
      setDrills(d);
      if (d && d.drills && d.drills[drillId]) {
        // Draw SESSION_LEN at random.
        const bank = d.drills[drillId];
        const shuffled = bank.slice().sort(() => Math.random() - 0.5);
        setQuestions(shuffled.slice(0, Math.min(SESSION_LEN, bank.length)));
      }
    });
    return () => { cancelled = true; };
  }, [drillId]);

  function handleAnswer(picked, q) {
    if (answered !== null) return;
    setAnswered(picked);
    const correct = isCorrect(drillId, q, picked);
    const next = [...results, { question: q, picked, correct, ms: Date.now() - questionStartRef.current }];
    setResults(next);
    if (window.DataLayer && window.DataLayer.recordAttempt) {
      window.DataLayer.recordAttempt({
        // Drill rows live in their own column; the API treats
        // drill:* phases specially.
        drillQuestionId: q.id,
        phase: 'drill:' + drillId,
        outcome: correct ? 'correct' : 'wrong',
        attemptsCount: 1,
        durationMs: Date.now() - questionStartRef.current,
      });
    }
  }

  function handleNext() {
    if (idx + 1 >= (questions ? questions.length : 0)) {
      setFinished(true);
      return;
    }
    setIdx(idx + 1);
    setAnswered(null);
    questionStartRef.current = Date.now();
  }

  if (!drills) {
    return <div style={{ flex: 1, padding: 48, color: C.umberSoft, fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic' }}>Loading…</div>;
  }
  if (!questions || !questions.length) {
    return (
      <div style={{ flex: 1, padding: 48 }}>
        <h2 style={{ fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', color: C.umber }}>Drill not found.</h2>
        <button style={window.ghostBtn(C)} onClick={() => setRoute('drills')}>Back to drills</button>
      </div>
    );
  }
  if (finished) {
    return <DrillResults palette={C} drillId={drillId} results={results} setRoute={setRoute} isMobile={isMobile} />;
  }

  const q = questions[idx];
  const meta = DRILL_META[drillId];
  const prompt = meta ? meta.prompt(q) : '';
  const correct = answered !== null ? isCorrect(drillId, q, answered) : null;

  return (
    <div style={{ flex: 1, height: '100%', overflow: 'auto', background: C.bone }}>
      <section className="atelier-section-pad" style={{ padding: isMobile ? '32px 20px 12px' : '48px 48px 12px' }}>
        <button
          onClick={() => setRoute('drills')}
          style={{
            appearance: 'none', background: 'transparent', border: 'none', padding: 0,
            cursor: 'pointer', marginBottom: 18,
            fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
            textTransform: 'uppercase', color: C.umberSoft, opacity: 0.7,
          }}
        >← Back to drills</button>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase', opacity: 0.55, color: C.umberSoft, marginBottom: 8,
        }}>{(meta && meta.name) || drillId} · {idx + 1} of {questions.length}</div>
        <h2 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: isMobile ? 26 : 34, lineHeight: 1.2, color: C.umber, letterSpacing: -0.3,
        }}>{prompt}</h2>
      </section>

      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 24px' : '32px 48px 32px' }}>
        <AnswerInputs
          palette={C}
          drillId={drillId}
          question={q}
          answered={answered}
          onAnswer={(picked) => handleAnswer(picked, q)}
        />
      </section>

      {answered !== null && (
        <section className="atelier-section-pad" style={{ padding: isMobile ? '0 20px 48px' : '0 48px 56px' }}>
          <div style={{
            padding: '14px 18px', borderRadius: 12,
            background: correct ? window.withAlpha(C.celadon || '#8FA391', 0.18)
                                : window.withAlpha(C.sienna || '#C97B5F', 0.14),
            border: '0.6px solid ' + (correct ? (C.sage || '#8FA391') : (C.sienna || '#C97B5F')),
            marginBottom: 16,
          }}>
            <div style={{
              fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic',
              fontSize: 16, color: C.umber,
            }}>
              {correct ? 'Yes.' : 'No — the answer is ' + formatAnswer(drillId, q) + '.'}
            </div>
          </div>
          <button
            onClick={handleNext}
            style={{ ...window.primaryBtn(C) }}
          >
            {idx + 1 >= questions.length ? 'See results' : 'Next'}
          </button>
        </section>
      )}
    </div>
  );
}

function AnswerInputs({ palette, drillId, question, answered, onAnswer }) {
  const C = palette;
  if (drillId === 'square-color') {
    return <BinaryButtons palette={C} answered={answered} labels={['Light', 'Dark']} values={['light', 'dark']} onAnswer={onAnswer} />;
  }
  if (drillId === 'knight-vision') {
    return <BinaryButtons palette={C} answered={answered} labels={['Yes, in one', 'No']} values={[true, false]} onAnswer={onAnswer} />;
  }
  // coordinate + diagonal: text-square input (8x8 grid).
  return <SquareGrid palette={C} answered={answered} correctSquare={question.answer} onAnswer={onAnswer} />;
}

function BinaryButtons({ palette, answered, labels, values, onAnswer }) {
  const C = palette;
  return (
    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
      {values.map((v, i) => {
        const picked = answered !== null && answered === v;
        return (
          <button
            key={String(v)}
            onClick={() => onAnswer(v)}
            disabled={answered !== null}
            style={{
              appearance: 'none', cursor: answered !== null ? 'default' : 'pointer',
              padding: '14px 28px', borderRadius: 10,
              border: '0.6px solid ' + (picked ? C.brassDeep : C.umberHair),
              background: picked ? window.withAlpha(C.brass, 0.12) : C.cream,
              color: C.umber,
              fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', fontSize: 18,
              transition: 'all 200ms ' + window.ATELIER_EASE,
            }}
          >{labels[i]}</button>
        );
      })}
    </div>
  );
}

function SquareGrid({ palette, answered, correctSquare, onAnswer }) {
  const C = palette;
  const FILES = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
  const RANKS = ['8', '7', '6', '5', '4', '3', '2', '1'];  // top → bottom
  return (
    <div style={{ maxWidth: 360, display: 'inline-block' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 2,
        border: '0.6px solid ' + C.umberHair, padding: 4, borderRadius: 8,
        background: C.cream,
      }}>
        {RANKS.map((r) => FILES.map((f) => {
          const s = f + r;
          const isDark = (FILES.indexOf(f) + RANKS.indexOf(r)) % 2 === 1;
          const picked = answered === s;
          const isCorrectHere = s === correctSquare;
          const showMark = answered !== null && (picked || isCorrectHere);
          return (
            <button
              key={s}
              onClick={() => onAnswer(s)}
              disabled={answered !== null}
              style={{
                appearance: 'none', cursor: answered !== null ? 'default' : 'pointer',
                aspectRatio: '1 / 1',
                background: showMark
                  ? (isCorrectHere ? window.withAlpha(C.celadon || '#8FA391', 0.4)
                                    : window.withAlpha(C.sienna || '#C97B5F', 0.3))
                  : (isDark ? '#B7B4AD' : '#E7E5E0'),
                border: '0.6px solid ' + (picked ? C.brassDeep : 'transparent'),
                borderRadius: 4,
                fontFamily: window.ATELIER_TYPE.ui, fontSize: 9,
                letterSpacing: 0.5,
                color: showMark ? C.umber : (isDark ? '#5b574f' : '#857f73'),
                transition: 'background 200ms ' + window.ATELIER_EASE,
              }}
            >{s.toUpperCase()}</button>
          );
        }))}
      </div>
    </div>
  );
}

function DrillResults({ palette, drillId, results, setRoute, isMobile }) {
  const C = palette;
  const correctCount = results.filter((r) => r.correct).length;
  const meta = DRILL_META[drillId];
  const wrong = results.filter((r) => !r.correct);

  return (
    <div style={{ flex: 1, height: '100%', overflow: 'auto', background: C.bone }}>
      <section className="atelier-section-pad" style={{ padding: isMobile ? '48px 20px 16px' : '64px 48px 16px' }}>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase', opacity: 0.55, color: C.umberSoft, marginBottom: 8,
        }}>{(meta && meta.name) || drillId}</div>
        <h1 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: isMobile ? 36 : 48, lineHeight: 1.05, color: C.umber, letterSpacing: -0.5,
        }}>{correctCount} of {results.length} correct.</h1>
      </section>

      {wrong.length > 0 && (
        <section className="atelier-section-pad" style={{ padding: isMobile ? '20px 20px 16px' : '28px 48px 16px' }}>
          <h2 style={{
            margin: '0 0 12px',
            fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', fontWeight: 300,
            fontSize: 18, color: C.umberSoft,
          }}>The ones to revisit</h2>
          {wrong.map((r, i) => (
            <div key={i} style={{
              padding: '10px 0', borderBottom: '0.6px solid ' + C.umberHair,
              display: 'flex', justifyContent: 'space-between', gap: 12,
              fontFamily: window.ATELIER_TYPE.display, fontSize: 14, color: C.umberSoft,
            }}>
              <div style={{ flex: 1 }}>{(meta && meta.prompt(r.question)) || ''}</div>
              <div style={{ color: C.umberFaint }}>{formatAnswer(drillId, r.question)}</div>
            </div>
          ))}
        </section>
      )}

      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 48px' : '32px 48px 56px' }}>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button style={window.ghostBtn(C)} onClick={() => setRoute('drills')}>Back to drills</button>
          <button style={window.ghostBtn(C)} onClick={() => setRoute('home')}>Go to a lesson</button>
        </div>
      </section>
    </div>
  );
}

function isCorrect(drillId, q, picked) {
  if (drillId === 'square-color')  return picked === q.answer;
  if (drillId === 'knight-vision') return picked === q.answer;
  // coordinate + diagonal: square answer
  return picked === q.answer;
}
function formatAnswer(drillId, q) {
  if (drillId === 'square-color')  return q.answer;
  if (drillId === 'knight-vision') return q.answer ? 'yes' : 'no';
  return q.answer.toUpperCase();
}

Object.assign(window, { DrillsHubScreen, DrillSessionScreen });
