/* ---------- puzzles: the card, the panels, the link picker, the results and the list ---------- */
const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫'};
function pzTwistTxt(t){const P=S.pz;
if(t.k==='sub')return tr('puzzles.no_subsea_cables');
if(t.k==='ring')return tr('puzzles.one_ring_through_every_pop');
if(t.k==='g')return tr('puzzles.every_link_n_g_or_more',{n:P.minG});
if(t.k==='avoid')return tr('puzzles.no_pop_in_list',{list:P.avoid.map(c=>CITY[c].name).join(', ')});
const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});}
// The short version, for the puzzle list.
function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;}
const pzUnitName=u=>{const l=S.links.find(x=>pzUnit(x)===u);return l?`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`:'';};
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):tr('puzzles.weekly_puzzle')}
${esc(pzName(d||P))} ${btn('☰','puzzleMenu',{},'ghost sm')}
`;
if(d)h+=`${esc(d.j)}
`;
h+=`${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`;
h+=`${e.marks.map(m=>`${esc(CITY[m.c].name)}${m.st===2?' ✓':m.st===1?' ·':' …'} `).join('')}
`;
for(const t of e.tw)h+=`${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')}
`;
h+=!e.conn?`🛡 ${tr('puzzles.n_1_connect_everything_first')}
`:e.n1?`🛡 ${tr('puzzles.survives_any_single_cut')}
`:`⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}
`;
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);}}
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];if(!k)return '';
const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):tr('puzzles.off_limits');
let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`${tr('common.your_pop')} `:'')+'`;
if(!p)h+=`${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(POP_MO)})}
${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`;
else{const others=[...S.pz.cities,...S.pz.via].filter(x=>x!==c);
h+=`${tr('puzzles.drag_from_this_pop_onto_another')}
${tr('puzzles.lease_a_wave_to')} ${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}
`;
const ls=S.links.filter(l=>l.a===c||l.b===c);if(ls.length)h+=`${tr('common.links')} `+ls.map(l=>`${esc(CITY[l.a===c?l.b:l.a].name)}
${capName(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join('');
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 '';
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)})} `)+'`;}
// 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.that_city_is_not_part_of'),'bad');sfx('err');return;}
if(!keep){UI.pzVia=null;UI.pzDiv=true;}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 land=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b);
let h=head+`${tr('common.route')} ${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${x.cab&&CAB[x.cab].age==='old'?'':''} `,'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)}
`;
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)})}
`;
h+=`${PZ_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),c=pzLinkCost(r,i,div)+pop;return `${LT[i].n} ${why?tr('common.too_far_for_this_cable'):pop?tr('puzzles.with_the_pop_price',{price:fmt$(c)}):''} ${tr('puzzles.price_per_year',{price:fmt$(pzLinkCost(r,i,div))})} `;}).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');}
function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h='';
for(let i=0;i<28;i++)h+=` `;
return `${h}
`;}
function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef();
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)}
${row(true,tr('puzzles.goal'),tr('puzzles.connected'))}${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'):tr('puzzles.one_cut_splits_it'))}
${nx?btn(tr('puzzles.next_puzzle'),'pzStart',{id:nx.id},'pink big'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big')}${e.stars<3?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`);
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 ----------
function pzMenu(){const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot),w=pzWeekly(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0;
let h=`${tr('puzzles.puzzles')}
${tr('puzzles.small_calm_network_builds')} ×
${tr('puzzles.no_clock_no_bills_nothing_breaks')}
${tr('puzzles.your_stars')} ⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}
`;
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+=`${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})} ${wr?`${pzStarStr(wr.st)} `:''}
${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
${btn(tr('common.play'),'pzWeekly',{},'pink')}
`;
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=pzTwistTag(d);
h+=`${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${d.cities.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);}