/* ---------- puzzles: the card, the panels, the link picker, the results and the list ---------- */ const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫',off:'📍'}; function pzTwistTxt(t){if(t.k==='sub')return tr('puzzles.no_subsea_cables');return tr('puzzles.one_ring_through_every_pop');} // The short version, for the puzzle list: what has to be carried, and the twists. function pzDemTag(d){const t=[];const eye=d.dem.filter(f=>f.t==='eye'),l2=d.dem.filter(f=>f.t==='l2'); if(eye.length)t.push(tr('puzzles.n_g_of_eyeballs',{n:fmtG(eye.reduce((a,f)=>a+f.g,0))}));if(l2.length)t.push(trn('puzzles.n_circuits',l2.length)); if(d.dem.some(f=>f.ms))t.push(tr('puzzles.latency_caps'));if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} // A cable carrying several of your waves is named on its own: cutting it takes them all. const pzUnitName=u=>{const ls=S.links.filter(x=>pzUnit(x)===u),l=ls[0];return !l?'':l.cable&&ls.length>1?esc(CAB[l.cable].name):`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`;}; // Each flow on the card: what it is, how much of it arrives, and a circuit's latency against its cap. function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0; const lat=f.ms?` · ${x.ms==null?tr('common.no_path'):x.ms.toFixed(1)+' ms'} / ${f.ms} ms`:''; return `
${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` ${tr('puzzles.best_effort')}`:''}${fmtG(x.g)} / ${fmtG(f.g)}
${lat?`
${tr('puzzles.latency')}${lat}
`:''}${f.t==='l2'?pzRouteCtl(x.i):''}
`;} // A circuit's path: the metrics, or the lowest latency. function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `
${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}
`;} function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); const star=(on,l)=>`⭐${l}`; let h=`
${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; if(d)h+=`

${esc(d.j)}

`;else if(P.wj)h+=`

${esc(pzTxt(P.wj))}

`; h+=`
${star(e.goal,tr('puzzles.delivered'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; if(P.src.length)h+=`
🗄️ ${tr('puzzles.content_lives_in_list',{list:P.src.map(c=>esc(CITY[c].name)).join(', ')})}
`; h+=`
${e.flows.map(pzFlowRow).join('')}
`; // Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick. for(const t of e.tw)h+=t.k==='avoid'?`
🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}
`:`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; const sp=fmt$(e.spend); h+=P.budget?`
${tr('puzzles.spent_x_of_y',{x:sp,y:fmt$(P.budget)})}${e.cheap?'✓':'✗'}
` :`
${tr('puzzles.spent_x',{x:sp})}${tr('puzzles.no_budget_star_on_the_house')}
`; const w=e.worst; h+=!e.goal?`
🛡 ${tr('puzzles.n_1_deliver_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut_under_load')}
` :`
⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}
${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}
`; h+=`
${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!(UI.pzHist&&UI.pzHist.length))}${btn(tr('puzzles.reset'),'pzReset',{},'ghost sm',!S.links.length&&!Object.keys(S.pops).length)}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}
`; if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} // Trenches on a pair get numbers, cables their names, so parallel links say where they run. function pzTrench(l){if(l.cable)return esc(CAB[l.cable].name);const us=[...new Set(pairLinks(l.a,l.b).filter(x=>!x.cable).map(pzUnit))];return tr('puzzles.trench_n',{n:us.indexOf(pzUnit(l))+1});} const pzLoadTxt=l=>`${fmtG(R.load[l.id]||0)} / ${fmtG(capOf(l))}`; function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,pu=portsUsed(c),pm=portsMax(c),cur=pzRtCost(g,rt); const dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v)); let h=`

${tr('puzzles.your_pop')}

${rt>1?rt+' × ':''}${esc(G.n)}${tr('puzzles.price_per_year',{price:fmt$(cur)})}
${tr('puzzles.router_load')}${fmtG(ld)} / ${fmtG(cap)}
${tr('puzzles.ports')}${tr('puzzles.u_of_m_used',{u:fmtPorts(pu),m:pm})}
${tr('puzzles.biggest_wave')}${LT[G.maxLT].n}
${btn(tr('puzzles.add_a_router_cost',{cost:dl(pzRtCost(g,rt+1)-cur)}),'pzRtAdd',{city:c},'sm',rt>=RMAX)}${rt>1?btn(tr('puzzles.remove_a_router'),'pzRtRm',{city:c},'ghost sm'):''}

${tr('puzzles.router_model')}

`; h+=PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i);return `
${esc(M.n)}${i===g?` ${tr('puzzles.installed')}`:''}
${tr('puzzles.model_facts',{cap:fmtG(M.cap),ports:M.ports,wave:LT[M.maxLT].n})}
${why?`
${esc(why)}
`:''}
${i===g?'':btn(dl(pzRtCost(i,rt)-cur),'pzRtModel',{city:c,g:i},'ghost sm',!!why)}
`;}).join(''); return h;} function pzPanel(sel){const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return ''; const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits'); let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`${tr('common.your_pop')}`:'')+'
'; if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; // What this city sends or asks for. const fl=P.dem.map((f,i)=>({f,i})).filter(({f})=>f.a===c||f.b===c),ev=pzEval(); if(P.src.includes(c))h+=`

🗄️ ${tr('puzzles.the_content_origin_lives_here')}

