// atelier-screens-d.jsx — Attack Vectors study room.
//
// Reads window.LESSON.attackVectors (computed by tools/attack-vectors.js)
// and draws arrows + battery lines + mating-net glow on the board. Three-
// column layout matches Tension and Targets.
//
// Per INV-001: copy is plain. Per INV-005: this room visualizes existing
// computed facts (attacker/defender geometry), not generated tactical claims.

const { useState: useAV, useEffect: useAVE, useMemo: useAVM } = React;

const VEC_TONE = {
  convergent_attack: 'sienna',
  battery: 'brass',
  mating_net_candidate: 'terracotta',
};

const VEC_LABELS = {
  convergent_attack: 'Convergent',
  battery: 'Battery',
  mating_net_candidate: 'Mating net',
};

const PIECE_TO_GLYPH_D = {
  wP: '♙', wN: '♘', wB: '♗', wR: '♖', wQ: '♕', wK: '♔',
  bP: '♟', bN: '♞', bB: '♝', bR: '♜', bQ: '♛', bK: '♚',
};

function sqToXY(sq, sqPx) {
  const file = sq.charCodeAt(0) - 'a'.charCodeAt(0);
  const rank = 8 - parseInt(sq[1], 10);
  return { x: file * sqPx + sqPx / 2, y: rank * sqPx + sqPx / 2 };
}

// ── Board overlay ─────────────────────────────────────────────────────
function AttackVectorOverlay({ palette, position, vectors, focusVec, hoverVec, size = 520 }) {
  const C = palette;
  const SQ = size / 8;
  const focusOrHover = hoverVec || focusVec;

  // Only render arrows for active items (focused/hovered) to keep the board
  // legible. The selected item gets full opacity; nothing else draws.
  const active = focusOrHover ? [focusOrHover] : vectors;
  const showFaded = !focusOrHover; // when nothing selected, draw all but faded

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      <defs>
        <marker id="arr-sienna" markerWidth="10" markerHeight="10" refX="8" refY="5" orient="auto">
          <polygon points="0,0 10,5 0,10" fill={C.sienna} />
        </marker>
        <marker id="arr-brass" markerWidth="10" markerHeight="10" refX="8" refY="5" orient="auto">
          <polygon points="0,0 10,5 0,10" fill={C.brass || C.umber} />
        </marker>
        <marker id="arr-terracotta" markerWidth="10" markerHeight="10" refX="8" refY="5" orient="auto">
          <polygon points="0,0 10,5 0,10" fill={C.terracotta || C.sienna} />
        </marker>
      </defs>

      {/* Squares */}
      {[...Array(8)].flatMap((_, rank) => [...Array(8)].map((__, file) => {
        const sq = 'abcdefgh'[file] + (8 - rank);
        const isLight = (file + rank) % 2 === 0;
        return (
          <rect key={sq}
            x={file * SQ} y={rank * SQ}
            width={SQ} height={SQ}
            fill={isLight ? C.squareLight : C.squareDark || C.boneDeep}
          />
        );
      }))}

      {/* Pieces */}
      {Object.entries(position).map(([sq, code]) => {
        const { x, y } = sqToXY(sq, SQ);
        return (
          <text key={'p-' + sq}
            x={x} y={y + SQ * 0.32}
            fontSize={SQ * 0.82}
            textAnchor="middle"
            fontFamily='"Noto Sans Symbols 2","Segoe UI Symbol",sans-serif'
            fill={code[0] === 'w' ? C.umber : C.umberSoft}
            pointerEvents="none"
          >{PIECE_TO_GLYPH_D[code] || '?'}</text>
        );
      })}

      {/* Vector lines */}
      {active.map((v, i) => drawVector(v, C, SQ, showFaded ? 0.35 : 1, i))}
    </svg>
  );
}

