// atelier-screens-e.jsx — Overloaded Defender study room.
//
// Reads window.LESSON.overload (computed by tools/overload-analysis.js).
// Where Targets asks "which piece falls first?", this room asks "which piece
// has too many jobs to keep them all?" Same three-column layout.
//
// Per INV-001 plain copy. Per INV-005 the room visualizes existing defender
// geometry — no invented tactical claims.

const { useState: useOD, useEffect: useODE, useMemo: useODM } = React;

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

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

// ── Board overlay ────────────────────────────────────────────────
function OverloadOverlay({ palette, position, defenders, focus, hover, size = 520 }) {
  const C = palette;
  const SQ = size / 8;
  const active = hover || focus;
  const drawList = active ? [active] : defenders;
  const dim = !active;

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      {[...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}
          />
        );
      }))}

      {Object.entries(position).map(([sq, code]) => {
        const { x, y } = odSqToXY(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"
          >{OD_GLYPH[code] || '?'}</text>
        );
      })}

      {/* Defender outline and burden lines */}
      {drawList.map((d, i) => {
        const opacity = dim ? 0.4 : 1;
        const tone = d.isPinned ? (C.terracotta || C.sienna) : C.sienna;
        const def = odSqToXY(d.square, SQ);
        return (
          <g key={i}>
            {/* Outline the overloaded defender */}
            <rect
              x={(d.square.charCodeAt(0) - 'a'.charCodeAt(0)) * SQ + 2}
              y={(8 - parseInt(d.square[1], 10)) * SQ + 2}
              width={SQ - 4} height={SQ - 4}
              fill="none" stroke={tone} strokeWidth={d.isPinned ? 2.5 : 1.6}
              strokeDasharray={d.isPinned ? '5 3' : 'none'}
              opacity={opacity}
              rx={2}
            />
            {/* Dotted lines from defender to each burden */}
            {d.burdens.map((b, j) => {
              const burdenXY = odSqToXY(b.square, SQ);
              return (
                <g key={j}>
                  <line
                    x1={def.x} y1={def.y} x2={burdenXY.x} y2={burdenXY.y}
                    stroke={tone} strokeWidth={1.5}
                    strokeDasharray="3 4" opacity={opacity * 0.85}
                  />
                  <circle cx={burdenXY.x} cy={burdenXY.y} r={SQ * 0.38}
                    fill="none" stroke={tone} strokeWidth={1.2}
                    strokeDasharray="2 3" opacity={opacity * 0.6}
                  />
                </g>
              );
            })}
          </g>
        );
      })}
    </svg>
  );
}

// ── Right-rail breakdown ────────────────────────────────────────
function DefenderBreakdown({ palette, defender }) {
  const C = palette;
  const T = window.COPY.overload;
  if (!defender) {
    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 = defender.isPinned ? (C.terracotta || C.sienna) : C.sienna;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <window.SectionHeading palette={C}
        kicker={`${defender.colorName} ${defender.kind} on ${defender.square}`}
        title={defender.isPinned ? T.pinnedTitle : T.overloadedTitle} small />
      <div style={{
        padding: '12px 14px',
        background: window.withAlpha(tone, 0.08),
        border: `0.6px solid ${tone}`,
        borderRadius: 10,
        fontFamily: window.ATELIER_TYPE.display, fontSize: 14, lineHeight: 1.5,
        color: C.umberSoft,
      }}>
        {defender.isPinned ? T.pinnedBlurb : T.overloadedBlurb}
      </div>

      <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.jobsLabel(defender.burdens.length)}</div>
        <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {defender.burdens.map((b, i) => (
            <li key={i} style={{
              fontFamily: window.ATELIER_TYPE.display, fontSize: 13, color: C.umber,
              lineHeight: 1.5,
            }}>
              <div style={{ color: C.umber }}>
                <span style={{ fontFamily: window.ATELIER_TYPE.ui, fontSize: 9, letterSpacing: 1.5, color: C.umberFaint, marginRight: 6 }}>
                  {String(i + 1).padStart(2, '0')}
                </span>
                Defends the {b.kind} on {b.square}
              </div>
              <div style={{ marginLeft: 18, marginTop: 2, color: C.umberSoft, fontSize: 12 }}>
                Attacked by {b.attackers.map((a) => `${a.kind} on ${a.from}`).join(', ')}
              </div>
            </li>
          ))}
        </ul>
      </div>

      <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.5,
      }}>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 9, letterSpacing: 3,
          textTransform: 'uppercase', color: C.umberFaint, marginBottom: 6,
        }}>{T.ideaLabel}</div>
        {defender.isPinned ? T.ideaPinned : T.ideaDeflect}
      </div>
    </div>
  );
}

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

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

  const data = lesson && lesson.overload;
  const [focus, setFocus] = useOD(null);
  const [hover, setHover] = useOD(null);

  useODE(() => { setFocus(null); }, [lesson && lesson.id]);

  if (!lesson || !data) {
    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 || {};
  const defenders = data.overloadedDefenders || [];

  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 />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {defenders.length === 0 && (
            <div style={{
              fontFamily: window.ATELIER_TYPE.display, fontSize: 13,
              color: C.umberSoft, padding: '12px 0',
            }}>{T.none}</div>
          )}
          {defenders.map((d, i) => {
            const active = focus === d;
            const tone = d.isPinned ? (C.terracotta || C.sienna) : C.sienna;
            return (
              <button key={i}
                onClick={() => setFocus(d)}
                onMouseEnter={() => setHover(d)}
                onMouseLeave={() => setHover(null)}
                style={{
                  appearance: 'none', textAlign: 'left', cursor: 'pointer',
                  background: active ? C.cream : 'transparent',
                  border: `0.6px solid ${active ? tone : C.umberHair}`,
                  borderRadius: 10, padding: '10px 12px',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                <span style={{
                  fontFamily: '"Noto Sans Symbols 2","Segoe UI Symbol",sans-serif',
                  fontSize: 22, color: C.umber,
                }}>{OD_GLYPH[d.piece]}</span>
                <span style={{ flex: 1 }}>
                  <span style={{
                    display: 'block', fontFamily: window.ATELIER_TYPE.display,
                    fontSize: 14, color: C.umber,
                  }}>{d.square.toUpperCase()}</span>
                  <span style={{
                    display: 'block', fontFamily: window.ATELIER_TYPE.ui,
                    fontSize: 9, letterSpacing: 1.5, textTransform: 'uppercase',
                    color: tone,
                  }}>
                    {d.isPinned ? T.pinnedTag : T.overloadedTag} · {d.burdens.length} {T.jobsShort}
                  </span>
                </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)',
          }}>
            <OverloadOverlay
              palette={C}
              position={position}
              defenders={defenders}
              focus={focus}
              hover={hover}
              size={520}
            />
          </div>
        </div>
      </div>

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

Object.assign(window, { OverloadedDefenderScreen });