`; if(fl.length)h+=`
${fl.map(({i})=>pzFlowRow(ev.flows[i])).join('')}
`; if(k==='off'&&!p)h+=`

${tr('puzzles.no_traffic_starts_or_ends_here')}

`; if(!p)return h+`

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; h+=pzPopSection(c); // Every pair this POP has links on, with what each member carries, so a second link is never a guess. const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))]; h+=`

${tr('common.links')}

`; if(!nb.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; for(const x of nb){const ls=pairLinks(c,x),ld=ls.reduce((a,l)=>a+(R.load[l.id]||0),0),cp=ls.filter(l=>!linkDown(l)).reduce((a,l)=>a+capOf(l),0); h+=`
${esc(CITY[x].name)} · ${groupLabel(ls,ls)}${fmtG(ld)} / ${fmtG(cp)}
${ls.map(l=>`
${capName(l)} · ${pzTrench(l)}${l.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join('')}
`;} const others=[...P.cities,...P.via].filter(x=>x!==c); h+=`

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}

${tr('puzzles.or_drag_to_any_city_on_the_map')}

`; h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`; return h+'';} const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b); let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${capName(l)}${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}`)+'
'; // What it carries now: each circuit by name, the eyeball traffic by where it is going. {const rec=R.ef[edgeKey(l)],u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`; if(rec){const rows=[];let l2=0;S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){rows.push([pzFlowName(f),v]);}}); const byc={};for(const k in rec.dst)byc[k]=rec.dst[k];S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){byc[f.b]=(byc[f.b]||0)-v;l2+=v;}}); for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]); if(rows.length)h+=`

${pl.length>1?tr('puzzles.carrying_on_this_pair',{n:pl.length}):tr('puzzles.carrying')}

`+rows.map(([n,v])=>`
${esc(n)}${fmtG(v)}
`).join('');void l2;}} if(pl.length>1)h+=`

${tr('puzzles.n_links_on_this_pair',{n:pl.length,what:groupLabel(pl,pl)})}

`+pl.map(x=>`
${capName(x)} · ${pzTrench(x)}${x.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(x)}
${x===l?'':btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join(''); h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=pzWaveWhy(l.a,l.b,i,r);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; h+=metricSection(l)+linkCheckControl(l); return h+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} // The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year. function pzLinkModal(a,b,keep){const kb=pzKind(b); if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} const r=rs.find(x=>x.via===UI.pzVia)||rs.find(x=>!(P.noSub&&x.sub))||rs[0];UI.pzVia=r.via; const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); let h=head; if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:groupLabel(pl,pl)+' · '+[...new Set(pl.map(pzTrench))].join(', ')})}

`; h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; if(P.noSub&&r.sub)h+=`

${tr('puzzles.the_sharks_say_no')}

`; if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`

${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}

`; h+=`
${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; openModal(h);} // ---------- results ---------- function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?tr('puzzles.one_backhoe_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');} // Stars still to win in this puzzle's pack, from the progress just saved. function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);} function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h=''; for(let i=0;i<28;i++)h+=``; return ``;} function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left=pzPackLeft(P),done=e.stars>=3; const row=(ok,l,v)=>`
${ok?'⭐':'☆'} ${l}${v}
`; const stars=[0,1,2].map(i=>`⭐`).join(''); openModal(`
${e.stars>=3?pzConfetti():''}
${tr('puzzles.puzzle_solved')}

${esc(pzName(pzDef(P.id)||P))}

${stars}

${pzLine(e)}

${left==null?'':`

${left?trn('puzzles.n_stars_left_in_this_pack',left):tr('puzzles.every_star_in_this_pack_is')}

`} ${row(true,tr('puzzles.delivered'),tr('puzzles.every_bit_arrives'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut_under_load'):tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(e.worst.u),g:fmtG(e.worst.g)}))}
${nx?btn(tr('puzzles.next_puzzle')+(done?' →':''),'pzStart',{id:nx.id},'pink big pznext'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big pznext')}${!done?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},done?'ghost':'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`); // Three stars: Next is the one big obvious tap (and the keyboard's default). if(done){const b=document.querySelector('#modalCard .pznext');if(b)try{b.focus({preventScroll:true});}catch(_){}} for(let i=prev;i{sfx('star');haptic(15);},Math.max(0,i-prev)*450+150); if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- // The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak. function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzDemTag(w); return `
📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` ${tr('puzzles.new_this_sunday')}`}
${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`${pzStarStr(wr.st)}`:''}
${w.wj?`
${esc(pzTxt(w.wj))}
`:''}
${pzCities(w).map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · '+tg.join(' · ')+'':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
⏳ ${pzWkNext(Date.now())}
${btn(tr('common.play'),'pzWeekly',{},wr&&wr.st>=3?'ghost':'pink',load)}
`;} function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot); let h=`
${tr('puzzles.puzzles')}

${tr('puzzles.small_networks_real_traffic')}

${tr('puzzles.no_clock_no_bills_real_traffic')}

`; // Once, after the puzzles got traffic: the old stars are kept on the wall, the new set starts at zero. if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} h+=`
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; if(pzOn())h+=`
${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; h+=pzWkRow(); for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length; h+=`

${open?'':'🔒 '}${esc(pk.n)} ⭐ ${got}/${n*3}

${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}

`; for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzDemTag(d); h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${pzCities(d).map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} openModal(h);}