// verify.mjs — de-risk every number "A Game You Shouldn't Be Able to Win" claims,
// BEFORE the page claims it (the P7 correctness-first discipline).
//
// The CHSH game (Clauser–Horne–Shimony–Holt 1969, as a game: Cleve–Høyer–Toner–
// Watrous 2004):
//   A referee sends Alice a private bit x and Bob a private bit y, each uniform and
//   independent. Alice (knowing only x) answers a bit a; Bob (knowing only y) answers
//   a bit b. They may NOT communicate. They WIN the round iff
//                         a XOR b  ==  x AND y.
//   So for question pairs (0,0),(0,1),(1,0) they must answer THE SAME; for (1,1) they
//   must answer DIFFERENTLY.
//
// We verify, exactly:
//   (1) The classical ceiling is 3/4 — by brute force over all 16 deterministic
//       strategies; shared randomness cannot beat it (a convexity argument, stated).
//   (2) The quantum strategy (a shared Bell state + four fixed measurement angles)
//       wins with probability (2+sqrt2)/4 = cos^2(pi/8) ≈ 0.8536, the Tsirelson
//       optimum — computed three independent ways that must agree:
//         (a) the CHSH correlator S = 2*sqrt2 via win = 1/2 + S/8,
//         (b) the Born-rule per-round probabilities P(same)=cos^2(Δ/2),
//         (c) a Monte-Carlo simulation using the EXACT sampler the page ships.
//   (3) No measurement angles beat 2*sqrt2 (Tsirelson bound) — numerical sweep.
//
// Run:  node research/chsh-bell/verify.mjs
// Everything here is pure double-precision JS, identical to the in-browser engine.

const PI = Math.PI, S2 = Math.SQRT2;
let pass = 0, fail = 0;
const ok = (name, cond, extra='') => { (cond?pass++:fail++); console.log(`${cond?'  ok':'FAIL'}  ${name}${extra?'   '+extra:''}`); };
const close = (a,b,eps=1e-12) => Math.abs(a-b) <= eps;

// The game's win predicate.
const won = (a,b,x,y) => ((a ^ b) === (x & y));

console.log('═══ (1) CLASSICAL: brute force over all 16 deterministic strategies ═══');
// A deterministic Alice is a pair [a(0), a(1)]; same for Bob. 4 × 4 = 16.
let best = 0, bestStrat = null, hist = {};
for (let a0=0;a0<2;a0++) for (let a1=0;a1<2;a1++)
for (let b0=0;b0<2;b0++) for (let b1=0;b1<2;b1++){
  let winCount = 0;
  for (let x=0;x<2;x++) for (let y=0;y<2;y++){
    const a = x? a1 : a0, b = y? b1 : b0;
    if (won(a,b,x,y)) winCount++;
  }
  const p = winCount/4;
  hist[p] = (hist[p]||0)+1;
  if (p > best){ best = p; bestStrat = {a0,a1,b0,b1}; }
}
console.log('   win-rate distribution over the 16 strategies:', hist);
ok('classical maximum win probability = 3/4', close(best, 0.75));
ok('the optimal strategy is "both always answer 0" among the maximisers',
   (()=>{ // confirm a0=a1=b0=b1=0 achieves the max
     let w=0; for (let x=0;x<2;x++) for (let y=0;y<2;y++) if (won(0,0,x,y)) w++; return w/4===0.75; })());
console.log('   (Shared randomness = a convex mixture of deterministic strategies; a linear');
console.log('    objective over a simplex is maximised at a vertex ⇒ 3/4 is the absolute');
console.log('    local–hidden-variable ceiling. This IS Bell\'s inequality for this game.)');

console.log('\n═══ (2) QUANTUM: the Tsirelson-optimal entangled strategy ═══');
// Shared state |Φ+> = (|00>+|11>)/sqrt2. Each party measures a spin in the X–Z
// plane; a measurement is parameterised by a Bloch angle. For |Φ+> the correlation
// between Alice's angle α and Bob's angle β is E(α,β) = cos(α − β), and the joint
// outcome statistics are P(equal outcomes) = cos^2((α−β)/2), P(differ)=sin^2((α−β)/2).
const E = (al,be) => Math.cos(al - be);
// The standard optimal settings (any global rotation is equivalent):
const A = [0, PI/2];        // Alice: angle for x=0, x=1
const B = [PI/4, -PI/4];    // Bob:   angle for y=0, y=1

