// council-matrix.jsx — Agreement matrix.
// 25×25 heatmap. Each cell shows how often two agents voted the same way
// over the last 30 days. The diagonal is 1.0. Off-diagonals texture
// 0.55–0.85 (deterministic from agent ids). If everyone always agreed,
// the whole grid would be a flat green — which is exactly the failure
// mode a skeptic would expect. Real divergence here is proof of
// independence at no marginal cost.

function AgreementMatrix() {
  const [hover, setHover] = React.useState(null);    // {i, j, value}
  const [pinA, setPinA]   = React.useState(null);    // pinned agent id
  const [pinB, setPinB]   = React.useState(null);

  // Precompute the matrix (25x25) once
  const matrix = React.useMemo(() => {
    return AGENTS.map(a => AGENTS.map(b => agreementBetween(a, b)));
  }, []);

  // Color ramp: low (cool grey) → mid (warm amber) → high (council green)
  // Stays dark-on-dark so the contrast in the diverse band is what stands out.
  const cellColor = (v) => {
    // Map 0.5 → 0.0, 1.0 → 1.0
    const t = Math.max(0, Math.min(1, (v - 0.5) / 0.5));
    // Blend from rgba(64, 80, 96, .25) (cool) to rgba(45,216,129, 1) (council green)
    const r = Math.round(64  + (45  - 64)  * t);
    const g = Math.round(80  + (216 - 80)  * t);
    const b = Math.round(96  + (129 - 96)  * t);
    const a = 0.18 + 0.72 * t;
    return `rgba(${r},${g},${b},${a.toFixed(3)})`;
  };

  return (
    <div>
      <div style={{ marginBottom: 22, maxWidth: 780 }}>
        <Mono color={T.allow} weight={500}>§ 04 · INDEPENDENCE</Mono>
        <h2 style={{
          fontFamily: GEIST, fontWeight: 600, fontSize: 36, letterSpacing: -1.2, lineHeight: 1.05,
          margin: '10px 0 6px', color: T.textInv,
        }}>The 25 do not vote in lockstep.</h2>
        <p style={{
          margin: 0, fontSize: 15, lineHeight: 1.55,
          color: T.muteInv, letterSpacing: -0.1,
        }}>
          Each cell is the share of last-30-day orders where two agents voted the same way. If one entity controlled all 25, every cell would be a flat green. The texture below is proof the agents are independent — same-specialty pairs cluster brighter, cross-specialty pairs cluster dimmer, and the diagonal is 1.0 because every agent agrees with itself.
        </p>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'auto 1fr auto',
        gap: 12, alignItems: 'stretch',
      }}>
        {/* Y-axis labels (agent ids, vertically) */}
        <div style={{
          display: 'grid', gridTemplateRows: `repeat(${AGENTS.length}, 1fr)`,
          paddingTop: 22, paddingRight: 4,
        }}>
          {AGENTS.map(a => {
            const spec = SPEC[a.specialty];
            const isPin = a.id === pinA || a.id === pinB;
            return (
              <div key={a.id} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
                gap: 6, paddingRight: 6,
                fontFamily: GMONO, fontSize: 9, letterSpacing: 0.6,
                color: isPin ? spec.color : T.muteInv,
              }}>
                <span style={{
                  width: 6, height: 6, background: spec.color, opacity: isPin ? 1 : 0.45,
                }}/>
                <span style={{ minWidth: 38, textAlign: 'right' }}>
                  {String(a.id).padStart(2,'0')} {a.name.slice(0, 5)}
                </span>
              </div>
            );
          })}
        </div>

        {/* Matrix body */}
        <div>
          {/* X-axis labels */}
          <div style={{
            display: 'grid', gridTemplateColumns: `repeat(${AGENTS.length}, 1fr)`,
            marginBottom: 4, height: 18,
          }}>
            {AGENTS.map(a => {
              const spec = SPEC[a.specialty];
              const isPin = a.id === pinA || a.id === pinB;
              return (
                <div key={a.id} style={{
                  textAlign: 'center', fontFamily: GMONO, fontSize: 9,
                  color: isPin ? spec.color : T.muteInv, letterSpacing: 0.4,
                }}>{a.id}</div>
              );
            })}
          </div>

          {/* Heat cells */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: `repeat(${AGENTS.length}, 1fr)`,
            gap: 2, padding: 2,
            background: 'rgba(244,244,240,0.02)',
            border: `1px solid ${T.inkBorder}`, position: 'relative',
          }}>
            {matrix.map((row, i) => row.map((val, j) => {
              const isDiagonal = i === j;
              const isHover = hover && hover.i === i && hover.j === j;
              const rowHi   = hover && hover.i === i;
              const colHi   = hover && hover.j === j;
              return (
                <button key={`${i}-${j}`}
                  onMouseEnter={() => setHover({ i, j, value: val })}
                  onMouseLeave={() => setHover(h => (h && h.i === i && h.j === j) ? null : h)}
                  onClick={() => {
                    if (i === j) { setPinA(AGENTS[i].id); setPinB(null); return; }
                    setPinA(AGENTS[i].id); setPinB(AGENTS[j].id);
                  }}
                  style={{
                    width: '100%', aspectRatio: '1 / 1', minWidth: 0,
                    padding: 0, border: 0, cursor: 'pointer',
                    background: isDiagonal ? 'rgba(244,244,240,0.18)' : cellColor(val),
                    outline: (isHover || rowHi || colHi) ? `1px solid ${T.allow}` : 'none',
                    outlineOffset: -1, transition: 'outline .1s linear',
                  }}/>
              );
            }))}
          </div>

          {/* Bottom row labels */}
          <div style={{
            marginTop: 4, height: 18,
            display: 'grid', gridTemplateColumns: `repeat(${AGENTS.length}, 1fr)`,
          }}>
            {AGENTS.map(a => {
              const isPin = a.id === pinA || a.id === pinB;
              return (
                <div key={a.id} style={{
                  textAlign: 'center', fontFamily: GMONO, fontSize: 9,
                  color: isPin ? SPEC[a.specialty].color : T.muteInv,
                  letterSpacing: 0.4,
                }}>{a.id}</div>
              );
            })}
          </div>
        </div>

        {/* Right legend / readout */}
        <div style={{
          width: 260, paddingLeft: 12, display: 'flex', flexDirection: 'column', gap: 16,
        }}>
          {/* Color ramp */}
          <div>
            <Mono color={T.muteInv} size={9}>AGREEMENT</Mono>
            <div style={{
              marginTop: 8, height: 10,
              background: 'linear-gradient(90deg, rgba(64,80,96,0.18), #2DD881)',
              border: `1px solid ${T.inkBorder}`,
            }}/>
            <div style={{
              marginTop: 4, display: 'flex', justifyContent: 'space-between',
              fontFamily: GMONO, fontSize: 9, color: T.muteInv, letterSpacing: 0.4,
            }}>
              <span>0.50</span><span>0.70</span><span>0.85</span><span>1.00</span>
            </div>
          </div>

          {/* Live hover/pin readout */}
          <MatrixReadout hover={hover} pinA={pinA} pinB={pinB}/>

          {/* Specialty key */}
          <div>
            <Mono color={T.muteInv} size={9}>SPECIALTIES</Mono>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8 }}>
              {ALL_SPECS.map(k => (
                <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 10, height: 10, background: SPEC[k].color }}/>
                  <span style={{
                    fontFamily: GMONO, fontSize: 10, letterSpacing: 0.5,
                    color: T.textInv,
                  }}>{SPEC[k].label.toUpperCase()}</span>
                  <span style={{
                    fontFamily: GMONO, fontSize: 9, color: T.muteInv,
                  }}>· {agentsBySpec(k).length}</span>
                </div>
              ))}
            </div>
          </div>

          {/* What the texture means */}
          <div style={{
            padding: '10px 12px', border: `1px dashed ${T.inkBorder}`,
            background: 'rgba(244,244,240,0.02)',
          }}>
            <Mono color={T.allow} size={9} weight={500}>WHAT TO LOOK FOR</Mono>
            <p style={{
              margin: '6px 0 0', fontSize: 11.5, lineHeight: 1.5,
              color: 'rgba(244,244,240,0.78)', letterSpacing: -0.05,
            }}>
              Bright clusters along the same-specialty blocks (5×5 squares on the diagonal). Cooler tones in cross-specialty regions. A perfectly uniform grid would mean the agents are not independent.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

