(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const p of r)if(p.type==="childList")for(const u of p.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&i(u)}).observe(document,{childList:!0,subtree:!0});function n(r){const p={};return r.integrity&&(p.integrity=r.integrity),r.referrerPolicy&&(p.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?p.credentials="include":r.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function i(r){if(r.ep)return;r.ep=!0;const p=n(r);fetch(r.href,p)}})();const ie={middle:12,outer:18},_={heat:"Heat Shield",hunger:"Dormancy",toxin:"Efflux",immunity:"Cloak"},H={heat:{label:"Heat",color:"#ff8a4c",icon:"sun",trait:"Heat Shield",response:"Heat sources add 3"},hunger:{label:"Hunger",color:"#b388ff",icon:"crescent",trait:"Dormancy",response:"Nutrient inlets add 1"},toxin:{label:"Toxin",color:"#7fd66b",icon:"skull",trait:"Efflux",response:"Toxin inlets add 3"},immunity:{label:"Immunity",color:"#5fd0ff",icon:"shield",trait:"Cloak",response:"Immune damage 3"}},F=6;function z(e,t,n){return en?n:e}function ae(){return{nutrient:0,heat:0,toxin:0,producer:0,grazer:0,phage:0}}function te(e){return{nutrient:e.nutrient,heat:e.heat,toxin:e.toxin,producer:e.producer,grazer:e.grazer,phage:e.phage}}function Ve(e){return{schemaVersion:1,mode:e.mode,scenarioId:e.scenarioId,turn:e.turn,rings:{inner:{direction:e.rings.inner.direction,tiles:e.rings.inner.tiles.map(te)},middle:{direction:e.rings.middle.direction,tiles:e.rings.middle.tiles.map(te)},outer:{direction:e.rings.outer.direction,tiles:e.rings.outer.tiles.map(te)}},lineage:{producer:{pressure:{...e.lineage.producer.pressure},unlocked:{...e.lineage.producer.unlocked}},grazer:{pressure:{...e.lineage.grazer.pressure},unlocked:{...e.lineage.grazer.unlocked}}},inheritedAtStart:{producer:[...e.inheritedAtStart.producer],grazer:[...e.inheritedAtStart.grazer]},consecutiveObjectiveTurns:e.consecutiveObjectiveTurns,environmentActive:{...e.environmentActive},outcome:e.outcome,actionLog:e.actionLog.map(t=>({ring:t.ring,dir:t.dir}))}}function be(e,t,n){return n==="cw"?(e+1)%t:(e+t-1)%t}function De(e,t){const n=e.length,i=new Array(n);for(let r=0;rae())},middle:{direction:"cw",tiles:Array.from({length:12},()=>ae())},outer:{direction:"cw",tiles:Array.from({length:18},()=>ae())}};for(const r of e.starts){const p=i[r.ring].tiles[r.index];i[r.ring].tiles[r.index]={...te(p),...r.chamber}}return{schemaVersion:1,mode:t,scenarioId:e.id,turn:0,rings:i,lineage:{producer:ke(n.producer),grazer:ke(n.grazer)},inheritedAtStart:{producer:[...n.producer],grazer:[...n.grazer]},consecutiveObjectiveTurns:0,environmentActive:{heat:!1,hunger:!1,toxin:!1,immunity:!1},outcome:"playing",actionLog:[]}}function Y(e,t){const{ring:n,index:i}=y(t);return e.rings[n].tiles[i]}function W(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.producer;return t}function ce(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.grazer;return t}function Qe(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.phage;return t}function ye(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.toxin;return t}function we(e,t){let n=0;for(const i of["inner","middle","outer"])for(const r of e.rings[i].tiles)r[t]>0&&n++;return n}const C=_e.map(e=>{const t={...e,sustained:()=>!1,win:()=>!1};return e.id==="s1-heat"?t.win=({state:n})=>Y(n,"I0").producer>=4&&W(n)>=12:e.id==="s2-hunger"?t.win=({state:n,resolvedTurn:i})=>i===10&&W(n)>=8&&ce(n)>=4&&we(n,"producer")>=3&&we(n,"grazer")>=2:e.id==="s3-toxin"?t.win=({state:n,resolvedTurn:i})=>i>=6&&i<=9&&ye(n)<=4&&W(n)+ce(n)>=8:e.id==="s4-immunity"?t.win=({state:n})=>Y(n,"I0").grazer>=3&&W(n)>=6:e.id==="s5-convergence"&&(t.sustained=n=>{const i=Y(n,"I0"),r=Y(n,"M0"),p=Y(n,"O0"),k=[i.producer+i.grazer>=1,r.producer+r.grazer>=1,p.producer+p.grazer>=1].filter(Boolean).length>=2,I=W(n),b=ce(n);return k&&I>=4&&I<=30&&b>=1&&b<=10&&Qe(n)<=5&&ye(n)<=8},t.win=({resolvedTurn:n,consecutive:i})=>i>=2&&n<=12),t});function he(e){const t=C.find(n=>n.id===e)??Ye[e];if(!t)throw new Error(`Unknown scenario: ${e}`);return t}const Ye={test:{id:"test",index:0,name:"Test",subtitle:"",turnLimit:99,starts:[],fixtures:[],sustained:()=>!1,win:()=>!1,teaches:""}};function We(e){const t=new Map;for(const n of e.fixtures){const i=`${n.ring}:${n.index}`;t.has(i)||t.set(i,[]),t.get(i).push({kind:n.kind,label:n.label})}return t}const E=["outer","middle","inner"],Ke=[];function Fe(e,t){return t==="producer"?e.nutrient:t==="grazer"?e.producer:e.grazer}function Ue(e){const t=new Map;for(const n of e.fixtures){const i=`${n.ring}:${n.index}`;t.has(i)||t.set(i,[]),t.get(i).push(n.kind)}return(n,i)=>t.get(`${n}:${i}`)??Je}const Je=[];function Ae(e,t,n=!0){const i=he(e.scenarioId),r=Ve(e),p=n?[]:Ke,u=s=>{n&&p.push(s)},k=Ue(i);r.rings[t.ring].tiles=De(r.rings[t.ring].tiles,t.dir),r.rings[t.ring].direction=t.dir,u({phase:"rotate",ring:t.ring,dir:t.dir});for(const s of["nutrient","toxin"]){const l={inner:r.rings.inner.tiles.map(a=>a[s]),middle:r.rings.middle.tiles.map(a=>a[s]),outer:r.rings.outer.tiles.map(a=>a[s])},o={inner:[0,0,0,0,0,0],middle:q(12),outer:q(18)},d={inner:[0,0,0,0,0,0],middle:q(12),outer:q(18)},f={inner:[0,0,0,0,0,0],middle:q(12),outer:q(18)};for(const a of E){const g=l[a].length,x=r.rings[a].direction;for(let m=0;m=1){const w=be(m,g,x);o[a][m]+=1,f[a][m]+=1,d[a][w]+=1}}for(let a=0;a<6;a++){const g=ee("outer",a),x=ee("middle",a),m=ee("inner",a);l.outer[g]>=1&&(o.outer[g]+=1,d.middle[x]+=1),l.middle[x]>=1&&(o.middle[x]+=1,d.inner[m]+=1)}for(const a of E)for(let g=0;g=1&&o.nutrient>=1){if(r.lineage.producer.unlocked.heat&&o.heat>=2){u({phase:"growth",ring:s,index:l,gained:0,suppressed:!0});continue}o.nutrient-=1;const f=o.producer;o.producer=z(o.producer+1,0,F),u({phase:"growth",ring:s,index:l,gained:o.producer-f,suppressed:!1})}}{const s=K(r,"producer"),l=K(r,"grazer");for(const o of E)for(let d=0;d=1){const a=r.lineage.producer.unlocked.hunger&&f.nutrient===0,g=s[o][d]>=1&&!a,x=r.lineage.grazer.unlocked.heat&&f.heat>=2;if(g&&!x){const m=k(o,d).includes("immuneNode"),S=r.lineage.producer.unlocked.immunity&&m?2:1;f.producer=z(f.producer-S,0,F);const P=f.grazer;f.grazer=z(f.grazer+1,0,F),u({phase:"feed",ring:o,index:d,predator:"grazer",preyRemoved:S,gained:f.grazer>P})}}}}{const s=K(r,"grazer"),l=K(r,"phage");for(const o of E)for(let d=0;d=1){const a=r.lineage.grazer.unlocked.hunger&&f.producer===0;if(s[o][d]>=1&&!a){const x=k(o,d).includes("immuneNode"),w=r.lineage.grazer.unlocked.immunity&&x?2:1;f.grazer=z(f.grazer-w,0,F);const S=f.phage;f.phage=z(f.phage+1,0,F),u({phase:"feed",ring:o,index:d,predator:"phage",preyRemoved:w,gained:f.phage>S})}else f.phage=z(f.phage-1,0,F),u({phase:"feed",ring:o,index:d,predator:"phage",preyRemoved:0,gained:!1,phageStarve:!0})}}}for(const s of["producer","grazer","phage"]){const l=K(r,s),o=[];for(const a of E){const g=r.rings[a].tiles.length,x=r.rings[a].direction;for(let m=0;m=0){const j=a==="inner"?["middle"]:a==="outer"?["middle"]:["inner","outer"];for(const A of j)N.push({ring:A,index:ee(A,Q)})}let T=null;for(const j of N){const A=Fe(r.rings[j.ring].tiles[j.index],s);A>S&&(!T||A>T.food)&&(T={ring:j.ring,index:j.index,food:A})}T&&o.push({from:a,fi:m,toRing:T.ring,toIndex:T.index})}}const d={},f=(a,g)=>`${a}:${g}`;for(const a of o)d[f(a.from,a.fi)]=(d[f(a.from,a.fi)]??0)-1,d[f(a.toRing,a.toIndex)]=(d[f(a.toRing,a.toIndex)]??0)+1;for(const[a,g]of Object.entries(d)){const[x,m]=a.split(":"),w=x,S=+m,P=r.rings[w].tiles[S];P[s]=z(P[s]+g,0,F),g!==0&&u({phase:"migrate",from:a,to:a,species:s})}}for(const s of["producer","grazer"])for(const l of["heat","hunger","toxin","immunity"])r.lineage[s].pressure[l]>=3&&!r.lineage[s].unlocked[l]&&(r.lineage[s].unlocked[l]=!0,u({phase:"evolution",lineage:s,pressure:l,unlocked:!0}));for(const s of["heat","hunger","toxin","immunity"])(r.lineage.producer.pressure[s]>=3||r.lineage.grazer.pressure[s]>=3)&&!r.environmentActive[s]&&(r.environmentActive[s]=!0,u({phase:"env",pressure:s,active:!0}));for(const s of E)for(let l=0;l0&&(o.heat-=1,u({phase:"fixtureGlobal",field:"heat",delta:-1}))}for(const s of E)for(let l=0;l=1&&!r.lineage.producer.unlocked.immunity&&d.push({lin:"producer",pop:o.producer}),o.grazer>=1&&!r.lineage.grazer.unlocked.immunity&&d.push({lin:"grazer",pop:o.grazer});const f=o.producer>=1&&r.lineage.producer.unlocked.immunity||o.grazer>=1&&r.lineage.grazer.unlocked.immunity;if(d.length===0)continue;d.sort((x,m)=>m.pop-x.pop||(x.lin==="producer"?-1:1));const a=d[0].lin,g=r.environmentActive.immunity?3:2;I.push({ring:s,index:l,lineage:a,damage:g}),u({phase:"immuneSelect",ring:s,index:l,lineage:a,damage:g,retarget:f&&d.length>=1})}const b={producer:{heat:new Set,hunger:new Set,toxin:new Set,immunity:new Set},grazer:{heat:new Set,hunger:new Set,toxin:new Set,immunity:new Set}};for(const s of E)for(let l=0;l=1&&(o.heat>=2&&b.producer.heat.add(d),o.nutrient===0&&b.producer.hunger.add(d),o.toxin>=2&&b.producer.toxin.add(d)),o.grazer>=1&&(o.heat>=2&&b.grazer.heat.add(d),o.producer===0&&b.grazer.hunger.add(d),o.toxin>=2&&b.grazer.toxin.add(d))}for(const s of I)b[s.lineage].immunity.add(`${s.ring}:${s.index}`);for(const s of["producer","grazer"])for(const l of["heat","hunger","toxin","immunity"])if(b[s][l].size>=1){const o=r.lineage[s].pressure[l];r.lineage[s].pressure[l]=Math.min(3,o+1),r.lineage[s].pressure[l]!==o&&u({phase:"pressureInc",lineage:s,pressure:l,to:r.lineage[s].pressure[l]})}for(const s of["producer","grazer"])for(const l of b[s].heat){const[o,d]=l.split(":"),f=+d,a=r.rings[o].tiles[f],g=s==="producer"?"producer":"grazer";if(!(a[g]<=0))if(r.lineage[s].unlocked.heat)u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"heat",kind:"prevented",amount:0});else{const x=a[g];a[g]=z(a[g]-2,0,F),u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"heat",kind:"loss",amount:x-a[g]})}}for(const s of ze([b.producer.heat,b.grazer.heat])){const[l,o]=s.split(":"),d=l,f=+o,a=r.rings[d].tiles[f];let g=0;r.lineage.producer.unlocked.heat&&a.producer>0&&g++,r.lineage.grazer.unlocked.heat&&a.grazer>0&&g++;const x=Math.min(2,g);if(x>0&&a.heat>0){const m=a.heat;a.heat=z(a.heat-x,0,F),u({phase:"spillover",ring:d,index:f,pressure:"heat",field:"heat",reduced:m-a.heat})}}for(const s of["producer","grazer"])for(const l of b[s].hunger){const[o,d]=l.split(":"),f=+d,a=r.rings[o].tiles[f],g=s==="producer"?"producer":"grazer";if(!(a[g]<=0))if(r.lineage[s].unlocked.hunger)u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"hunger",kind:"prevented",amount:0});else{const x=a[g];a[g]=z(a[g]-1,0,F),u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"hunger",kind:"loss",amount:x-a[g]})}}for(const s of ze([b.producer.toxin,b.grazer.toxin])){const[l,o]=s.split(":"),d=l,f=+o,a=r.rings[d].tiles[f];for(const m of["producer","grazer"]){const w=m==="producer"?"producer":"grazer";if(!(a[w]<=0)&&b[m].toxin.has(`${d}:${f}`))if(r.lineage[m].unlocked.toxin)if(a.nutrient>=1)a.nutrient-=1,u({phase:"consequence",ring:d,index:f,lineage:m,pressure:"toxin",kind:"payNutrient",amount:1});else{const S=a[w];a[w]=z(a[w]-1,0,F),u({phase:"consequence",ring:d,index:f,lineage:m,pressure:"toxin",kind:"payPop",amount:S-a[w]})}else{const S=a[w];a[w]=z(a[w]-1,0,F),u({phase:"consequence",ring:d,index:f,lineage:m,pressure:"toxin",kind:"loss",amount:S-a[w]})}}let g=0;r.lineage.producer.unlocked.toxin&&a.producer>0&&g++,r.lineage.grazer.unlocked.toxin&&a.grazer>0&&g++;const x=Math.min(2,g);if(x>0&&a.toxin>0){const m=a.toxin;a.toxin=z(a.toxin-x,0,F),u({phase:"spillover",ring:d,index:f,pressure:"toxin",field:"toxin",reduced:m-a.toxin})}}for(const s of I){const l=r.rings[s.ring].tiles[s.index],o=s.lineage==="producer"?"producer":"grazer";if(l[o]<=0)continue;const d=l[o];l[o]=z(l[o]-s.damage,0,F),u({phase:"consequence",ring:s.ring,index:s.index,lineage:s.lineage,pressure:"immunity",kind:"loss",amount:d-l[o]})}const M=e.turn+1,$=i.sustained(r,{state:r,resolvedTurn:M,consecutive:0,fixturesByTile:()=>[]})?e.consecutiveObjectiveTurns+1:0;r.consecutiveObjectiveTurns=$,r.turn=M,r.actionLog=[...r.actionLog,t];let h=0;for(const s of E)for(const l of r.rings[s].tiles)h+=l.producer+l.grazer;return h===0?r.outcome="collapsed":i.win({state:r,resolvedTurn:M,consecutive:$,fixturesByTile:()=>[]})?r.outcome="won":M>=i.turnLimit?r.outcome="expired":r.outcome="playing",u({phase:"outcome",outcome:r.outcome,turn:M}),{state:r,events:n?p:[]}}function q(e){return new Array(e).fill(0)}function K(e,t){return{inner:e.rings.inner.tiles.map(n=>n[t]),middle:e.rings.middle.tiles.map(n=>n[t]),outer:e.rings.outer.tiles.map(n=>n[t])}}function ze(e){const t=new Set;for(const n of e)for(const i of n)t.add(i);return[...t].sort()}const B=640,V=B/2,D=B/2,Ee={inner:96,middle:168,outer:246},le={inner:30,middle:23,outer:17.5},Te=Math.PI/180;function Se(e,t){const n=(90-60*t)*Te;return[V+e*Math.cos(n),D-e*Math.sin(n)]}function U(e,t){const n=e==="inner"?1:e==="middle"?2:3,i=Ee[e],r=Math.floor(t/n),p=t%n/n,u=Se(i,r%6),k=Se(i,(r+1)%6);return[u[0]+(k[0]-u[0])*p,u[1]+(k[1]-u[1])*p]}function de(e,t,n){const i=[];for(let r=0;r<6;r++){const p=(90-60*r)*Te;i.push(`${(e+n*Math.cos(p)).toFixed(2)},${(t-n*Math.sin(p)).toFixed(2)}`)}return i.join(" ")}function ue(e,t){return e==="inner"?t:e==="middle"?2*t%ie.middle:3*t%ie.outer}function Xe(e,t){return e==="inner"?!0:e==="middle"?t%2===0:t%3===0}function fe(e,t){return`${e==="inner"?"I":e==="middle"?"M":"O"}${t}`}const Ie={inner:"#5fd0ff",middle:"#9d7bff",outer:"#7fffd6"};function Ze(e,t,n){const i=[];for(let r=0;r<6;r++){const p=r*60*Math.PI/180,u=e+Math.cos(p)*n*.5,k=t-Math.sin(p)*n*.5;i.push(``)}return`${i.join("")}`}function et(e,t,n){const i=[];for(let r=0;r<3;r++){const p=(r+1)/4,u=e-n*.45+p*n*.9;i.push(``),i.push(``)}return` ${i.join("")} `}function tt(e,t,n){const i=[];for(let p=0;p<6;p++){const u=(p*60+30)*Math.PI/180,k=e+Math.cos(u)*n*.5,I=t+Math.sin(u)*n*.5,b=e+Math.cos(u)*n*.78,M=t+Math.sin(u)*n*.78;i.push(``)}const r=[];for(let p=0;p<6;p++){const u=(90-60*p)*Math.PI/180;r.push(`${(e+Math.cos(u)*n*.45).toFixed(1)},${(t-Math.sin(u)*n*.45).toFixed(1)}`)}return`${i.join("")}`}function pe(e,t,n,i){return e==="producer"?Ze(t,n,i):e==="grazer"?et(t,n,i):tt(t,n,i)}function Me(e,t,n,i){switch(e){case"nutrientInlet":return` `;case"heatSource":{const r=[];for(let p=0;p<8;p++){const u=p*45*Math.PI/180;r.push(``)}return`${r.join("")}`}case"toxinInlet":return``;case"drain":return``;case"immuneNode":return``;case"objective":return``}}function nt(e,t,n={}){const i=We(t),r=($,h)=>(i.get(`${$}:${h}`)??[]).map(s=>({kind:s.kind,label:s.label})),p=n.previewState,u=[];for(let $=0;$<6;$++){const h=U("inner",ue("inner",$));U("middle",ue("middle",$));const s=U("outer",ue("outer",$)),l=!!n.selectedRing;u.push(``)}const k=[];for(const $ of["inner","middle","outer"]){const h=[];for(let s=0;s<6;s++){const l=(90-60*s)*Math.PI/180,o=Ee[$]+le[$]*.9;h.push(`${(V+o*Math.cos(l)).toFixed(1)},${(D-o*Math.sin(l)).toFixed(1)}`)}k.push(``)}const I=[];for(const $ of["outer","middle","inner"]){const h=le[$];for(let s=0;s0?'filter="url(#heatGlow)" ':"",x=$==="inner"?"#10243a":$==="middle"?"#152039":"#0f1c33",m=o+h*.55,w=h*1.1,S=d.nutrient/6*w,P=d.toxin/6*w,N=`clip-${$}-${s}`;let Q="";if(p){const G=p.rings[$].tiles[s],X=G.producer-d.producer,Z=G.grazer-d.grazer;(X!==0||Z!==0)&&(Q=`${X!==0?`P${X>0?"+":""}${X}`:""}${Z!==0?` G${Z>0?"+":""}${Z}`:""}`)}let T="";const j=h*.5;d.producer>0&&(T+=pe("producer",l-h*.32,o-h*.18,j)),d.grazer>0&&(T+=pe("grazer",l+h*.3,o-h*.18,j*.95)),d.phage>0&&(T+=pe("phage",l,o+h*.22,j*.85));const A=[];d.producer>0&&A.push(`P${d.producer}`),d.grazer>0&&A.push(`V${d.grazer}`),d.phage>0&&A.push(`F${d.phage}`);const He=A.length?`${A.join(" ")}`:"";let ve="";for(const G of r($,s))G.kind!=="objective"&&(ve+=Me(G.kind,l,o-h*0,h*.7));const qe=r($,s).find(G=>G.kind==="objective")?Me("objective",l,o,h*1.15):"";I.push(` ${qe} ${S>0?``:""} ${P>0?``:""} ${d.heat>0?``:""} ${ve} ${T} ${He} ${a} ${Q} `)}}const b=`ADAPTIVELOOP`,M=[];if(n.flowEvents&&n.flowEvents.length){const $=h=>J(h);for(const h of n.flowEvents){const[s,l]=U(h.ring,h.index),o=le[h.ring],d=h.field==="nutrient"?"#5fb0ff":"#9fe06a";if(h.tangential>0){const a=$(h.ring)==="cw"?o*.5:-o*.5;M.push(`${h.field} tangential flow at ${fe(h.ring,h.index)}`)}if(h.radial>0){const f=Math.atan2(D-l,V-s),a=s+Math.cos(f)*o*.4,g=l+Math.sin(f)*o*.4,x=s+Math.cos(f)*o*.95,m=l+Math.sin(f)*o*.95;M.push(`${h.field} radial-inward flow at ${fe(h.ring,h.index)}`)}}}function J($){return e.rings[$].direction}return` ${k.join("")} ${u.join("")} ${I.join("")} ${M.join("")} ${b} `}function it(e){const t=[];for(const n of["producer","grazer"]){const i=e.lineage[n],r=n==="producer"?"Lumiflora":"Vellea",p=["heat","hunger","toxin","immunity"].map(u=>{const k=i.pressure[u],I=i.unlocked[u],b="▰".repeat(k)+"▱".repeat(3-k);return`${b}${I?"✓":""}`});t.push(`
${r}${p.join("")}
`)}return t.join("")}const re="adaptive-loop-save-v1",rt=1;function ot(e){const t={...e,savedAt:new Date().toISOString()};localStorage.setItem(re,JSON.stringify(t))}function st(){const e=localStorage.getItem(re);if(!e)return{ok:!1,reason:"No saved game found."};let t;try{t=JSON.parse(e)}catch{return{ok:!1,reason:"Saved game is corrupt (invalid JSON)."}}const n=t;return!n||typeof n!="object"?{ok:!1,reason:"Saved game is empty."}:n.schemaVersion!==rt?{ok:!1,reason:`Unsupported save version ${n.schemaVersion}.`}:!n.state||!n.scenarioId||!n.progress?{ok:!1,reason:"Saved game is missing required fields."}:at(n.state)?{ok:!0,env:n}:{ok:!1,reason:"Saved game state is invalid."}}function je(){localStorage.removeItem(re)}function Oe(){return!!localStorage.getItem(re)}function at(e){if(!e||typeof e!="object")return!1;const t=e;if(t.schemaVersion!==1||!t.rings||!["inner","middle","outer"].every(i=>Array.isArray(t.rings[i]?.tiles)))return!1;const n={inner:6,middle:12,outer:18};for(const i of["inner","middle","outer"]){if(t.rings[i].tiles.length!==n[i])return!1;for(const r of t.rings[i].tiles){const p=r;for(const u of["nutrient","heat","toxin","producer","grazer","phage"])if(typeof p[u]!="number"||p[u]<0||p[u]>6||!Number.isInteger(p[u]))return!1}}return!0}const Pe=[{ring:"inner",dir:"cw",label:"Inner ⟳",key:"1"},{ring:"inner",dir:"ccw",label:"Inner ⟲",key:"2"},{ring:"middle",dir:"cw",label:"Middle ⟳",key:"3"},{ring:"middle",dir:"ccw",label:"Middle ⟲",key:"4"},{ring:"outer",dir:"cw",label:"Outer ⟳",key:"5"},{ring:"outer",dir:"ccw",label:"Outer ⟲",key:"6"}];let c,R;function ct(e){R=e,c={view:"title",mode:"campaign",scenario:C[0],state:Le(C[0],"campaign"),progress:me(),selected:null,preview:null,lastEvents:[],announce:"",pendingNewTraits:[]},O()}function me(){return{unlocked:[C[0].id],inherited:{producer:[],grazer:[]},entrySnapshot:{producer:[],grazer:[]},victory:!1}}function O(){R.innerHTML=lt(),mt(),R.querySelector("#announce")?.setAttribute("aria-live","polite")}function lt(){return c.view==="title"?dt():c.view==="menu"?ut():c.view==="victory"?gt():c.view==="choice"?pt():ft()}function oe(e,t){return`

${t}

${c.announce}
${e}
`}function dt(){return`
${c.announce}

Adaptive Loop

A calm deterministic microfluidic strategy puzzle.

Rotate the three concentric glass rings to align the six radial gates, route nutrient inward, and provoke — then exploit — the ecosystem's counter-adaptations.

${Oe()?"A saved run is available.":"No saved run yet."}

`}function ut(){const e=C.map(t=>{const n=c.progress.unlocked.includes(t.id);return`
  • `}).join("");return oe(``,"Adaptive Loop — Menu")}function ft(){const e=c.scenario,t=c.state,n=t.outcome!=="playing",i=(c.preview?.events??[]).filter(o=>o.phase==="flow").map(o=>({ring:o.ring,index:o.index,field:o.field,tangential:o.tangential,radial:o.radial})),r=nt(t,e,{previewState:c.preview?.state??null,selectedRing:c.selected?.ring??null,flowEvents:i}),p=Ft(e),u=`Turn ${t.turn}/${e.turnLimit}${t.outcome!=="playing"?` — ${xe(t.outcome)}`:""}`,k=Pe.map(o=>{const d=c.selected&&c.selected.ring===o.ring&&c.selected.dir===o.dir,f=d&&c.preview?` → ${Ne(c.preview.events)}`:"";return``}).join(""),b=``,M=``,J=t.outcome==="collapsed"||t.outcome==="expired"?'':"",$=St(c.preview?.events??c.lastEvents),h=it(t),s=["heat","hunger","toxin","immunity"].filter(o=>t.environmentActive[o]).map(o=>`${H[o].label} Response`).join(""),l=[...c.progress.inherited.producer.map(o=>`Lumiflora:${_[o]}`),...c.progress.inherited.grazer.map(o=>`Vellea:${_[o]}`)].join(", ")||"none";return oe(`
    ${r}
    `,`Adaptive Loop — ${e.name}`)}function pt(){const e=c.pendingNewTraits.map((t,n)=>{const i=t.lin==="producer"?"Lumiflora":"Vellea",r=H[t.p];return``}).join("");return oe(`

    Scenario won — preserve a lineage trait?

    The ecosystem unlocked new adaptations. Preserve one to carry its gift (and cost) forward, or decline.

    ${e}
    `,"Lineage choice")}function gt(){return oe('

    Campaign Victory

    You stabilized the Adaptive Loop across all five scenarios.

    ',"Victory")}function ht(){const e=`
  • Lumiflora (producer, green diatom) — consumes nutrient, grows.
  • Vellea (grazer, amber crescent) — consumes producers, grows.
  • Phage (pink lander) — consumes grazers; starves without prey.
  • `,t=["heat","hunger","toxin","immunity"].map(n=>`
  • ${H[n].label} → trait ${_[n]}. Response: ${H[n].response}.
  • `).join("");return`

    Help & Legend

    Rotate a ring (buttons or keys 1–6). A rotation moves that ring's payloads and re-aligns the gates; the tick then resolves flow, growth, feeding, migration, adaptation, and pressure. Select to preview exact deltas; Commit applies it.

    Species

      ${e}

    Pressures & adaptations

      ${t}

    Gate tiles glow in their ring color; nutrient fills the tile base blue, toxin green, heat warms the rim. 1–6 rotate, Enter/Space commits, Esc cancels.

    `}function mt(){const e=(t,n,i)=>R.querySelector(t)?.addEventListener(n,i);e("#btnStart","click",xt),e("#btnContinue","click",vt),e("#btnReplay","click",()=>{c.view="menu",c.mode="standalone",c.progress={...me(),unlocked:C.map(t=>t.id)},O()}),e("#btnMenu","click",()=>{c.view="menu",O()}),e("#btnSaveQuit","click",yt),e("#btnHelp","click",wt),e("#btnDecline","click",()=>ge(null)),R.querySelectorAll(".rot").forEach(t=>{const n=t.dataset.ring,i=t.dataset.dir;t.addEventListener("click",()=>ne({ring:n,dir:i})),t.addEventListener("focus",()=>{(!c.selected||c.selected.ring!==n||c.selected.dir!==i)&&ne({ring:n,dir:i})}),t.addEventListener("mouseenter",()=>{c.selected||ne({ring:n,dir:i})})}),R.querySelectorAll(".scenario-btn").forEach(t=>{t.addEventListener("click",()=>{const n=t.dataset.scid;se(n,c.mode)})}),R.querySelectorAll(".choice").forEach(t=>{t.addEventListener("click",()=>{const n=+t.dataset.i;ge(c.pendingNewTraits[n]??null)})}),e("#btnCommit","click",Ce),e("#btnCancel","click",Re),e("#btnRetry","click",kt),document.onkeydown=$t}function $t(e){if(e.key==="Escape"){Re();return}if(c.view!=="play"||c.state.outcome!=="playing")return;const t="123456".indexOf(e.key);if(t>=0){ne(Pe[t]);return}(e.key==="Enter"||e.key===" ")&&c.selected&&(e.preventDefault(),Ce())}function xt(){c.mode="campaign",c.progress=me(),c.view="play",se(C[0].id,"campaign")}function vt(){const e=st();if(!e.ok){c.announce=e.reason,O();return}const t=e.env;c.mode=t.mode,c.progress=t.progress,c.scenario=he(t.scenarioId),c.state=t.state,c.selected=null,c.preview=null,c.lastEvents=[],c.view="play",c.announce="Resumed saved run.",O()}function se(e,t){const n=he(e);c.scenario=n,c.mode=t;const i=t==="standalone"?{producer:[],grazer:[]}:c.progress.inherited;c.state=Le(n,t,i),c.progress.entrySnapshot={producer:[...i.producer],grazer:[...i.grazer]},c.selected=null,c.preview=null,c.lastEvents=[],c.view="play",c.announce=`${n.name}: ${n.teaches}`,$e(),O()}function ne(e){if(c.state.outcome!=="playing")return;c.selected=e;const{state:t,events:n}=Ae(c.state,e,!0);c.preview={state:t,events:n},c.announce=`Previewing ${e.ring} ${e.dir}: ${Ne(n)}`,O(),R.querySelector(`.rot[data-ring="${e.ring}"][data-dir="${e.dir}"]`)?.focus()}function Re(){c.selected&&(c.selected=null,c.preview=null,c.announce="Preview cancelled.",O())}function Ce(){if(!c.selected||c.state.outcome!=="playing")return;const e=c.selected,{state:t,events:n}=Ae(c.state,e,!0);c.state=t,c.lastEvents=n,c.selected=null,c.preview=null,c.announce=`Turn ${t.turn}: ${xe(t.outcome)}.`,$e(),t.outcome==="won"?bt():O()}function bt(){if(c.mode==="standalone"){c.announce="Standalone scenario complete.",O();return}const e=c.state.inheritedAtStart,t=[];for(const r of["producer","grazer"])for(const p of["heat","hunger","toxin","immunity"])c.state.lineage[r].unlocked[p]&&!e[r].includes(p)&&!c.progress.inherited[r].includes(p)&&t.push({lin:r,p});const n=c.scenario.index,i=C[n];if(i&&!c.progress.unlocked.includes(i.id)&&c.progress.unlocked.push(i.id),!i){c.progress.victory=!0,c.view="victory",je(),O();return}if(t.length===0){ge(null);return}c.pendingNewTraits=t,c.view="choice",O()}function ge(e){e&&(c.progress.inherited[e.lin]=[...c.progress.inherited[e.lin],e.p]);const t=c.scenario.index,n=C[t];if(!n){c.progress.victory=!0,c.view="victory",je(),O();return}se(n.id,"campaign")}function kt(){c.progress.inherited={producer:[...c.progress.entrySnapshot.producer],grazer:[...c.progress.entrySnapshot.grazer]},se(c.scenario.id,c.mode)}function yt(){$e(),c.view="title",c.announce="Saved. Quit to title.",O()}function $e(){c.view==="play"&&ot({schemaVersion:1,mode:c.mode,scenarioId:c.scenario.id,state:c.state,progress:c.progress,actionLog:c.state.actionLog,outcome:c.state.outcome})}function wt(){const e=R.querySelector("#helpPanel");e&&(e.classList.toggle("hidden"),e.setAttribute("aria-hidden",e.classList.contains("hidden")?"true":"false"))}function Ft(e,t){return e.id==="s1-heat"?"Grow producers: producer at I0 ≥ 4 and total producer ≥ 12. (Tuned: see TUNING.md)":e.id==="s2-hunger"?"Endure to turn 10: total producer ≥ 8, grazer ≥ 4, across ≥3 producer tiles and ≥2 grazer tiles.":e.id==="s3-toxin"?"Cleanse: by turn 6–9 reach total toxin ≤ 4 and producer+grazer ≥ 8. (Tuned)":e.id==="s4-immunity"?"Escort: grazer at I0 (sanctuary) ≥ 3 and total producer ≥ 6. (Tuned)":e.id==="s5-convergence"?"Hold equilibrium: assay spoke + balanced ecosystem sustained for 2 consecutive turns. (Tuned)":e.teaches}function xe(e){return e==="won"?"Objective achieved":e==="collapsed"?"Ecosystem collapsed":e==="expired"?"Turn limit expired":"resolved"}function Ne(e){const t=[];for(const n of e)n.phase==="evolution"&&t.push(`unlocks ${_[n.pressure]}`),n.phase==="env"&&t.push(`${H[n.pressure].label} response`),n.phase==="outcome"&&n.outcome!=="playing"&&t.push(`→ ${n.outcome}`);return t.slice(0,3).join(", ")||"tick resolves"}function zt(e){return e==="heat"?"no growth/feeding while hot":e==="hunger"?"dormant when starving (inedible, can't migrate)":e==="toxin"?"pays 1 nutrient under toxin":"predator removes 2 cloaked prey at immune nodes"}function St(e){if(e.length===0)return'
  • Select a rotation to preview the tick.
  • ';const t=[];for(const n of e){const i=It(n);i&&t.push(`
  • ${i}
  • `)}return(t.length?t:['
  • No notable changes.
  • ']).join("")}function It(e){switch(e.phase){case"rotate":return`Rotate ${e.ring} ${e.dir}.`;case"flow":return`Flow ${e.field} at ${L(e.ring,e.index)} (${e.delta>=0?"+":""}${e.delta}).`;case"growth":return e.suppressed?`Growth suppressed (heat) at ${L(e.ring,e.index)}.`:`Producer +${e.gained} at ${L(e.ring,e.index)}.`;case"feed":return e.predator==="grazer"?`Grazer ate producer at ${L(e.ring,e.index)}.`:e.phageStarve?`Phage starved at ${L(e.ring,e.index)}.`:`Phage ate grazer at ${L(e.ring,e.index)}.`;case"migrate":return`${e.species} migrated ${e.from}→${e.to}.`;case"evolution":return`${e.lineage==="producer"?"Lumiflora":"Vellea"} unlocked ${_[e.pressure]}.`;case"env":return`${H[e.pressure].label} response active: ${H[e.pressure].response}.`;case"fixture":return`${e.kind} at ${L(e.ring,e.index)}: ${e.field} ${e.delta>=0?"+":""}${e.delta}.`;case"fixtureGlobal":return null;case"immuneSelect":return`Immune node at ${L(e.ring,e.index)} targets ${e.lineage}${e.retarget?" (retarget spillover)":""}.`;case"pressureInc":return`${e.lineage} ${e.pressure} track → ${e.to}/3.`;case"consequence":return e.kind==="prevented"?`${e.lineage} ${e.pressure} loss prevented (adapted) at ${L(e.ring,e.index)}.`:e.kind==="payNutrient"?`${e.lineage} pays 1 nutrient (Efflux) at ${L(e.ring,e.index)}.`:e.kind==="payPop"?`${e.lineage} loses ${e.amount} (Efflux, no nutrient) at ${L(e.ring,e.index)}.`:`${e.lineage} loses ${e.amount} to ${e.pressure} at ${L(e.ring,e.index)}.`;case"spillover":return`Spillover: ${e.field} −${e.reduced} at ${L(e.ring,e.index)} (${e.pressure} adaptation).`;case"outcome":return e.outcome==="playing"?null:`${xe(e.outcome)}.`}}function L(e,t){return`${e==="inner"?"I":e==="middle"?"M":"O"}${t}`}const Ge=document.getElementById("app");if(!Ge)throw new Error("#app mount point missing");ct(Ge);