// atelier-screens-j.jsx — TrainerScreen (Block D, slice D.6).
//
// 5-rung hint ladder for a stuck lesson. Reachable only via the
// /#trainer:<lessonId> deep link (no toggle on the regular lesson
// screen, per the design-review revision: hints stay a deliberate
// destination, not the path of least resistance).
//
// Rungs are derived procedurally from lesson facts that are already
// engine-vetted (heroPiece, theme, hero square, target via
// A_TRAJECTORIES[hero][1]). No new tactical claims — pure restatement.

const { useState: useSJ, useEffect: useEJ, useMemo: useMJ } = React;

const PIECE_NAMES_J = {
  knight: 'knight', bishop: 'bishop', rook: 'rook',
  queen: 'queen', pawn: 'pawn', king: 'king',
};
const THEME_HINT = {
  'pin':               { name: 'pin',              hint: 'A pinned piece can\'t move without exposing a more valuable piece behind it.' },
  'fork':              { name: 'fork',             hint: 'One piece attacks two targets at once.' },
  'discovered-attack': { name: 'discovered attack',hint: 'Moving one piece reveals the threat of a piece sitting behind it.' },
  'skewer':            { name: 'skewer',           hint: 'A high-value piece is forced to step aside, exposing a piece behind it.' },
  'knight-endgame':    { name: 'knight endgame',   hint: 'A knight\'s short range matters most in pawn endings.' },
};

function rungsForLesson(lesson) {
  if (!lesson || !lesson.meta) return [];
  const meta = lesson.meta;
  const piece = meta.heroPiece || (lesson.heroPiece || 'piece');
  const color = meta.sideToMove === 'black' ? 'Black' : 'White';
  const heroSq = (window.A_HERO || lesson.hero || '').toUpperCase();
  const trajectories = window.A_TRAJECTORIES || (lesson.trajectories) || {};
  const target = (trajectories[(window.A_HERO || lesson.hero || '').toLowerCase()] || [])[1];
  const targetUC = target ? String(target).toUpperCase() : null;
  const themeMeta = THEME_HINT[meta.theme] || { name: meta.theme || 'tactic', hint: 'A specific motif lives on this board.' };
  const pieceName = PIECE_NAMES_J[piece] || piece;

  return [
    {
      title: 'A nudge',
      body: 'Read the position before reading any hint. Who has the move, what are the pieces under pressure, who has the long-range piece doing the most work?',
    },
    {
      title: 'The motif',
      body: 'There\'s a ' + themeMeta.name + ' here. ' + themeMeta.hint,
    },
    {
      title: 'The piece',
      body: 'The ' + color + ' ' + pieceName + ' on ' + heroSq + ' is the one to move.',
    },
    {
      title: 'The destination',
      body: targetUC
        ? 'It goes to ' + targetUC + '.'
        : 'Its best square is somewhere it activates a second threat.',
    },
    {
      title: 'The move',
      body: targetUC
        ? color + ' ' + pieceName + ' on ' + heroSq + ' moves to ' + targetUC + '.'
        : 'The full move is what the lesson reveals at the end.',
    },
  ];
}

function TrainerScreen({ palette, setRoute, lessonId }) {
  const C = palette;
  const isMobile = window.useBreakpoint().isMobile;
  const [revealedCount, setRevealedCount] = useSJ(0);
  // Reset reveal count when the lesson id changes.
  useEJ(() => { setRevealedCount(0); }, [lessonId]);

  const lesson = window.LESSON && window.LESSON.id === lessonId ? window.LESSON : null;
  const rungs = useMJ(() => rungsForLesson(lesson), [lesson]);

  if (!lesson) {
    return (
      <div style={{ flex: 1, padding: 48 }}>
        <div style={{ fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', color: C.umberSoft }}>
          Loading position…
        </div>
      </div>
    );
  }

  const visibleRungs = rungs.slice(0, revealedCount);

  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('lesson:' + lessonId)}
          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 the lesson</button>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase', opacity: 0.55, color: C.umberSoft, marginBottom: 8,
        }}>Trainer mode · {revealedCount} of {rungs.length}</div>
        <h1 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: isMobile ? 30 : 40, lineHeight: 1.05, color: C.umber, letterSpacing: -0.4,
        }}>
          {window.creativeTitle ? window.creativeTitle(lessonId) : lesson.meta.title}
        </h1>
        <p style={{ marginTop: 12, fontFamily: window.ATELIER_TYPE.display, fontSize: 15, color: C.umberSoft, maxWidth: 600 }}>
          Five small hints, in order. Each one reveals a little more. Stop as soon as you see it.
        </p>
      </section>

      {/* Board — read-only spotlight, no interaction. The lesson screen
          handles actual move attempts; trainer is a reading exercise. */}
      <section style={{ display: 'flex', justifyContent: 'center', padding: isMobile ? '8px 20px' : '16px 48px' }}>
        <div style={{ maxWidth: isMobile ? 320 : 480, width: '100%' }}>
          <window.AtelierBoard
            palette={C}
            layers={{ heatmap: false, hero: false, trajectory: false, tension: false }}
            size={isMobile ? Math.min(320, window.innerWidth - 48) : 460}
          />
        </div>
      </section>

      {/* Rung list — visible rungs first, then the next-to-reveal button */}
      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 48px' : '32px 48px 56px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 640 }}>
          {visibleRungs.map((r, i) => (
            <div key={i} style={{
              padding: '14px 18px', borderRadius: 12,
              background: C.cream,
              border: '0.6px solid ' + C.umberHair,
            }}>
              <div style={{
                fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 2,
                textTransform: 'uppercase', color: C.umberFaint, marginBottom: 6,
              }}>Hint {i + 1} · {r.title}</div>
              <div style={{
                fontFamily: window.ATELIER_TYPE.display, fontSize: 16, lineHeight: 1.55,
                color: C.umber,
              }}>{r.body}</div>
            </div>
          ))}
          {revealedCount < rungs.length ? (
            <button
              onClick={() => setRevealedCount(revealedCount + 1)}
              style={{ ...window.primaryBtn(C), alignSelf: 'flex-start' }}
            >
              {revealedCount === 0 ? 'Show me a hint' : 'Show the next hint'}
            </button>
          ) : (
            <button
              style={{ ...window.ghostBtn(C), alignSelf: 'flex-start' }}
              onClick={() => setRoute('lesson:' + lessonId)}
            >
              Back to the lesson
            </button>
          )}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { TrainerScreen });