function MatrixReadout({ hover, pinA, pinB }) {
  let title = 'HOVER A CELL';
  let line  = 'Move over any cell to inspect a pair.';
  let detail = null;

  if (hover) {
    const a = AGENTS[hover.i], b = AGENTS[hover.j];
    if (a.id === b.id) {
      title = `${a.name} × itself`;
      line  = 'An agent always agrees with itself. The diagonal is 1.00 by definition.';
    } else {
      const pct = (hover.value * 100).toFixed(1);
      const same = a.specialty === b.specialty;
      title = `${a.name} × ${b.name}`;
      line  = `Voted the same way on ${pct}% of last-30-day orders.`;
      detail = same
        ? `Both ${SPEC[a.specialty].label.toLowerCase()} agents — expected to agree more often.`
        : `${SPEC[a.specialty].label} × ${SPEC[b.specialty].label} — divergent by design.`;
    }
  } else if (pinA && pinB) {
    const a = agentById(pinA), b = agentById(pinB);
    const v = agreementBetween(a, b);
    title = `${a.name} × ${b.name}`;
    line  = `Pinned · ${(v * 100).toFixed(1)}% agreement.`;
  }

  return (
    <div style={{ padding: '12px 14px', background: T.ink, border: `1px solid ${T.inkBorder}` }}>
      <Mono color={T.allow} size={9} weight={500}>{title}</Mono>
      <p style={{ margin: '6px 0 0', fontSize: 12.5, lineHeight: 1.55, color: T.textInv, letterSpacing: -0.05 }}>
        {line}
      </p>
      {detail && (
        <p style={{
          margin: '6px 0 0', fontSize: 11, lineHeight: 1.5,
          color: T.muteInv, letterSpacing: -0.05,
        }}>{detail}</p>
      )}
    </div>
  );
}

Object.assign(window, { AgreementMatrix });