// (2a) via the CHSH correlator S = E00 + E01 + E10 − E11, and win = 1/2 + S/8.
const E00 = E(A[0],B[0]), E01 = E(A[0],B[1]), E10 = E(A[1],B[0]), E11 = E(A[1],B[1]);
const S = E00 + E01 + E10 - E11;
const winFromS = 0.5 + S/8;
console.log(`   E00=${E00.toFixed(6)} E01=${E01.toFixed(6)} E10=${E10.toFixed(6)} E11=${E11.toFixed(6)}`);
ok('CHSH correlator S = 2*sqrt2 (Tsirelson bound)', close(S, 2*S2, 1e-12), `S=${S.toFixed(10)}`);
ok('win (from S)  = (2+sqrt2)/4', close(winFromS, (2+S2)/4, 1e-12), `=${winFromS.toFixed(10)}`);
ok('(2+sqrt2)/4   = cos^2(pi/8)', close((2+S2)/4, Math.cos(PI/8)**2, 1e-12), `=${(Math.cos(PI/8)**2).toFixed(10)}`);

// (2b) via the Born-rule per-round probabilities (independent of the S algebra).
let winProbAnalytic = 0;
for (let x=0;x<2;x++) for (let y=0;y<2;y++){
  const d = A[x] - B[y];
  const pSame = Math.cos(d/2)**2;          // Born rule for |Φ+>
  const needSame = ((x & y) === 0);        // win wants a==b unless x=y=1
  const pWin = needSame ? pSame : (1 - pSame);
  winProbAnalytic += pWin / 4;
}
ok('win (from Born-rule per-round probs) = (2+sqrt2)/4', close(winProbAnalytic, (2+S2)/4, 1e-12),
   `=${winProbAnalytic.toFixed(10)}`);

// (2c) Monte Carlo with the EXACT sampler the page ships (a tiny seeded PRNG so the
//      check is reproducible to the byte). mulberry32.
function mulberry32(seed){ return function(){ let t = seed += 0x6D2B79F5; t = Math.imul(t ^ t>>>15, t|1); t ^= t + Math.imul(t ^ t>>>7, t|61); return ((t ^ t>>>14) >>> 0) / 4294967296; }; }
function quantumRound(rng){
  const x = rng()<0.5?0:1, y = rng()<0.5?0:1;
  const d = A[x] - B[y];
  const pSame = Math.cos(d/2)**2;
  const same = rng() < pSame;              // sample joint outcome correlation
  const a = rng()<0.5?0:1;                 // uniform marginal (Bell state ⇒ each side fair)
  const b = same ? a : (a^1);
  return won(a,b,x,y);
}
function classicalRound(rng){               // best classical: both always 0
  const x = rng()<0.5?0:1, y = rng()<0.5?0:1;
  return won(0,0,x,y);
}
function runMC(fn, N, seed){ const rng = mulberry32(seed); let w=0; for (let i=0;i<N;i++) if (fn(rng)) w++; return w/N; }

const N = 3_000_000;
const qMC = runMC(quantumRound, N, 0x1234abcd);
const cMC = runMC(classicalRound, N, 0x1234abcd);
console.log(`   Monte Carlo, N=${N.toLocaleString()} rounds, seeded (reproducible):`);
ok('quantum MC ≈ 0.8536 (matches the analytic optimum)', close(qMC, (2+S2)/4, 1.5e-3), `=${qMC.toFixed(6)}`);
ok('classical-best MC ≈ 0.7500', close(cMC, 0.75, 1.5e-3), `=${cMC.toFixed(6)}`);

console.log('\n═══ (3) TSIRELSON: no measurement angles beat S = 2*sqrt2 ═══');
// Sweep all four angles on a fine grid; the maximum CHSH value over real projective
// qubit measurements on |Φ+> cannot exceed 2*sqrt2 (Tsirelson 1980). We confirm the
// grid maximum sits at 2*sqrt2 (achieved, never exceeded) up to grid resolution.
let smax = -Infinity, argmax=null;
const G = 90; // 2°-ish steps over each angle
for (let i0=0;i0<G;i0++) for (let i1=0;i1<G;i1++) for (let j0=0;j0<G;j0++) for (let j1=0;j1<G;j1++){
  const a0=i0/G*PI, a1=i1/G*PI, b0=j0/G*PI, b1=j1/G*PI;
  const s = E(a0,b0)+E(a0,b1)+E(a1,b0)-E(a1,b1);
  if (s>smax){ smax=s; argmax={a0,a1,b0,b1}; }
}
console.log(`   grid-max S = ${smax.toFixed(6)}  (Tsirelson bound 2*sqrt2 = ${(2*S2).toFixed(6)})`);
ok('grid maximum does not exceed 2*sqrt2 (to grid resolution)', smax <= 2*S2 + 1e-9);
ok('grid maximum reaches 2*sqrt2 (the bound is achieved)', smax >= 2*S2 - 5e-3, `Δ=${(2*S2-smax).toExponential(2)}`);

