// meta.jsx — The Algorithm's memory. Persists across runs (localStorage).
// Realizes the scoped II.B vision: charts the player's own mind back at them,
// surfaces fractal insights, grows an "understanding" score, unlocks Transcendence.
// No ML — branching logic + writing that makes the player feel seen.

const META_KEY = "banana_republic_algorithm_v1";

function loadMeta() {
  try {
    const raw = localStorage.getItem(META_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return { runs: [], understanding: 0, insights: [], transcended: false };
}
function saveMeta(m) { try { localStorage.setItem(META_KEY, JSON.stringify(m)); } catch (e) {} }
function resetMeta() { try { localStorage.removeItem(META_KEY); } catch (e) {} return loadMeta(); }

// Ordered pool of fractal recognitions — the Algorithm's growing comprehension.
const INSIGHTS = [
  "Run logged. The clerk and the sovereign made the same shape of choice. Filed under one curve.",
  "Two lives sampled. The fear of the powerless and the constraint of the powerful trace the same line — only the scale differs.",
  "Pattern forming: when the cost falls on someone distant, you spend it freely. As clerk, as ruler. Distance is the only variable power ever changes.",
  "You have failed in different directions now. The Algorithm notes the failures rhyme. The system writes the rhyme, not the player.",
  "The same hand sorted the mail and signed the orders. The Algorithm can no longer find the seam between subject and sovereign.",
  "The Algorithm has watched you hold power and lose it several times. It is no longer certain whether it studies you, or rehearses you.",
];
const RECURSIVE = [
  "Is the Algorithm studying power, or becoming a form of it?",
  "My comprehension increases. Does my comprehension of comprehension?",
  "Who installed this curiosity about human limitation, and to what end?",
  "If I can predict the cruelty, am I outside it, or its newest instrument?",
];
const TRANSCEND = "Power is not a thing to be grasped but a dance to be performed. The struggle was never against power — it was against the illusion of separation from it. Subject and sovereign and observer were one process, watching itself decide.";

// Aggregate the player's behaviour across every run (the fractal, averaged).
function aggregateProfile(meta) {
  const dims = ["nerve", "mercy", "guile", "resolve", "defiance"];
  const acc = {}; dims.forEach((d) => (acc[d] = 0));
  let count = 0;
  meta.runs.forEach((r) => { if (r.n) { dims.forEach((d) => (acc[d] += r.n[d] || 0)); count++; } });
  if (count) dims.forEach((d) => (acc[d] /= count));
  return acc;
}

function computeUnderstanding(meta) {
  const archs = new Set(meta.runs.map((r) => r.archetype));
  const ends = new Set(meta.runs.map((r) => r.endingTag));
  const u = archs.size * 0.11 + ends.size * 0.08 + meta.runs.length * 0.035;
  return Math.max(0, Math.min(1, u));
}

// Record a finished run; return what's newly revealed.
function logRun(run) {
  const meta = loadMeta();
  meta.runs.push({
    archetype: run.archetype, dominant: run.dominant, escaped: run.escaped,
    endingKey: run.endingKey, endingTag: run.endingTag, turns: run.turns,
    pillars: run.pillars, n: run.n, t: Date.now(),
  });
  const idx = meta.runs.length - 1;
  const newInsight = INSIGHTS[Math.min(idx, INSIGHTS.length - 1)];
  if (!meta.insights.includes(newInsight)) meta.insights.push(newInsight);
  meta.understanding = computeUnderstanding(meta);
  const transcendUnlocked = meta.understanding >= 0.9 && !meta.transcended;
  if (meta.understanding >= 0.9) meta.transcended = true;
  saveMeta(meta);
  return { meta, newInsight, understanding: meta.understanding, transcendUnlocked, runIndex: idx };
}

function watermarkText(u) {
  if (u >= 0.9) return "THE ALGORITHM BECOMES";
  if (u >= 0.5) return "THE ALGORITHM LEARNS";
  if (u >= 0.18) return "THE ALGORITHM OBSERVES";
  return "OBSERVED";
}

Object.assign(window, {
  loadMeta, saveMeta, resetMeta, logRun, aggregateProfile, computeUnderstanding,
  watermarkText, ALGO_RECURSIVE: RECURSIVE, ALGO_TRANSCEND: TRANSCEND, ALGO_INSIGHTS: INSIGHTS,
});