function drawVector(v, C, SQ, opacity, key) {
  const tone = VEC_TONE[v.type] || 'sienna';
  const stroke = C[tone] || C.umber;
  const markerId = `arr-${tone}`;

  if (v.type === 'convergent_attack') {
    const target = sqToXY(v.target, SQ);
    return v.attackers.map((a, j) => {
      const from = sqToXY(a.from, SQ);
      return (
        <line key={`cv-${key}-${j}`}
          x1={from.x} y1={from.y} x2={target.x} y2={target.y}
          stroke={stroke} strokeWidth={2} opacity={opacity}
          markerEnd={`url(#${markerId})`} strokeLinecap="round"
        />
      );
    });
  }
  if (v.type === 'battery') {
    const rear = sqToXY(v.rear, SQ);
    const front = sqToXY(v.front, SQ);
    const target = sqToXY(v.target, SQ);
    return (
      <g key={`bat-${key}`}>
        <line x1={rear.x} y1={rear.y} x2={front.x} y2={front.y}
          stroke={stroke} strokeWidth={3} opacity={opacity}
          strokeDasharray="6 4" strokeLinecap="round" />
        <line x1={front.x} y1={front.y} x2={target.x} y2={target.y}
          stroke={stroke} strokeWidth={2} opacity={opacity}
          markerEnd={`url(#${markerId})`} strokeLinecap="round" />
      </g>
    );
  }
  if (v.type === 'mating_net_candidate') {
    const king = sqToXY(v.kingSquare, SQ);
    return (
      <circle key={`mn-${key}`}
        cx={king.x} cy={king.y} r={SQ * 0.55}
        fill="none" stroke={stroke} strokeWidth={2.5} opacity={opacity}
        strokeDasharray="3 5"
      />
    );
  }
  return null;
}

// ── Right rail breakdown ─────────────────────────────────────────────
function VectorBreakdown({ palette, vec }) {
  const C = palette;
  const T = window.COPY.attackVectors;
  if (!vec) {
    return (
      <div style={{
        padding: '14px 16px',
        background: C.bone, borderRadius: 12,
        border: `0.6px dashed ${C.umberHair}`,
        fontFamily: window.ATELIER_TYPE.display, fontSize: 14, color: C.umberSoft,
      }}>
        {T.selectPrompt}
      </div>
    );
  }
  const tone = VEC_TONE[vec.type];
  const palColor = C[tone] || C.umber;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <window.SectionHeading palette={C}
        kicker={VEC_LABELS[vec.type] || vec.type}
        title={vec.label} small />
      <div style={{
        padding: '12px 14px',
        background: window.withAlpha(palColor, 0.08),
        border: `0.6px solid ${palColor}`,
        borderRadius: 10,
        fontFamily: window.ATELIER_TYPE.display, fontSize: 14, lineHeight: 1.5,
        color: C.umberSoft,
      }}>
        {T.typeBlurbs[vec.type]}
      </div>

      {vec.type === 'convergent_attack' && (
        <div style={{
          padding: '12px 14px', background: C.bone, borderRadius: 10,
          border: `0.6px solid ${C.umberHair}`,
        }}>
          <div style={{
            fontFamily: window.ATELIER_TYPE.ui, fontSize: 9, letterSpacing: 3,
            textTransform: 'uppercase', color: C.umberFaint, marginBottom: 8,
          }}>{T.attackersLabel(vec.attackers.length)}</div>
          <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
            {vec.attackers.map((a, i) => (
              <li key={i} style={{
                fontFamily: window.ATELIER_TYPE.display, fontSize: 13,
                color: C.umber,
              }}>{a.kind} on {a.from}</li>
            ))}
          </ul>
          <div style={{
            marginTop: 10, fontFamily: window.ATELIER_TYPE.display, fontSize: 13,
            color: C.umberSoft,
          }}>Target: {window.PieceTitle ? window.PieceTitle(vec.targetPiece, vec.target) : (vec.target)}</div>
        </div>
      )}

      {vec.type === 'battery' && (
        <div style={{
          padding: '12px 14px', background: C.bone, borderRadius: 10,
          border: `0.6px solid ${C.umberHair}`,
        }}>
          <div style={{ fontFamily: window.ATELIER_TYPE.display, fontSize: 13, color: C.umber, lineHeight: 1.6 }}>
            <div><strong>Rear:</strong> {vec.rearPiece && vec.rearPiece[1]} on {vec.rear}</div>
            <div><strong>Front:</strong> {vec.frontPiece && vec.frontPiece[1]} on {vec.front}</div>
            <div><strong>Target:</strong> {vec.target}</div>
            <div style={{ marginTop: 6, color: C.umberSoft, fontSize: 12 }}>
              Axis: {vec.axis}
            </div>
          </div>
        </div>
      )}

      {vec.type === 'mating_net_candidate' && (
        <div style={{
          padding: '12px 14px', background: C.bone, borderRadius: 10,
          border: `0.6px solid ${C.umberHair}`,
          fontFamily: window.ATELIER_TYPE.display, fontSize: 13, color: C.umber, lineHeight: 1.6,
        }}>
          <div>King: {vec.kingSquare} ({vec.kingColor})</div>
          <div>In check: {vec.inCheck ? 'yes' : 'no'}</div>
          <div>Escape squares: {vec.escapeSquares.length === 0 ? 'none' : vec.escapeSquares.join(', ')}</div>
          <div style={{ marginTop: 8, color: C.umberSoft, fontSize: 12 }}>{T.matingNetCaveat}</div>
        </div>
      )}
    </div>
  );
}