// Also: the algebraic maximum (a "PR box") would be S=4 → win=1. Quantum (2*sqrt2 →
// 0.8536) sits strictly between classical (3/4) and that no-signalling maximum (1).
ok('quantum optimum lies strictly between classical 3/4 and the no-signalling max 1',
   (2+S2)/4 > 0.75 + 1e-9 && (2+S2)/4 < 1 - 1e-9, `${((2+S2)/4).toFixed(4)} ∈ (0.75, 1.0)`);

console.log('\n═══ (4) THE SLIDER FAMILY: win(θ) = 1/2 + (3·cosθ − cos3θ)/8 ═══');
// The page\'s "spread" slider rotates one parameter θ with settings
//   A0 = 0,  A1 = 2θ,  B0 = θ,  B1 = −θ.
// Then E00=E01=E10=cosθ and E11=cos3θ, so S(θ) = 3cosθ − cos3θ and
//   win(θ) = 1/2 + S(θ)/8.  The curve bulges above the flat classical 0.75 line.
const winTheta = (th) => 0.5 + (3*Math.cos(th) - Math.cos(3*th))/8;
// Cross-check the closed form against the four-angle Born-rule sum at sample θ.
function winThetaBorn(th){
  const Aa=[0,2*th], Bb=[th,-th]; let w=0;
  for (let x=0;x<2;x++) for (let y=0;y<2;y++){
    const d=Aa[x]-Bb[y], pSame=Math.cos(d/2)**2, needSame=((x&y)===0);
    w += (needSame?pSame:1-pSame)/4;
  }
  return w;
}
let agree = true;
for (const th of [0, 0.3, 0.6, PI/4, 1.0, PI/3, PI/2]) agree = agree && close(winTheta(th), winThetaBorn(th), 1e-12);
ok('closed form win(θ) matches the four-angle Born-rule sum at 7 sample θ', agree);
ok('win(0) = 3/4 (all measurements aligned ⇒ no advantage)', close(winTheta(0), 0.75, 1e-12), `=${winTheta(0).toFixed(6)}`);
ok('win(π/4) = (2+sqrt2)/4 (the peak = Tsirelson optimum)', close(winTheta(PI/4), (2+S2)/4, 1e-12), `=${winTheta(PI/4).toFixed(10)}`);
// The peak is exactly at θ=π/4 and is a strict maximum above 0.75.
let peak=-1, peakTh=0; for (let i=0;i<=100000;i++){ const th=i/100000*PI/2, w=winTheta(th); if (w>peak){peak=w;peakTh=th;} }
ok('numerical peak of win(θ) sits at θ = π/4', close(peakTh, PI/4, 1e-3), `θ*=${(peakTh/PI).toFixed(5)}π`);
// win(θ) > 3/4 ⟺ 3cosθ − cos3θ > 2 ⟺ 2cos³θ − 3cosθ + 1 < 0 ⟺ cosθ > (√3−1)/2,
// i.e. the violation band is θ ∈ (0, arccos((√3−1)/2)) ≈ (0°, 68.53°), peak at 45°.
const upperCross = Math.acos((Math.sqrt(3)-1)/2);
ok('violation band upper edge = arccos((√3−1)/2) ≈ 68.53°', close(upperCross, 1.1960, 1e-3), `=${(upperCross*180/PI).toFixed(2)}°`);
ok('the curve exceeds the classical 0.75 wall across the band, not outside it',
   winTheta(0.5)>0.75 && winTheta(1.0)>0.75 && winTheta(upperCross+0.05)<0.75);

console.log(`\n${fail===0?'✓ ALL CHECKS PASS':'✗ '+fail+' CHECK(S) FAILED'}  (${pass} passed, ${fail} failed)`);
process.exit(fail===0?0:1);