// ── Screen ───────────────────────────────────────────────────────────
function AttackVectorsScreen({ palette, tweaks, setRoute }) {
  const C = palette;
  const T = window.COPY.attackVectors;

  const [lesson, setLesson] = useAV(window.LESSON || null);
  useAVE(() => {
    const handler = (e) => setLesson(e.detail);
    window.addEventListener('lessonLoaded', handler);
    return () => window.removeEventListener('lessonLoaded', handler);
  }, []);

  const av = lesson && lesson.attackVectors;
  const [filter, setFilter] = useAV('all'); // all / convergent / battery / mating
  const [focusVec, setFocusVec] = useAV(null);
  const [hoverVec, setHoverVec] = useAV(null);

  useAVE(() => { setFocusVec(null); }, [lesson && lesson.id]);

  const filteredVectors = useAVM(() => {
    if (!av) return [];
    if (filter === 'all') return av.vectors;
    if (filter === 'convergent') return av.convergent;
    if (filter === 'battery') return av.batteries;
    if (filter === 'mating') return av.matingNets;
    return [];
  }, [av, filter]);

  if (!lesson || !av) {
    return (
      <div style={{ flex: 1, height: '100%', overflow: 'auto', background: C.bone, padding: 40 }}>
        <window.Topbar palette={C} kicker={T.topbarKicker} title={T.topbarTitle} rightSlot={null} />
        <div style={{ padding: 40, textAlign: 'center', color: C.umberSoft, fontFamily: window.ATELIER_TYPE.display, fontSize: 16 }}>
          {T.emptyState}
        </div>
      </div>
    );
  }

  const position = lesson.position || {};

  return (
    <div style={{
      flex: 1, height: '100%', overflow: 'hidden', display: 'grid',
      gridTemplateColumns: '340px minmax(0, 1fr) 340px',
      background: C.bone,
    }}>
      <aside style={{
        padding: '24px 22px', borderRight: `0.6px solid ${C.umberHair}`,
        background: C.bone, overflow: 'auto',
        display: 'flex', flexDirection: 'column', gap: 16,
      }}>
        <window.SectionHeading palette={C} kicker={T.listKicker} title={T.listTitle} small />

        {/* Filters */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {[
            { key: 'all', label: T.filterAll, count: av.vectors.length },
            { key: 'convergent', label: T.filterConvergent, count: av.convergent.length },
            { key: 'battery', label: T.filterBattery, count: av.batteries.length },
            { key: 'mating', label: T.filterMating, count: av.matingNets.length },
          ].map(({ key, label, count }) => {
            const active = key === filter;
            return (
              <button key={key} onClick={() => { setFilter(key); setFocusVec(null); }}
                style={{
                  appearance: 'none', cursor: 'pointer',
                  padding: '6px 12px', borderRadius: 99,
                  border: `0.6px solid ${active ? C.umber : C.umberHair}`,
                  background: active ? C.cream : 'transparent',
                  color: active ? C.umber : C.umberSoft,
                  fontFamily: window.ATELIER_TYPE.ui,
                  fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase',
                }}>
                {label} <span style={{ opacity: 0.6, marginLeft: 4 }}>{count}</span>
              </button>
            );
          })}
        </div>

        {/* Vector list */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {filteredVectors.length === 0 && (
            <div style={{ fontFamily: window.ATELIER_TYPE.display, fontSize: 13, color: C.umberSoft, padding: '12px 0' }}>
              {T.noVectors}
            </div>
          )}
          {filteredVectors.map((v, i) => {
            const tone = VEC_TONE[v.type];
            const active = focusVec === v;
            return (
              <button key={i}
                onClick={() => setFocusVec(v)}
                onMouseEnter={() => setHoverVec(v)}
                onMouseLeave={() => setHoverVec(null)}
                style={{
                  appearance: 'none', textAlign: 'left', cursor: 'pointer',
                  background: active ? C.cream : 'transparent',
                  border: `0.6px solid ${active ? C[tone] : C.umberHair}`,
                  borderRadius: 10, padding: '10px 12px',
                  display: 'flex', flexDirection: 'column', gap: 4,
                }}>
                <span style={{
                  fontFamily: window.ATELIER_TYPE.ui, fontSize: 9, letterSpacing: 1.5,
                  textTransform: 'uppercase', color: C[tone] || C.umberFaint,
                }}>{VEC_LABELS[v.type]}</span>
                <span style={{
                  fontFamily: window.ATELIER_TYPE.display, fontSize: 13, color: C.umber,
                  lineHeight: 1.35,
                }}>{v.label}</span>
              </button>
            );
          })}
        </div>

        <div style={{
          padding: '14px 16px',
          background: C.cream, borderRadius: 10,
          border: `0.6px dashed ${C.umberHair}`,
        }}>
          <div style={{
            fontFamily: window.ATELIER_TYPE.ui, fontSize: 9, letterSpacing: 3,
            textTransform: 'uppercase', color: C.umberFaint, marginBottom: 8,
          }}>{T.howToReadTitle}</div>
          <p style={{ margin: 0, fontFamily: window.ATELIER_TYPE.display, fontSize: 12, lineHeight: 1.5, color: C.umberSoft }}>
            {T.howToReadBody}
          </p>
        </div>
      </aside>

      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <window.Topbar palette={C} kicker={T.topbarKicker} title={T.topbarTitle} rightSlot={null} />
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 24,
          background: `radial-gradient(120% 80% at 50% -10%, ${window.withAlpha(C.brassLight, 0.35)}, transparent 60%)`,
        }}>
          <div style={{
            background: C.boneDeep, padding: 14, borderRadius: 8,
            boxShadow: '0 30px 50px -28px rgba(42,34,27,0.45)',
          }}>
            <AttackVectorOverlay
              palette={C}
              position={position}
              vectors={filteredVectors}
              focusVec={focusVec}
              hoverVec={hoverVec}
              size={520}
            />
          </div>
        </div>
      </div>

      <aside style={{
        padding: '24px 22px', borderLeft: `0.6px solid ${C.umberHair}`,
        background: C.cream, overflow: 'auto',
      }}>
        <VectorBreakdown palette={C} vec={focusVec || hoverVec} />
      </aside>
    </div>
  );
}

Object.assign(window, { AttackVectorsScreen });
