seriesoftubes/site/index.html
Claude 706dc92e8f
Add second exchanges in seven more cities, and Barcelona with Catnip-IX
Paella-NIX (Madrid), KleyWrecks (Frankfurt), LO-NAPS (London),
DE-KICKS New York, JINXED-IX (Johannesburg), IX Strayla (Sydney) and
BB-Kicks (Tokyo) join FRIES-IX in XIX. Exchanges can now discount ports
with a fee multiplier. When a city has several, each IX section is
headed with its name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZpEGw99npYwAWtMVXQYgo
2026-10-23 12:23:48 +00:00

2126 lines
270 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Series of Tubes — Build the Internet, One Tube at a Time</title>
<meta name="description" content="A free cartoon browser game about building the internet. Lay fiber and subsea cables, buy transit, peer at internet exchanges, host CDN caches and survive backhoes, sharks and BGP leaks on your way to Tier 1.">
<meta name="keywords" content="internet game, network simulation, BGP, peering, internet exchange, IXP, transit, CDN, subsea cables, dark fiber, browser game, Tier 1">
<meta name="author" content="Frederic Jung">
<meta name="robots" content="index, follow, max-image-preview:large">
<meta name="theme-color" content="#57C4E5">
<meta name="color-scheme" content="light">
<meta name="application-name" content="Series of Tubes">
<meta name="apple-mobile-web-app-title" content="Series of Tubes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<meta name="generator" content="Series of Tubes __VERSION__">
<link rel="canonical" href="https://seriesoftub.es/">
<!-- Open Graph -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="Series of Tubes">
<meta property="og:title" content="Series of Tubes — Build the Internet, One Tube at a Time">
<meta property="og:description" content="Lay fiber, buy transit, peer at IXs and keep the eyeballs happy while backhoes, sharks and route leaks try to stop you. A free cartoon game about how the internet really works.">
<meta property="og:url" content="https://seriesoftub.es/">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://seriesoftub.es/images/og-image.png">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Series of Tubes: a cartoon world map with fiber links, subsea cables and routers">
<!-- Twitter / X -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Series of Tubes — Build the Internet, One Tube at a Time">
<meta name="twitter:description" content="A free cartoon game about building the internet: fiber, transit, peering, CDNs, and a lot of backhoes.">
<meta name="twitter:image" content="https://seriesoftub.es/images/og-image.png">
<meta name="twitter:image:alt" content="Series of Tubes: a cartoon world map with fiber links, subsea cables and routers">
<!-- Icons -->
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="icon" type="image/x-icon" href="/favicon.ico" sizes="32x32 16x16">
<link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;700;800&family=Nunito:wght@500;700;800;900&display=swap">
<!-- Structured data -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebSite",
"name": "Series of Tubes",
"url": "https://seriesoftub.es/",
"description": "A free cartoon browser game about building the internet."
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "VideoGame",
"name": "Series of Tubes",
"url": "https://seriesoftub.es/",
"image": "https://seriesoftub.es/images/og-image.png",
"description": "Build an internet: lay terrestrial and subsea fiber, buy IP transit, peer at internet exchanges, set up PNIs and CDN caches, sign business customers and survive constant failures on your way to becoming a Tier 1 network.",
"genre": ["Simulation", "Strategy", "Tycoon"],
"gamePlatform": "Web browser",
"applicationCategory": "Game",
"operatingSystem": "Any",
"playMode": "SinglePlayer",
"inLanguage": "en",
"isAccessibleForFree": true,
"softwareVersion": "__VERSION__",
"dateModified": "__BUILD_DATE__",
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
"author": { "@type": "Person", "name": "Frederic Jung", "url": "https://github.com/fjaeckel" }
}
</script>
<style>
/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). Single committed bright look. */
:root{
--sea:#57C4E5; --sea2:#3AA6CF; --wave:#9BE2F2; --land:#9BDA6C; --land2:#7FC455; --sand:#F8E6A8;
--ink:#1E2640; --ink2:#55608A; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC;
--me:#FF4F9A; --sun:#FFD23F; --ok:#22C47A; --warn:#FFAA1F; --bad:#FF4D5E;
--t1:#7B61FF; --t2:#2F8CFF; --cdn:#FF8A3D; --eye:#16A866;
--display:'Baloo 2','Trebuchet MS',system-ui,sans-serif;
--body:'Nunito',system-ui,-apple-system,sans-serif;
color-scheme:light;
}
[hidden]{display:none!important}
html,body{height:100%}
body{margin:0}
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.ver{font-size:11.5px;color:var(--ink2);margin-top:10px}
.ver a{color:inherit}
body{background:var(--sea);color:var(--ink);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased}
#map{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab}
#map.linking{cursor:crosshair}
.num{font-variant-numeric:tabular-nums}
h2,h3,h4{font-family:var(--display);margin:0;text-wrap:balance;line-height:1.1}
button{font:inherit;color:inherit}
:focus-visible{outline:3px solid var(--me);outline-offset:2px}
/* sticker surfaces */
.card{background:var(--paper);border:3px solid var(--ink);border-radius:18px;box-shadow:4px 4px 0 var(--ink)}
/* HUD */
#hud{position:fixed;top:calc(env(safe-area-inset-top,0px) + 10px);left:max(12px,env(safe-area-inset-left,0px));right:max(12px,env(safe-area-inset-right,0px));display:flex;gap:8px;align-items:stretch;flex-wrap:wrap;pointer-events:none;z-index:5}
#hud>*{pointer-events:auto}
.chip{background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:3px 11px;display:flex;flex-direction:column;justify-content:center;min-height:46px}
.chip .lbl{font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--ink2)}
.chip .val{font-family:var(--display);font-weight:800;font-size:19px;line-height:1.05;white-space:nowrap}
.chip .sub{font-size:11px;font-weight:800;white-space:nowrap}
.brand{flex-direction:row;align-items:center;gap:9px;background:var(--me);color:#fff}
.brand .val{font-size:20px}
.brand .lbl{color:#FFE0EE}
.tube{width:30px;height:30px;flex:none}
.up{color:var(--ok)} .down{color:var(--bad)}
.speed{flex-direction:row;align-items:center;gap:4px;padding:4px 6px}
.speed button{border:2.5px solid var(--ink);background:var(--paper);border-radius:9px;min-width:34px;height:32px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13px}
.speed button.on{background:var(--sun)}
.spacer{flex:1}
.noc{cursor:pointer;border:3px solid var(--ink)}
.noc.hot{background:var(--bad);color:#fff;animation:throb 1s ease-in-out infinite}
.noc.hot .lbl{color:#FFE1E4}
@keyframes throb{50%{transform:scale(1.05)}}
.minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%}
.minibar i{display:block;height:100%;background:var(--ok)}
/* drawers */
#left{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);left:max(12px,env(safe-area-inset-left,0px));width:300px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;z-index:4}
#panel{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);right:max(12px,env(safe-area-inset-right,0px));width:370px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;z-index:4}
.scroll{overflow:auto;padding:12px 14px 14px;overscroll-behavior:contain}
.tabs{display:flex;gap:4px;padding:8px 8px 0;border-bottom:3px solid var(--ink);flex:none}
.tabs button{border:2.5px solid var(--ink);border-bottom:none;border-radius:11px 11px 0 0;background:var(--soft);padding:4px 10px 3px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13.5px;position:relative;top:3px}
.tabs button.on{background:var(--paper);padding-bottom:6px}
.tabs .cnt{display:inline-block;background:var(--me);color:#fff;border-radius:9px;padding:0 6px;font-size:11px;margin-left:4px}
.tabs .cnt.red{background:var(--bad)}
#leftToggle{display:none}
.ph{display:flex;align-items:flex-start;gap:8px;padding:12px 14px 8px;border-bottom:3px solid var(--ink);flex:none}
.ph h2{font-size:26px}
.eyebrow{font-size:10.5px;font-weight:900;letter-spacing:.09em;text-transform:uppercase;color:var(--ink2)}
.x{margin-left:auto;border:2.5px solid var(--ink);background:var(--paper);border-radius:10px;width:32px;height:32px;font-size:20px;line-height:1;cursor:pointer;font-weight:900;flex:none}
.facts{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
.fact{background:var(--soft);border:2px solid var(--ink);border-radius:9px;padding:1px 8px;font-size:12px;font-weight:700}
.fact.ixf{background:#FFF3C4}
.fact.mine{background:var(--me);color:#fff}
.fact.down{background:var(--bad);color:#fff}
section{padding:10px 0;border-bottom:2px dashed var(--line)}
section:last-child{border-bottom:none}
section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap:8px}
.lead{margin:0 0 8px;color:var(--ink2);font-size:12.5px;line-height:1.45}
.note{margin:6px 0 0;color:var(--ink2);font-size:12.5px;line-height:1.4}
.kv{display:flex;justify-content:space-between;gap:8px;font-size:13px;margin:3px 0}
.kv b{font-variant-numeric:tabular-nums}
.row{display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid var(--line)}
.row:first-of-type{border-top:none}
.row .grow{flex:1;min-width:0}
.row .nm{font-weight:800;font-size:13.5px;line-height:1.2}
.row .meta{font-size:11.5px;color:var(--ink2);line-height:1.3}
.btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:5px}
.why{font-size:11px;color:#B23A48;font-weight:700;margin-top:3px;line-height:1.3}
.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s}
.b:hover{filter:brightness(1.05)}
.b:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)}
.b:disabled{opacity:.42;cursor:not-allowed;transform:none;box-shadow:0 3px 0 var(--ink)}
.b.ghost{background:var(--paper)}
.b.pink{background:var(--me);color:#fff}
.b.red{background:var(--bad);color:#fff}
.b.green{background:var(--ok);color:#fff}
.b.sm{font-size:12px;padding:2px 8px 1px;border-radius:9px;box-shadow:0 2px 0 var(--ink)}
.b.big{font-size:18px;padding:7px 18px 5px}
.b small{font-family:var(--body);font-weight:800;font-size:10.5px;opacity:.85;margin-left:3px}
.logo{width:30px;height:30px;border-radius:50%;background:var(--c);border:2.5px solid var(--ink);display:grid;place-items:center;color:#fff;font-family:var(--display);font-weight:800;font-size:11px;flex:none;letter-spacing:-.02em}
.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:var(--ink2)}
.tag.t1{background:var(--t1)} .tag.t2{background:var(--t2)} .tag.cdn{background:var(--cdn)} .tag.eye{background:var(--eye)}
.tag.open{background:var(--ok)} .tag.selective{background:var(--warn);color:var(--ink)} .tag.restrictive{background:var(--bad)} .tag.paid{background:var(--me)}
.tag.st{background:var(--paper);color:var(--ink)}
.tag.st.on{background:var(--ink);color:#fff}
.bar{height:11px;border:2px solid var(--ink);border-radius:7px;background:var(--paper);overflow:hidden;margin:3px 0}
.stack{display:flex;height:16px;border:2px solid var(--ink);border-radius:8px;overflow:hidden;margin:4px 0 6px;background:var(--paper)}
.stack i{display:block;height:100%}
.sub4{font-size:13.5px;margin:10px 0 3px}
.dot{display:inline-block;width:10px;height:10px;border-radius:50%;border:1.5px solid var(--ink);margin-right:6px;vertical-align:-1px}
.bar>i{display:block;height:100%;background:var(--ok);transition:width .3s}
.bar.warn>i{background:var(--warn)} .bar.bad>i{background:var(--bad)} .bar.me>i{background:var(--me)}
.goal{display:flex;gap:9px;padding:8px 0;border-top:1px solid var(--line)}
.goal:first-child{border-top:none}
.goal .ck{width:22px;height:22px;border:2.5px solid var(--ink);border-radius:7px;flex:none;display:grid;place-items:center;font-weight:900;background:var(--paper);font-size:13px}
.goal.done .ck{background:var(--ok);color:#fff}
.goal.done .gt{text-decoration:line-through;color:var(--ink2)}
.goal.cur{background:#FFF6CF;margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)}
.goal .gt{font-weight:900;font-size:13.5px}
.goal .gd{font-size:12px;color:var(--ink2);line-height:1.4;margin-top:2px}
.goal .gr{font-size:11px;font-weight:900;color:var(--eye);margin-top:2px}
.empty{color:var(--ink2);font-size:12.5px;line-height:1.45;padding:6px 0}
.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:#FFF0F1}
.inc .nm{font-weight:900}
.inc .meta{font-size:12px;color:var(--ink2);margin-top:2px;line-height:1.35}
/* toasts */
#toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 14px);display:flex;flex-direction:column-reverse;gap:8px;z-index:8;width:min(460px,calc(100% - 32px));pointer-events:none}
.toast{pointer-events:none;background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:9px 12px;display:flex;gap:10px;align-items:center;animation:pop .25s cubic-bezier(.3,1.6,.6,1)}
.toast.good{background:#DFFBEA} .toast.bad{background:#FFE1E4} .toast.goal{background:#FFF3C4}
.toast .b{pointer-events:auto}
.seg{display:flex;flex-wrap:wrap;gap:6px}
.seg .b{white-space:normal;text-align:left}
.toast .tx{flex:1;font-size:13px;line-height:1.35}
.toast .tx b{font-family:var(--display);font-size:14.5px}
@keyframes pop{from{transform:scale(.8) translateY(10px);opacity:0}}
#hint{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 76px);background:var(--ink);color:#fff;border-radius:12px;padding:6px 12px;font-weight:800;font-size:12.5px;z-index:3;pointer-events:none;max-width:min(440px,calc(100% - 32px));text-align:center;box-shadow:3px 3px 0 rgba(30,38,64,.25)}
/* modal */
#update{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 70px);z-index:18;width:min(520px,calc(100% - 24px));pointer-events:auto}
#update .b{pointer-events:auto}
.notes{margin:10px 0 0;padding-left:20px;line-height:1.5}
.notes li{margin:4px 0}
#bankBox{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:16;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))}
#bankCard{max-width:760px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)}
.cashbtn{cursor:pointer;text-align:left;font:inherit;color:inherit;position:relative}
.cashbtn .badge{position:absolute;top:-8px;right:-8px;background:var(--me);color:#fff;border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 6px;line-height:16px}
.loan{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;margin-top:10px;display:flex;gap:10px;align-items:flex-start}
.loan .grow{flex:1;min-width:0}
.loan .terms{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun)}
#dash{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:15;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))}
#dashCard{max-width:980px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)}
.dgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:10px 0}
.tile{border:2.5px solid var(--ink);border-radius:13px;padding:6px 10px;background:var(--soft)}
.tile .lbl{font-size:10px;font-weight:900;letter-spacing:.08em;text-transform:uppercase;color:var(--ink2)}
.tile .val{font-family:var(--display);font-weight:800;font-size:22px;line-height:1.1;font-variant-numeric:tabular-nums}
.tile .sub{font-size:11.5px;color:var(--ink2);font-weight:700}
.dcols{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:12px}
@media (max-width:760px){.dcols{grid-template-columns:minmax(0,1fr)}}
.panel2{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;min-width:0}
.panel2 h3{font-size:17px;margin-bottom:4px}
.chart{width:100%;height:auto;display:block}
.legend{display:flex;flex-wrap:wrap;gap:10px;font-size:11.5px;font-weight:800;color:var(--ink2);margin-top:4px}
.legend i{display:inline-block;width:11px;height:11px;border-radius:3px;border:1.5px solid var(--ink);margin-right:5px;vertical-align:-1px}
.tbl{width:100%;border-collapse:collapse;font-size:12.5px;font-variant-numeric:tabular-nums}
.tbl th{text-align:left;font-size:10px;letter-spacing:.07em;text-transform:uppercase;color:var(--ink2);padding:4px 6px;border-bottom:2px solid var(--ink)}
.tbl td{padding:5px 6px;border-bottom:1px solid var(--line);vertical-align:middle}
.tbl td.r,.tbl th.r{text-align:right}
.mix{display:flex;height:10px;width:100px;border:1.5px solid var(--ink);border-radius:5px;overflow:hidden;background:var(--paper)}
.mix i{display:block;height:100%}
.tscroll{overflow-x:auto}
#modal{position:fixed;inset:0;background:rgba(30,38,64,.45);display:grid;place-items:center;z-index:20;padding:16px max(16px,env(safe-area-inset-right,0px)) 16px max(16px,env(safe-area-inset-left,0px))}
#modal .card{width:min(560px,100%);max-height:calc(100% - 20px);overflow:auto;padding:20px 22px}
.title-art{display:flex;align-items:center;gap:14px}
.title-art h1{font-family:var(--display);font-weight:800;font-size:clamp(34px,7vw,52px);line-height:.95;margin:0;letter-spacing:-.01em}
.title-art h1 span{color:var(--me)}
.tagline{color:var(--ink2);font-size:14.5px;line-height:1.45;margin:10px 0 14px}
label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink2);margin:12px 0 5px}
input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft)}
.starts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
.start{border:3px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--paper);cursor:pointer;text-align:left;box-shadow:0 3px 0 var(--ink)}
.start.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 3px 0 var(--me)}
.start b{font-family:var(--display);font-size:17px;display:block}
.start span{font-size:12px;color:var(--ink2);line-height:1.3;display:block}
.tiers{display:grid;gap:7px;margin-top:10px}
.tierbtn{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:13px;padding:8px 12px;background:var(--paper);cursor:pointer;box-shadow:0 3px 0 var(--ink);text-align:left}
.tierbtn:hover{background:#FFF6CF}
.tierbtn:disabled{opacity:.4;cursor:not-allowed}
.tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px}
.tierbtn .grow{flex:1}
.tierbtn .pr{font-family:var(--display);font-weight:800;font-size:18px}
.gl dt{font-family:var(--display);font-weight:800;font-size:16px;margin-top:10px}
.gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px}
.kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)}
@media (max-width:760px){
.chip{min-height:40px;padding:2px 8px}
.chip .val{font-size:16px}
.chip .lbl{font-size:9px}
.brand .val{font-size:16px}
.hide-sm{display:none !important}
#hud{gap:6px}
.chip{min-height:34px;padding:2px 7px;border-width:2.5px;box-shadow:2px 2px 0 var(--ink);border-radius:11px}
.chip .val{font-size:14px}
.chip .sub{font-size:10px}
.brand .tube{width:22px;height:22px}
.brand>div{display:none}
.speed{padding:2px 4px;gap:3px}
.speed button{min-width:28px;height:26px;font-size:11.5px;border-width:2px;border-radius:7px}
.spacer{display:none}
#left{top:auto}
#left{top:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 8px);left:8px;right:8px;width:auto;max-height:55%}
#left.closed{display:none}
#leftToggle{display:flex;position:fixed;left:max(12px,env(safe-area-inset-left,0px));bottom:calc(env(safe-area-inset-bottom,0px) + 14px);z-index:4}
#panel{top:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 8px);left:8px;right:8px;width:auto;max-height:58%;z-index:6}
.ph h2{font-size:22px}
#hint{top:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 70px)}
#toasts{bottom:auto;top:calc(env(safe-area-inset-top,0px) + 112px);flex-direction:column;width:calc(100% - 24px)}
.toast{padding:6px 10px;border-width:2.5px;box-shadow:2px 2px 0 var(--ink)}
.toast .tx{font-size:12px}
.toast .tx b{font-size:13px}
}
@media (prefers-reduced-motion:reduce){*{animation:none !important;transition:none !important}}
</style>
</head>
<body>
<header class="sr-only">
<h1>Series of Tubes: build the internet, one tube at a time</h1>
<p>A free cartoon browser game about how the internet works. Start as a tiny network in one city, launch home broadband, buy IP transit from Tier 1 and Tier 2 carriers, peer at internet exchanges, set up private interconnects and embedded CDN caches, and lay terrestrial fiber, subsea waves and your own dark fiber with DWDM and ZR optics. Sign enterprise, hosting, high-frequency trading, AI GPU and hyperscaler customers, and keep them happy while backhoes, sharks, fat fingers, route leaks, DDoS attacks and geopolitics break things.</p>
</header>
<noscript>
<div style="max-width:640px;margin:40px auto;padding:0 16px;font:16px/1.5 system-ui,sans-serif;color:#1E2640;background:#fff">
<h1>Series of Tubes</h1>
<p>Series of Tubes is a cartoon game about building the internet: fiber, transit, peering, CDNs and a lot of backhoes. It runs entirely in your browser and needs JavaScript to play.</p>
<p><a href="https://github.com/fjaeckel/seriesoftubes">Source code on GitHub</a></p>
</div>
</noscript>
<canvas id="map" aria-label="World map of your network"></canvas>
<header id="hud">
<div class="chip brand">
<svg class="tube" viewBox="0 0 32 32" aria-hidden="true"><path d="M4 22c0-7 5-12 12-12h6" fill="none" stroke="#1E2640" stroke-width="7" stroke-linecap="round"/><path d="M4 22c0-7 5-12 12-12h6" fill="none" stroke="#FFD23F" stroke-width="3.5" stroke-linecap="round"/><circle cx="25" cy="10" r="5" fill="#fff" stroke="#1E2640" stroke-width="2.5"/></svg>
<div><div class="val" id="hName">Series of Tubes</div><div class="lbl" id="hAsn">AS —</div></div>
</div>
<button class="chip cashbtn" data-act="bank" aria-label="Cash and bank"><span class="lbl">Cash · Bank</span><span class="val num" id="hCash">$0</span><span class="sub num" id="hRate">—</span><span class="badge" id="hBank" hidden></span></button>
<div class="chip hide-sm"><div class="lbl">Traffic served</div><div class="val num" id="hTraffic">0</div><div class="minibar"><i id="hTrafBar" style="width:0"></i></div></div>
<div class="chip"><div class="lbl">Reach</div><div class="val num" id="hReach">0%</div></div>
<div class="chip hide-sm"><div class="lbl">Rank</div><div class="val" id="hTier">Tier 3</div></div>
<button class="chip noc" id="hNoc" data-act="leftTab" data-args='{"t":"noc"}'><span class="lbl">NOC</span><span class="val num" id="hNocVal">All quiet</span></button>
<div class="spacer"></div>
<div class="chip"><div class="lbl">Date</div><div class="val num" id="hDate">Y1 · Jan 1</div></div>
<div class="chip speed" role="group" aria-label="Game speed">
<button data-act="speed" data-args='{"v":0}' id="sp0" aria-label="Pause">❚❚</button>
<button data-act="speed" data-args='{"v":1}' id="sp1">1×</button>
<button data-act="speed" data-args='{"v":2}' id="sp2">2×</button>
<button data-act="speed" data-args='{"v":4}' id="sp4">4×</button>
<button data-act="speed" data-args='{"v":8}' id="sp8">8×</button>
<button data-act="dash" aria-label="NOC dashboard" title="NOC dashboard"><svg width="16" height="14" viewBox="0 0 16 14" aria-hidden="true"><path d="M1 13h14M2 10l4-5 3 3 5-6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
<button data-act="help" aria-label="How to play">?</button>
<button data-act="mute" id="muteBtn" aria-label="Toggle sound">♪</button>
</div>
</header>
<aside id="left" class="card">
<nav class="tabs" id="leftTabs"></nav>
<div class="scroll" id="leftBody"></div>
</aside>
<button id="leftToggle" class="b pink" data-act="toggleLeft">Goals & NOC</button>
<aside id="panel" class="card" hidden>
<div id="panelBody" style="display:flex;flex-direction:column;min-height:0;flex:1"></div>
</aside>
<div id="hint" hidden></div>
<div id="toasts" aria-live="polite"></div>
<div id="update" class="toast goal" hidden role="status"></div>
<div id="bankBox" hidden><div class="card" id="bankCard" role="dialog" aria-label="Bank"></div></div>
<div id="dash" hidden><div class="card" id="dashCard" role="dialog" aria-label="NOC dashboard"></div></div>
<div id="modal" hidden><div class="card" id="modalCard" role="dialog" aria-modal="true"></div></div>
<script>
'use strict';
/* ================= ANALYTICS (ridiculytics) =================
Off unless ANALYTICS.host is set. Fill in your collector when you self-host the game.
Inside the claude.ai viewer outside requests are blocked, so it only reports from your own domain. */
const APP_VERSION='__VERSION__';
// Filled in by scripts/build.sh from CHANGELOG.md for this version.
const RELEASE_NOTES=/*__RELEASE_NOTES__*/[];
const IS_DEV=APP_VERSION.startsWith('__');
// Only report from the real site; previews, localhost and the Claude viewer stay silent.
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
(function(){
try{
window.ridiculytics=window.ridiculytics||function(){const q=window.ridiculytics.q=window.ridiculytics.q||[];if(q.length<100)q.push(arguments);};
if(!ANALYTICS.host)return;
const sc=document.createElement('script');sc.defer=true;sc.src='https://cdn.jsdelivr.net/npm/ridiculytics@1.0.1/web/counter.min.js';
sc.setAttribute('data-host',ANALYTICS.host);if(ANALYTICS.site)sc.setAttribute('data-site',ANALYTICS.site);sc.setAttribute('data-spa','false');sc.integrity='sha384-uNCU8e2RB7Yn6lVNut2gupQsJwKwXPZu2i4t/Eg6Q59ki0kchBR4L4yoS3ZxxjEX';sc.crossOrigin='anonymous';sc.referrerPolicy='no-referrer';
document.head.appendChild(sc);
}catch(e){}
})();
const TRACKED=new Set();
function track(name,once){if(!ANALYTICS.host)return;if(once){if(TRACKED.has(name))return;TRACKED.add(name);}try{window.ridiculytics(name);}catch(e){}}
const PLAY_MARKS=[1,5,15,30,60,120];
/* ================= CONSTANTS ================= */
const W=2000, H=1000, KM=14;
const POP_COST=20000, POP_MO=1500, EYE_RATE=150, CACHE_CAP=100, CACHE_MO=400;
const DAY_MS=2500, ROUTER_COST=15000, ROUTER_MO=1500, GEN_COST=12000, GEN_MO=600, DIVERSE=1.4;
const RU_BOX=40000, RU_BOX_MO=2000;
const popCost=c=>POP_COST+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0);
const CN_LIC=150000, CN_JV_MO=6000, SCRUB_COST=60000, SCRUB_MO=5000;
const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000;
const LT=[{n:'10G',g:10,m:1},{n:'100G',g:100,m:2.8},{n:'400G',g:400,m:6},{n:'1.6T',g:1600,m:13},{n:'6.4T',g:6400,m:28}];
const PORT=[{n:'10G',g:10,setup:500,tmo:150,ix:400,pni:200},{n:'100G',g:100,setup:1500,tmo:400,ix:1500,pni:350},{n:'400G',g:400,setup:4000,tmo:900,ix:4000,pni:600},{n:'800G',g:800,setup:8000,tmo:1600,ix:7000,pni:1000}];
const RG=[
{n:'Rusty Router 9000',pn:'100G',cap:400,cost:0,mo:0,maxLT:1,maxP:1,lvl:1,blurb:'Bought used on eBuy. The fans sound like a jet engine.'},
{n:'Edge Lord 400',pn:'400G',cap:3200,cost:30000,mo:1000,maxLT:2,maxP:2,lvl:2,blurb:'Sharp, edgy, and finally speaks 400G and 400ZR+.'},
{n:'Chonk 800',pn:'800G',cap:12800,cost:90000,mo:3000,maxLT:4,maxP:3,lvl:3,blurb:'An absolute unit with 800G ports. Takes 800ZR+ optics.'},
{n:'Absolute Unit 1.6T',pn:'1.6T',cap:51200,cost:250000,mo:8000,maxLT:4,maxP:3,lvl:4,blurb:'1.6T ports and its own weather system. Needs a forklift.'},
];
const routerCost=g=>Math.round(ROUTER_COST+RG[g].cost*0.8);
// dark fiber & optical gear
const DF_SYS={
lite:{n:'Rainbow-in-a-Box DWDM',max:16,cost:25000,lvl:2,blurb:'Fixed mux plus amplifiers. Up to 16 channels, no remote switching.'},
roadm:{n:'ROADMaster 9000',max:64,cost:60000,lvl:3,blurb:'Full C-band, remotely reconfigurable, takes long-haul transponders. Up to 64 channels.'},
};
const AMP_EVERY=100, AMP_COST=8000, AMP_MO=300;
const OPT={
zr4:{n:'Ackackia 400ZR+',g:400,cost:12000,reach:1500,rg:1,lvl:2,sys:'lite',blurb:'Coherent pluggable in the router. No transponder shelf.'},
zr8:{n:'Sizzle 800ZR+',g:800,cost:22000,reach:900,rg:2,lvl:3,sys:'lite',blurb:'Twice the speed, shorter reach.'},
tp16:{n:'Sienna WaveMagic 1.6T',g:1600,cost:70000,reach:4000,rg:2,lvl:4,sys:'roadm',blurb:'Big shelf, big reach, big invoice.'},
};
const dfLeaseMo=km=>Math.round(400+km*1.0);
const dfBuildCost=km=>Math.round(25000+km*120);
const dfBuildDays=km=>Math.round(120+km*0.25);
const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY));
const fmtCap=g=>g>=1000?(+(g/1000).toFixed(1))+'T':g+'G';
const WAVECO=['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','Bolt Technology','youNetworks','GTT (Got Tangled Twice)'];
const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const REG={AM:'Americas',EU:'Europe',AF:'Africa',AS:'Asia',OC:'Oceania'};
const waveMo=(km,sub,tier)=>Math.round((300+km*1.2)*LT[tier].m*(sub?1.8:1));
const FABS=[
{id:'mgp',name:'Megapork',col:'#FF5A1F',cities:['icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','mrs','sto','mad','sin','hkg','tok','syd','jnb'],blurb:'Elastic interconnection, now with bacon. Spin up a circuit in 59 seconds, oink in 60.'},
{id:'pkf',name:'PocketFabric',col:'#00A896',cities:['sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra'],blurb:'A whole network fabric that fits in your pocket.'},
{id:'ccn',name:'Consolation Connect',col:'#8E44AD',cities:['icn','lon','fra','ams','mrs','bom','sin','hkg','tok','syd','lag','jnb'],blurb:'Strong in Asia and Africa. Every circuit comes with a consolation prize.'},
];
const FAB=Object.fromEntries(FABS.map(f=>[f.id,f]));
const NNI=[{n:'10G',g:10,mo:500},{n:'100G',g:100,mo:1200}];
const VXC=[{n:'10G',g:10,m:1},{n:'50G',g:50,m:2.4},{n:'100G',g:100,m:3.6}];
const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1));
const MET={prefer:{l:'Prefer',f:0.5},normal:{l:'Normal',f:1},avoid:{l:'Avoid',f:4},backup:{l:'Backup only',f:60}};
const PREF={high:'Prefer',normal:'Normal',low:'Backup only'};
const edgeKey=l=>l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;
const dfCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=OPT[c].g;const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>OPT[a].g-OPT[b].g)[0];if(fo)g-=OPT[fo].g;}return Math.max(0,g);};
const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1);
const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;};
const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='df'?(l.ready>S.day?'building':(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+OPT[c].g,0))+' DF':'dark'):LT[l.tier].n;
/* ================= WORLD ================= */
// Real-ish geography: lon/lat outlines, equirectangular, with gentle "magnifying lenses" over the busy regions.
const LENSES=[{lon:9,lat:49,r:170,m:1.25},{lon:121,lat:32,r:120,m:0.45},{lon:-80,lat:40,r:110,m:0.5}];
function proj0(lon,lat){return [(lon+180)/360*W,(84-lat)*6.4];}
for(const L of LENSES){const q=proj0(L.lon,L.lat);L.x=q[0];L.y=q[1];}
function proj(lon,lat){const q=proj0(lon,lat);let dx=0,dy=0;for(const L of LENSES){let ex=q[0]-L.x;ex-=W*Math.round(ex/W);const ey=q[1]-L.y,f=L.m*Math.exp(-(ex*ex+ey*ey)/(L.r*L.r));dx+=ex*f;dy+=ey*f;}return [q[0]+dx,q[1]+dy];}
function hav(lo1,la1,lo2,la2){const r=Math.PI/180,dLa=(la2-la1)*r,dLo=(lo2-lo1)*r,a=Math.sin(dLa/2)**2+Math.cos(la1*r)*Math.cos(la2*r)*Math.sin(dLo/2)**2;return 2*6371*Math.asin(Math.min(1,Math.sqrt(a)));}
const LANDS_LL=[{id:'am',ll:[[-166,68],[-157,71.2],[-141,69.8],[-128,70],[-115,68.5],[-97,68],[-94,62],[-92.5,57.5],[-85,55.2],[-80,51.5],[-78.5,58],[-77,62],[-70,61],[-64.5,60],[-61.5,56.5],[-57,52],[-55.6,49.5],[-53,47],[-59,46.5],[-61,45.2],[-66,44.5],[-70,43.3],[-70,42],[-74,40.6],[-76,38],[-75.8,35.5],[-77.5,34.5],[-79,33],[-81,31],[-80.05,27],[-80.1,25.3],[-81.5,25],[-82.7,27.5],[-84,30],[-89,30.2],[-94,29.5],[-97,28],[-97.5,25],[-97.7,22],[-96,19],[-94,18.3],[-91,18.5],[-90.4,21],[-87,21.5],[-88,17],[-88.5,15.8],[-84,15.8],[-83.4,12],[-83.7,10.5],[-81.5,9],[-79.5,9.5],[-77.5,8.6],[-75,10.8],[-71.5,12.3],[-68,10.6],[-62,10.5],[-60,8],[-57,6],[-52,5],[-50,1.5],[-48,-1],[-44,-2.5],[-39,-3.5],[-35,-5.5],[-35,-9],[-37.5,-12.5],[-39,-15],[-39.7,-19],[-41,-22],[-44,-23],[-48,-26],[-48.6,-28.5],[-51,-31],[-53,-34],[-58,-34.5],[-57,-37],[-62,-39],[-65,-41],[-64,-43],[-67.5,-46],[-66,-48],[-69,-51],[-68.5,-53],[-70,-55],[-73,-53],[-75,-48],[-73.5,-43],[-73.5,-37],[-71.5,-32],[-71.3,-27],[-70.5,-20],[-71.5,-17],[-76,-14],[-78,-10],[-81,-6],[-80.5,-3],[-80,0],[-79,1.5],[-77.5,4],[-77.4,7.5],[-80,7.3],[-82.5,8.2],[-85.7,10],[-87,12.5],[-91,14],[-94,16],[-96.5,15.7],[-100,17],[-105.5,20],[-105.5,22.5],[-108,25.5],[-110.8,27.9],[-113,31.3],[-114.7,31.7],[-113.5,29],[-112,26.5],[-110,24],[-109.5,23],[-112,24.8],[-114,27.5],[-115.5,29.8],[-117,32.5],[-118.5,34],[-120.6,34.6],[-122.5,37.5],[-124,40.5],[-124.5,43],[-124,46.2],[-124.7,48.4],[-123,49],[-126,50.5],[-130,54.5],[-133,57.5],[-137,58.5],[-141,60],[-146,61],[-150,59.5],[-152,58.5],[-156,57.5],[-158,56.8],[-162,55.5],[-164.5,54.5],[-158,58.5],[-162,60],[-165,61.5],[-166,64],[-164,65.5]]},{id:'eu',ll:[[-9,39],[-9.5,43],[-8,43.7],[-1.8,43.4],[-1.2,46],[-2.5,47.3],[-4.5,48],[-1.6,48.6],[1.5,50.2],[3,51.2],[4.5,52.5],[5,53.4],[7,53.6],[8.6,54],[8.2,55.5],[8.1,57],[10.5,57.7],[10.5,56.5],[11.2,56],[12.6,56.1],[12.7,55.6],[12.1,54.9],[11,54.3],[14,54],[18.5,54.8],[21,55.3],[21,57],[24,57.5],[24,59.2],[28,59.5],[30,60],[28,60.5],[25,60.1],[22.5,60.3],[21.5,61.5],[21.5,63],[25,65],[25.5,65.6],[22,65.8],[20.5,63.5],[18,62.5],[17.4,61],[19,59.8],[18,59],[16.5,57],[16,56.2],[14.2,55.4],[13,55.4],[12.9,56.5],[11.5,58],[10.5,59.3],[8,58],[5.5,58.5],[5,60],[5,62],[7,63],[10,64],[12.5,66],[15,68.5],[18,69.8],[21.5,70.2],[26,71],[30,70],[33,69.3],[41,67],[44,68.5],[53,68.5],[58,69],[68,69],[69,72.8],[73,72.5],[80,73.5],[87,74.8],[100,76],[104,77.7],[112,74],[113.5,73.5],[127,73.5],[132,71.5],[140,72.5],[150,71.5],[160,70],[170,70],[180,69],[190,66.5],[186,64.5],[182,65],[178,62.5],[173,61],[170,60],[164,60],[164,57],[162,55],[159,52],[156.7,51],[156,55.5],[157,58],[155,59.5],[150,59.5],[143,59.3],[137,54.5],[141,53],[140,48.5],[135,43.5],[131,42.7],[129.5,41],[129.4,37],[129.4,35.5],[127.5,34.6],[126.3,34.8],[126.5,37],[125,37.8],[124.5,39.7],[121.5,39],[121.7,40.8],[119,39.3],[117.8,38.5],[119,37.2],[122.5,37.3],[120.5,36],[119.2,35],[121,32],[121.9,30.8],[121.5,28],[119.5,25.5],[116.5,23],[114.3,22.1],[111,21.5],[109.7,20.5],[108.5,21.6],[106.5,20],[106,18],[108.5,15],[109.3,12],[107,10.5],[105,8.6],[104.8,10.3],[103,11],[100.9,12.6],[100,13.4],[99.3,10.5],[100.3,7],[101,6.8],[103.4,4],[104.3,1.4],[103.6,1.25],[101.3,2.8],[100.2,5.3],[98.3,8],[98.6,13],[97.7,16.5],[94.4,16.2],[94.2,18.8],[92.3,20.6],[91.8,22.6],[90,22],[88.3,21.6],[86.9,20.6],[85,19.5],[82.3,16.6],[80.3,15.8],[80.3,13.5],[79.8,10.3],[78.3,8.9],[77.5,8.1],[76.5,8.9],[75.8,11.5],[74.8,12.9],[73.5,16],[72.8,19],[72.7,21.2],[70,22.5],[68.5,23.5],[66.6,25.4],[61.6,25.2],[57.3,25.8],[56.4,27.1],[54.7,26.5],[51.5,27.9],[50,30],[48,30],[48.4,28.5],[49.5,26.7],[50.8,24.8],[51.6,24.2],[52.6,24.2],[54.6,24.5],[56,26.2],[56.4,24.5],[57.8,23.8],[58.8,22.5],[59.8,22.4],[58.5,20.5],[57.7,19],[55.4,17.7],[52.2,15.7],[48.7,14],[45,12.8],[43.4,12.6],[42.7,15.7],[42.5,17.2],[41,19.5],[39.1,21.6],[38.4,23.6],[37,25.5],[35.2,28],[34.9,29.5],[34.3,27.8],[33,28.8],[32.6,30],[32.3,31.2],[34.2,31.3],[34.9,32.8],[35.6,34.5],[36,35.8],[36.2,36.7],[34.5,36.8],[32.5,36.1],[30.5,36.4],[29,36.6],[27.3,37.4],[26.3,38.6],[26.5,40],[26.2,40.6],[24,40.8],[22.6,40.4],[23.5,38],[22.3,36.5],[21.7,36.8],[21.2,38.4],[19.5,40],[19.5,41.8],[18.5,42.5],[16,43.5],[13.7,45.6],[12.3,45.3],[12.4,44.2],[13.6,43.5],[15.9,41.6],[18.5,40.2],[17,39],[16.6,38],[15.6,38],[16.1,39],[15.6,40.1],[14.3,40.6],[12.5,41.6],[11,42.5],[10.2,43.9],[8.8,44.4],[7.5,43.8],[6,43.1],[4,43.5],[3.1,43.1],[3.2,41.9],[0.8,41],[0,39.5],[-0.3,38.4],[-0.8,37.6],[-2.1,36.7],[-4.4,36.7],[-5.6,36],[-6.3,36.8],[-7.4,37.2],[-8.9,37]]},{id:'af',ll:[[-17.5,14.7],[-17,21],[-16,24],[-13,27.5],[-9.8,30],[-9.2,32.5],[-6.8,34],[-5.9,35.8],[-2,35.1],[1,36.5],[5,36.8],[9.8,37.3],[11,36.9],[10.2,35.2],[11.1,33.3],[15.2,32.3],[19,30.3],[20.1,32],[23,32.6],[25,31.7],[29,30.9],[32.2,31.3],[32.6,30],[33.5,28],[35.5,24],[37.2,21],[38.5,18],[39.6,15.5],[41.6,13.5],[43.3,12.4],[44,10.4],[47,11.1],[51.2,11.8],[51,10.4],[49.5,7],[47.8,4.5],[45,1.6],[42,-1],[40.2,-2.8],[39.3,-4.8],[38.8,-6.5],[39.6,-10],[40.5,-11],[40.6,-14.6],[37,-17.5],[35.4,-22],[35.5,-24],[32.9,-25.9],[32.5,-28.6],[31,-29.9],[28,-32.7],[25.6,-33.9],[22.5,-34],[20,-34.8],[18.4,-34],[17.9,-32.5],[16.5,-28.6],[15.2,-27],[14.4,-23],[12.8,-19],[11.8,-16.8],[12.2,-14.5],[13.6,-12.2],[13.2,-8.8],[12.3,-6],[11.8,-3.5],[9.5,-1],[9.4,1],[9.8,3.2],[8.9,4.5],[6,4.3],[4.3,6.3],[1.6,6.2],[-2,4.8],[-4.6,5.2],[-7.5,4.4],[-9.4,5.4],[-11.5,6.9],[-13.2,8.7],[-15,10.9],[-16.7,12.4]]},{id:'uk',ll:[[-5.7,50.1],[-3,50.6],[1.4,51.2],[1.7,52.7],[0.3,53.4],[-0.2,54.3],[-1.6,55.6],[-2,56.4],[-1.8,57.6],[-3.4,58.6],[-5,58.6],[-6.2,57.5],[-5.6,56.3],[-5,55],[-3.2,54.9],[-3.4,54],[-3,53.4],[-4.6,53.3],[-4.2,52.2],[-5.2,51.7],[-3.2,51.4],[-4.6,51]]},{id:'ie',ll:[[-6,52.2],[-6.2,53.5],[-5.6,54.6],[-6.4,55.2],[-7.4,55.4],[-8.5,54.5],[-10,54.2],[-9.6,53.2],[-10.2,51.9],[-9.6,51.5],[-8.2,51.8]]},{id:'is',ll:[[-22.5,63.9],[-24,65.5],[-22,66.4],[-16,66.5],[-14.5,65.3],[-14.6,64.4],[-18,63.4]]},{id:'jp',ll:[[129.6,33.3],[130.2,31.3],[131.4,31.5],[132,33],[133.5,33.4],[135.2,33.6],[136.8,34.3],[138.8,34.6],[140,35],[140.8,35.7],[141,38.2],[141.9,39.5],[141.4,41.4],[140,41.4],[139.9,40.3],[139.8,38.5],[138.8,37.8],[137.3,36.9],[136,36],[135.4,35.6],[133,35.5],[131.5,34.6],[130.9,34]]},{id:'oc',ll:[[113.5,-22],[114,-26.5],[115,-30],[115.7,-33.6],[115,-34.3],[117.9,-35.1],[123.5,-33.9],[126,-32.3],[131,-31.5],[134,-32.8],[135.6,-34.8],[137.6,-35.6],[138.5,-34.6],[139.6,-36.9],[141.5,-38.4],[144.9,-37.9],[146.4,-39.1],[150,-37.5],[150.8,-34.5],[152.5,-32.4],[153.6,-28.5],[153,-25],[150.8,-22.5],[149,-20.6],[146.3,-18.9],[145.4,-16],[145.3,-14.9],[143.5,-12.3],[142.5,-10.7],[141.6,-12.8],[141.6,-16],[140.6,-17.6],[139.3,-17.4],[137,-15.9],[135.8,-15],[136.8,-12.2],[135,-12],[132.6,-11.5],[131,-12.2],[129.5,-14.9],[128,-15.4],[126.5,-13.9],[124.5,-16.5],[122.2,-18.2],[121,-19.7],[118.5,-20.3],[116.7,-20.6],[114.6,-21.8]]},{id:'nz',ll:[[172.7,-34.4],[174.5,-36],[175.9,-37.5],[178.5,-37.7],[177.9,-39.2],[176.9,-39.6],[175.2,-41.6],[174.6,-41.2],[174.9,-39.9],[173.8,-39.3],[174.6,-38.1],[174.5,-37.3],[173.1,-35.3]]},{id:'idn',ll:[[105.2,-6.8],[106.8,-6.1],[108.5,-6.4],[110.5,-6.9],[112.6,-6.9],[114.6,-7.7],[114.4,-8.7],[111,-8.3],[108,-7.8],[105.5,-7]]},{id:'ph',ll:[[120.6,18.5],[122.2,18.5],[122,16.5],[121.6,14.2],[124,13.8],[124,12.5],[123.3,13],[121,13.6],[120.6,14.5],[119.8,16.2]]}];
const LANDS=LANDS_LL.map(l=>({id:l.id,pts:l.ll.map(q=>proj(q[0],q[1]))}));
const DECOR=[[[-73,78],[-60,81.5],[-35,82.5],[-20,81.5],[-18,77],[-20,72],[-23,70],[-30,68],[-38,65.5],[-43,60],[-48,61],[-52,64.5],[-54,68],[-55,71],[-60,76],[-68,77]],[[-80,73.5],[-72,71.5],[-67,69.5],[-62,66.5],[-64,63],[-71,62.5],[-78,64],[-83,66],[-88,70],[-85,73]],[[-110,76],[-95,77],[-80,79],[-70,82],[-90,82.3],[-105,79]],[[-118,73],[-105,72],[-100,69.5],[-110,68.8],[-118,70]],[[140,41.5],[141.6,42.4],[143.3,42],[145.6,43.3],[144.5,44],[141.9,45.5],[141.4,43.4],[140,42.6]],[[120.1,23],[121,25.2],[121.9,25],[121.5,22.5],[120.8,21.9]],[[122,11],[125.5,11.5],[126.5,9.5],[126.2,6.5],[124,6.5],[122,7]],[[95.3,5.6],[98,4],[100.3,2],[103.8,-1],[106,-3],[106,-5.9],[104.5,-5.9],[102.3,-4],[100.3,-1],[97.5,2.4],[95.2,4]],[[109.6,2],[111,1.6],[113,3.2],[115.5,5.2],[117.2,6.9],[119,5],[118,2],[117.5,0.6],[116.2,-2.5],[116,-4],[114.5,-3.4],[111.7,-3],[110,-1.6],[109,0.5]],[[119,-5.5],[120.5,-1],[121.5,1],[125,1.5],[123,-1],[121.5,-4.5]],[[131,-1.2],[134,-0.8],[138,-1.6],[141,-2.6],[145,-4.3],[147.5,-6],[147.5,-8],[146,-8],[143.4,-9.1],[141,-9.1],[139,-8],[138,-8.5],[137.7,-5.6],[134,-4],[132,-2.8]],[[172.6,-40.5],[174.3,-41.7],[173,-43.5],[171.2,-44.5],[170.6,-45.9],[169.2,-46.6],[166.5,-46],[167,-45],[168.4,-44],[170.8,-42.6],[171.5,-41.7]],[[144.6,-40.7],[148.3,-40.9],[148,-43.2],[146,-43.5]],[[49.3,-12],[50.5,-15.5],[49.5,-17.5],[47.1,-24.9],[45,-25.5],[43.8,-23.6],[43.3,-21],[44.4,-16.2],[46.5,-15.7],[48,-13.5]],[[79.8,9.8],[81.9,7.5],[81.2,6.2],[80,6],[79.7,8.2]],[[-85,21.9],[-82,23.2],[-77.5,22.3],[-74.2,20.2],[-77.7,19.9],[-80.5,21.8]],[[-74.5,18.5],[-72,19.9],[-68.4,18.6],[-70,18.2]],[[12.4,38.1],[15.6,38.3],[15.1,36.7]],[[8.2,41],[9.8,41.1],[9.6,39.1],[8.4,39]],[[11,78],[17,80],[27,80],[20,77]],[[52,71],[56,74],[64,76.5],[68,77],[58,74],[54,71]],[[142,46],[143.5,49],[143,54],[142,53],[141.8,48]],[[108.7,19],[111,19.7],[110,18.2]]].map(poly=>poly.map(q=>proj(q[0],q[1])));
const CITY_LL={"bcn":[2.17,41.39],"stg":[9.18,48.78],"ber":[13.4,52.52],"zrh":[8.54,47.37],"nbo":[36.82,-1.29],"cai":[31.24,30.04],"sea":[-122.33,47.61],"sjc":[-121.89,37.34],"lax":[-118.24,34.05],"dal":[-96.8,32.78],"chi":[-87.63,41.88],"ash":[-77.49,39.04],"nyc":[-74.0,40.71],"mia":[-80.19,25.76],"tor":[-79.38,43.65],"mtl":[-73.57,45.5],"mex":[-99.13,19.43],"sao":[-46.63,-23.55],"lon":[-0.13,51.51],"dub":[-6.26,53.35],"rek":[-21.94,64.15],"ams":[4.9,52.37],"fra":[8.68,50.11],"par":[2.35,48.86],"mrs":[5.37,43.3],"mad":[-3.7,40.42],"sto":[18.07,59.33],"osl":[10.75,59.91],"cph":[12.57,55.68],"hel":[24.94,60.17],"beg":[20.46,44.79],"sof":[23.32,42.7],"mos":[37.62,55.76],"lag":[3.38,6.52],"jnb":[28.05,-26.2],"dxb":[55.27,25.2],"bom":[72.88,19.08],"sin":[103.82,1.35],"jkt":[106.85,-6.2],"mnl":[120.98,14.6],"hkg":[114.17,22.32],"sha":[121.47,31.23],"pek":[116.4,39.9],"icn":[126.98,37.57],"tok":[139.69,35.69],"syd":[151.21,-33.87],"per":[115.86,-31.95],"akl":[174.76,-36.85]};
const CITIES=[
{id:'sea',name:'Seattle',x:205,y:245,land:'am',reg:'AM',P:300,ix:'Sea-IX',dc:'Westin-ish Carrier Hotel'},
{id:'sjc',name:'San Jose',x:240,y:345,land:'am',reg:'AM',P:500,ix:'Silly-Con Valley IX',dc:'Equinox SV-ish'},
{id:'dal',name:'Dallas',x:385,y:415,land:'am',reg:'AM',P:450,ix:'Yee-Haw-IX',dc:'Infomart-ish'},
{id:'chi',name:'Chicago',x:470,y:270,land:'am',reg:'AM',P:600,ix:'Windy-IX',dc:'350 Cermak-ish'},
{id:'ash',name:'Ashburn',x:572,y:332,land:'am',reg:'AM',P:250,ix:'Equinox Ashburn IX',dc:'Data Center Alley',note:'The data-center capital. Rumor says 70% of the internet passes through here, and nobody has checked.'},
{id:'nyc',name:'New York',x:615,y:283,land:'am',reg:'AM',P:1200,ix:'NY-Yikes',dc:'60 Hudson-ish'},
{id:'mia',name:'Miami',x:530,y:482,land:'am',reg:'AM',P:400,ix:'Miam-IX',dc:'NAP of the Americas-ish',note:'Cable landing hub for South America.'},
{id:'sao',name:'São Paulo',x:640,y:730,land:'am',reg:'AM',P:900,ix:'IX.brrr',dc:'Digital Reality SP'},
{id:'lon',name:'London',x:935,y:275,land:'uk',reg:'EU',P:1000,ix:'LYNX',dc:'Telehouse-ish Docklands',note:'On an island, so every link off it is a subsea cable.'},
{id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',P:350,ix:'HAMS-IX',dc:'Science Park-ish'},
{id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',P:600,ix:'DE-KICKS',dc:'Kleyer-ish Campus',note:'Europe\'s crossroads. Lots of networks, lots of sausages.'},
{id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',P:900,ix:'Fromage-IX',dc:'Interaction PAR'},
{id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:'Subsea cables to Africa and Asia land here.'},
{id:'tor',name:'Toronto',x:548,y:252,land:'am',reg:'AM',P:500,ix:'Sorry-IX',dc:'151 Front Street-ish',note:'Canada’s hub. Polite packets, long winters, free cooling.'},
{id:'mtl',name:'Montreal',x:598,y:238,land:'am',reg:'AM',P:300,ix:'Poutine-IX',dc:'Hydro-powered Hangar',note:'Cheap hydro power makes it a data center favorite.'},
{id:'lax',name:'Los Angeles',x:270,y:395,land:'am',reg:'AM',P:900,ix:'Any2-Anywhere',dc:'One Wilshire-ish',note:'Pacific cables land nearby, and everyone meets in one famous building downtown.'},
{id:'mex',name:'Mexico City',x:368,y:470,land:'am',reg:'AM',P:700,ix:'',dc:'Querétaro-ish Campus',note:'Huge mobile market. Most of its traffic still detours through the US.'},
{id:'rek',name:'Reykjavik',x:850,y:170,land:'is',reg:'EU',P:60,ix:'',dc:'Geothermal Bitcoin Barn',note:'Free cooling and geothermal power. Plenty of data centers, very few cables.'},
{id:'dub',name:'Dublin',x:876,y:268,land:'ie',reg:'EU',P:250,ix:'Craic-IX',dc:'Hyperscale Campus Clonsilla-ish',note:'Every hyperscaler’s European HQ, mostly for tax reasons. The power grid is nervous.'},
{id:'osl',name:'Oslo',x:1062,y:172,land:'eu',reg:'EU',P:200,ix:'NIX-NIX',dc:'Fjord-cooled Mountain Hall'},
{id:'cph',name:'Copenhagen',x:1085,y:215,land:'eu',reg:'EU',P:250,ix:'Hygge-IX',dc:'Danish Design DC',note:'Landing point for cables from the US, Iceland and the Baltic.'},
{id:'hel',name:'Helsinki',x:1168,y:140,land:'eu',reg:'EU',P:200,ix:'Sauna-IX',dc:'Underground Sauna Bunker',note:'Fast fiber east and west, and one very nervous subsea cable to Germany.'},
{id:'beg',name:'Belgrade',x:1122,y:338,land:'eu',reg:'EU',P:250,ix:'',dc:'Danube Docks DC'},
{id:'sof',name:'Sofia',x:1165,y:358,land:'eu',reg:'EU',P:250,ix:'Rakija-IX',dc:'Vitosha-ish DC',note:'Balkan peering hub with famously cheap ports.'},
{id:'dxb',name:'Dubai',x:1292,y:428,land:'eu',reg:'AS',P:400,ix:'Sand-IX',dc:'Air-conditioned Mirage DC',note:'Crossroads for cables between Europe, Asia and Africa. Some voice apps are blocked, and the A/C bill is legendary.'},
{id:'mos',name:'Moscow',x:1235,y:192,land:'eu',reg:'EU',P:900,ru:true,arpu:0.5,ix:'Borscht-IX',dc:'Very Secure Bunker',note:'Sovereign internet rules: every POP needs a government box in the rack, Goggle video is throttled, and the national firewall runs drills.'},
{id:'akl',name:'Auckland',x:1964,y:826,land:'nz',reg:'OC',P:250,ix:'Kiwi-IX',dc:'Sheep-cooled Shed',note:'Far from everything. Every packet here has a long journey home.'},
{id:'per',name:'Perth',x:1712,y:785,land:'oc',reg:'OC',P:200,ix:'',dc:'Very Remote DC',note:'The most isolated big city on Earth. Asia is closer than Sydney.'},
{id:'jkt',name:'Jakarta',x:1614,y:624,land:'idn',reg:'AS',P:900,ix:'Nasi-IX',dc:'Monsoon-proof DC',note:'270 million people on 17,000 islands. Mobile first, and very hungry for bandwidth.'},
{id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',P:600,ix:'',dc:'Typhoon-rated DC',note:'Typhoons, earthquakes and a lot of very online people.'},
{id:'ber',name:'Berlin',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'Currywurst-IX',dc:'Former Brewery DC',note:'Startups, techno and a surprising number of data centers in old breweries.'},
{id:'zrh',name:'Zurich',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Cuckoo-IX',dc:'Bank Vault DC',note:'Banks, very punctual packets, and racks inside old bank vaults.'},
{id:'nbo',name:'Nairobi',x:0,y:0,land:'af',reg:'AF',P:350,ix:'Safari-IX',dc:'Silicon Savannah Campus',note:'East Africa’s hub. Cables land in Mombasa, and mobile money runs everything.'},
{id:'cai',name:'Cairo',x:0,y:0,land:'af',reg:'AF',P:600,ix:'Pharaoh-IX',dc:'Pyramid-adjacent DC',note:'Almost every Europe–Asia cable crosses Egypt. The tolls are legendary.'},
{id:'stg',name:'Stuttgart',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Spätzle-IX',dc:'Kehrwoche-certified DC',ixOnly:true,note:'Cars, engineers and Kehrwoche: every rack is swept on a strict rota. Nobody sells transit here, there is only the Spätzle-IX. Peer locally or haul your traffic to Frankfurt.'},
{id:'sto',name:'Stockholm',x:1110,y:160,land:'eu',reg:'EU',P:300,ix:'NodNod',dc:'Bunker-ish DC'},
{id:'bcn',name:'Barcelona',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Catnip-IX',dc:'Poblenou-ish DC',note:'Catalonia’s own exchange. Small and proud, and local networks find it impossible to resist.'},
{id:'mad',name:'Madrid',x:935,y:392,land:'eu',reg:'EU',P:600,ix:'Siesta-IX',dc:'Interaction MAD'},
{id:'lag',name:'Lagos',x:1010,y:565,land:'af',reg:'AF',P:500,ix:'Jollof-IX',dc:'Rack Centre-ish'},
{id:'jnb',name:'Johannesburg',x:1130,y:730,land:'af',reg:'AF',P:400,ix:'Braai-IX',dc:'Teraco-ish'},
{id:'bom',name:'Mumbai',x:1385,y:488,land:'eu',reg:'AS',P:1100,ix:'Mumb-IX',dc:'Nesco-ish'},
{id:'sin',name:'Singapore',x:1556,y:568,land:'eu',reg:'AS',P:450,ix:'Lah-IX',dc:'Equinox SG-ish',note:'Asia\'s hub. Expensive, humid, very well connected.'},
{id:'hkg',name:'Hong Kong',x:1645,y:440,land:'eu',reg:'AS',P:600,ix:'HK-Kicks',dc:'Mega-ish Plus'},
{id:'icn',name:'Seoul',x:1722,y:302,land:'eu',reg:'AS',P:900,ix:'Kimch-IX',dc:'Gasan-ish Digital Complex',note:'Some of the fastest home broadband on the planet. The eyeballs here expect a lot.'},
{id:'pek',name:'Beijing',x:1652,y:318,land:'eu',reg:'AS',P:1800,cn:true,arpu:0.6,ix:'',dc:'Zhongguancun-ish DC',note:'Mainland China. Behind the Great Firewall, with its own rules for foreign networks.'},
{id:'sha',name:'Shanghai',x:1680,y:388,land:'eu',reg:'AS',P:2200,cn:true,arpu:0.6,ix:'',dc:'Lujiazui-ish Data Center',note:'Mainland China. Enormous market, strict rules, and a famously congested border.'},
{id:'tok',name:'Tokyo',x:1795,y:320,land:'jp',reg:'AS',P:1400,ix:'JP-Naptime',dc:'Otemachi-ish'},
{id:'syd',name:'Sydney',x:1860,y:790,land:'oc',reg:'OC',P:500,ix:'Roo-IX',dc:'Global Swish'},
];
// Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat.
const CITY_NUDGE={stg:[30,6],fra:[-8,-8],bcn:[-6,-4]};
for(const c of CITIES){const q=CITY_LL[c.id];if(q){c.lon=q[0];c.lat=q[1];const pt=proj(q[0],q[1]),n=CITY_NUDGE[c.id]||[0,0];c.x=pt[0]+n[0];c.y=pt[1]+n[1];}}
const CITY=Object.fromEntries(CITIES.map(c=>[c.id,c]));
const CABLES=[
{"id":"marea","name":"Marea Carey","price":0.8,"age":"new","blurb":"Hits the high notes across the Atlantic. Huge capacity, cheap waves.","pairs":[["ash","mad",[[-74,36.5],[-50,40],[-25,43],[-10,44]]]]},
{"id":"grace","name":"Grace Hopscotch","price":0.85,"age":"new","blurb":"Hops from New York to the UK and Spain.","pairs":[["nyc","lon",[[-72,40],[-50,47],[-25,50],[-10,50.5]]],["nyc","mad",[[-72,39.8],[-50,42],[-25,43.2],[-10,43.8]]]]},
{"id":"dunant","name":"Dunno-ant","price":0.85,"age":"new","blurb":"Nobody remembers who it is named after.","pairs":[["ash","par",[[-74,36.8],[-50,42],[-25,46],[-5,47.3]]]]},
{"id":"amitie","name":"Amitié-ish","price":0.9,"age":"new","blurb":"A friendly cable with French manners.","pairs":[["nyc","lon",[[-70,41.5],[-50,46],[-25,49],[-8,50.3]]],["nyc","par",[[-70,41.3],[-50,45],[-25,47.5],[-5,47.6]]]]},
{"id":"hibx","name":"Hibernia Express-o","price":1.7,"age":"mid","blurb":"The straightest line across the Atlantic. Traders pay double to save a few milliseconds.","pairs":[["nyc","lon",[[-68,42],[-55,46.5],[-30,52.5],[-12,52.5]]]],"lat":0.9},
{"id":"tat","name":"TAT-14 Retirement Home","price":1.3,"age":"old","blurb":"Laid last century. Cuts often, costs more, still somehow running.","pairs":[["nyc","ams",[[-70,41],[-45,48],[-20,52],[0,54],[3,53.5]]]]},
{"id":"ella","name":"EllaLink-ing","price":1.0,"age":"new","blurb":"Brazil straight to Iberia, skipping the US entirely.","pairs":[["sao","mad",[[-44,-24.5],[-38,-14],[-34,-6],[-30,5],[-22,20],[-14,33],[-10,37.5]]]]},
{"id":"sacs","name":"SACS-y Cable","price":1.0,"age":"mid","blurb":"South Atlantic, cool and confident.","pairs":[["sao","lag",[[-44,-24.5],[-35,-10],[-15,-3],[0,2],[3,5.5]]]]},
{"id":"col3","name":"Columbus III-and-a-half","price":1.4,"age":"old","blurb":"Discovered the Atlantic again. Old, pricey and fragile.","pairs":[["mia","mad",[[-79,26],[-60,30],[-30,35],[-10,36.5]]]]},
{"id":"twoaf","name":"2Africa-n-Back","price":0.75,"age":"new","blurb":"All the way around Africa and back. Cheapest capacity on the map.","pairs":[["lon","lag",[[-6,49],[-12,40],[-20,20],[-18,8],[-5,3],[3,5.5]]],["jnb","mrs",[[32,-30],[40,-20],[45,-5],[52,10],[45,12.3],[44,12.4],[41,15.1],[38,21.1],[35,26.1],[33,29.6],[32.4,31.3],[30,32.1],[20,34.1],[12,37.6],[6,42.5]]],["mrs","bom",[[6,42.5],[12,37.6],[20,34.1],[30,32.1],[32.4,31.3],[33,29.6],[35,26.1],[38,21.1],[41,15.1],[44,12.4],[52,13],[62,18],[70,19]]]]},
{"id":"equi","name":"Equi-yes","price":0.8,"age":"new","blurb":"Always agrees with you. Iberia to West Africa.","pairs":[["mad","lag",[[-10,38],[-15,28],[-18,15],[-14,5],[-2,3],[3,5.8]]]]},
{"id":"smw6","name":"SEE-ME-WAVE 6","price":0.95,"age":"new","blurb":"Sixth in a long-running series. Europe to India to Singapore.","pairs":[["mrs","bom",[[6.4,42.74],[12.4,37.84],[20.4,34.34],[30.4,32.34],[32.8,31.54],[33.4,29.84],[35.4,26.34],[38.4,21.34],[41.4,15.34],[44.4,12.64],[52,13.4],[62,18.4],[70,19.4]]],["bom","sin",[[72,17],[76,8],[80.5,5],[90,5],[96,5.5],[100,4],[103,1.5]]],["mrs","sin",[[6.4,42.74],[12.4,37.84],[20.4,34.34],[30.4,32.34],[32.8,31.54],[33.4,29.84],[35.4,26.34],[38.4,21.34],[41.4,15.34],[44.4,12.64],[52,12.8],[62,12.5],[75,6.8],[80.5,5.2],[92,5.8],[97,5.8],[100.5,4],[103,1.7]]]]},
{"id":"peace","name":"PEACE-out","price":0.85,"age":"new","blurb":"Marseille to Singapore, then it leaves the party.","pairs":[["mrs","sin",[[5.6,42.26],[11.6,37.36],[19.6,33.86],[29.6,31.860000000000003],[32.0,31.060000000000002],[32.6,29.360000000000003],[34.6,25.860000000000003],[37.6,20.860000000000003],[40.6,14.86],[43.6,12.16],[52,12.2],[62,11.8],[75,6.3],[80.5,4.6],[92,5.2],[97,5.3],[100.5,3.6],[103,1.4]]]]},
{"id":"aae","name":"AAE-1-ish","price":1.0,"age":"mid","blurb":"Asia, Africa, Europe, and one more thing.","pairs":[["mrs","hkg",[[6.8,42.98],[12.8,38.08],[20.8,34.58],[30.8,32.58],[33.199999999999996,31.78],[33.8,30.080000000000002],[35.8,26.580000000000002],[38.8,21.580000000000002],[41.8,15.58],[44.8,12.88],[52,11.8],[62,11.4],[75,6],[80.5,4.4],[92,5],[97,5],[100.5,3.3],[104.5,1.5],[107,5],[110,10],[113,18],[114.2,21.8]]],["sin","hkg",[[104.5,1.5],[108,6],[111,12],[114,20],[114.2,22]]]]},
{"id":"apg","name":"A Pretty Gateway","price":0.9,"age":"mid","blurb":"The pretty way around East Asia.","pairs":[["sin","hkg",[[105,2],[109,7],[112,13],[114.6,20],[114.4,22]]],["hkg","tok",[[116,21.5],[122,24],[126,28],[132,32],[137,33.8],[139.8,35]]],["hkg","icn",[[116,22],[122,26],[125,32],[126,35],[126.2,36.8]]],["tok","icn",[[136,33.8],[130,33.5],[128,34.5],[126.5,35.5]]],["tok","sha",[[135,33.5],[128,31.5],[122.5,31.2]]]]},
{"id":"jup","name":"Jupiterrible","price":0.9,"age":"new","blurb":"Named after a planet, behaves like one: big and far away.","pairs":[["lax","tok",[[-121,33.5],[-145,32],[-175,32],[-200,33],[-218,34.5]]]]},
{"id":"fast","name":"FASTEST","price":0.85,"age":"mid","blurb":"Its predecessor was FASTER. Marketing had a good day.","pairs":[["sea","tok",[[-125,46],[-150,45],[-180,42],[-205,38],[-218,35]]]]},
{"id":"ncp","name":"New Cross Pacific-ish","price":1.0,"age":"mid","blurb":"Crosses the Pacific, mildly annoyed about it.","pairs":[["sea","icn",[[-125,46.5],[-155,46.5],[-185,42],[-212,33],[-229,33.8],[-232,36]]],["sea","sha",[[-125,46.2],[-155,45.5],[-185,40],[-212,31],[-236,30.5]]]]},
{"id":"plcn","name":"Pacific Light-ish","price":1.1,"age":"mid","blurb":"Lighter on paperwork than its namesake. Still heavy on paperwork.","pairs":[["lax","hkg",[[-121,33],[-150,25],[-180,22],[-215,21],[-240,21.5]]]]},
{"id":"scx","name":"Southern Cross-ed Fingers","price":1.2,"age":"old","blurb":"Old Pacific workhorse. Everyone hopes it holds.","pairs":[["sjc","syd",[[-123,37],[-150,20],[-175,0],[-190,-20],[-200,-30],[-207,-33.5]]],["akl","syd",[[168,-37],[158,-35]]]]},
{"id":"hwk","name":"Hawaiki-wiki","price":0.95,"age":"new","blurb":"Quick Pacific crossing with a stop for snacks.","pairs":[["sea","syd",[[-125,45],[-150,20],[-170,-5],[-185,-25],[-200,-32],[-206,-33.8]]],["akl","sea",[[178,-34],[190,-20],[210,10],[230,40],[234.5,47]]]]},
{"id":"indigo","name":"Indigo-go","price":0.9,"age":"new","blurb":"Singapore to Sydney in one go, via Perth.","pairs":[["sin","syd",[[104.5,0],[107,-8],[113,-12],[112,-25],[114,-35],[130,-37],[145,-41],[152,-36]]],["sin","per",[[104.6,0],[107.2,-8],[113,-14],[112.5,-25],[115,-31.8]]]]},
{"id":"guam","name":"Guam-bling","price":1.1,"age":"mid","blurb":"A bet on a tiny island in the middle of the Pacific.","pairs":[["tok","syd",[[142,33],[146,15],[152,0],[156,-20],[152.5,-33]]]]},
{"id":"ohman","name":"Oh-Man Australia Cable","price":1.0,"age":"new","blurb":"Perth to the Gulf across the Indian Ocean. Oh man, it is long.","pairs":[["per","dxb",[[113,-31],[100,-25],[80,-10],[65,10],[59,20],[57,24.5]]]]},
{"id":"tasman","name":"Tasman Global Excess","price":0.95,"age":"new","blurb":"Sydney to Auckland with plenty to spare.","pairs":[["akl","syd",[[170,-36],[158,-34.5]]]]},
{"id":"bifrost","name":"Bi-Frosted","price":0.9,"age":"new","blurb":"A rainbow bridge from Singapore to California, via Jakarta and Manila.","pairs":[["sin","jkt",[[105,-1],[106,-4]]],["jkt","mnl",[[108,-5],[112,-3],[118,2],[122,6],[121,10],[120,13.5]]],["mnl","lax",[[123,15],[140,20],[180,25],[210,30],[235,33.5]]]]},
{"id":"sjcph","name":"Sushi-Jollibee Cable","price":0.9,"age":"mid","blurb":"Southeast Asia to Japan, with snacks.","pairs":[["hkg","mnl",[[116,21],[119.5,16],[120.3,14.6]]],["mnl","sin",[[119,12],[115,8],[110,5],[105,2]]],["mnl","tok",[[122,19],[127,24],[133,30],[138.5,34.5]]]]},
{"id":"farice","name":"Far-Ice-1","price":1.2,"age":"old","blurb":"Iceland’s lifeline to Scotland. Lonely but determined.","pairs":[["rek","lon",[[-20,63],[-10,61],[-4,59],[-1.5,57]]]]},
{"id":"danice","name":"Dance-Ice","price":1.0,"age":"mid","blurb":"Iceland to Denmark, choreographed.","pairs":[["rek","cph",[[-18,63],[-5,62],[5,59],[8.5,57.5],[11,57]]]]},
{"id":"gcon","name":"Greenland Connect-the-Dots","price":1.4,"age":"old","blurb":"Hops via Greenland. Polar bears included.","pairs":[["rek","mtl",[[-26,63.5],[-42,60],[-55,53],[-60,48],[-66,47],[-70,46.5]]]]},
{"id":"iris","name":"IRIS-ish","price":0.9,"age":"new","blurb":"Iceland to Ireland, brand new and still smells like plastic.","pairs":[["rek","dub",[[-22,63],[-15,58],[-10.5,54.5],[-9,53.3]]]]},
{"id":"aec","name":"AEConnect-the-Dots","price":0.85,"age":"new","blurb":"New York to Ireland: the tech-tax express.","pairs":[["nyc","dub",[[-70,41],[-50,47],[-25,52],[-11,52.8]]]]},
{"id":"havf","name":"Havfun","price":0.8,"age":"new","blurb":"Danish for “sea fun”. Probably.","pairs":[["nyc","cph",[[-70,41.5],[-50,49],[-25,55],[-10,58],[0,58],[7,57.5],[10,57.6]]],["dub","cph",[[-10,54.5],[-8,57],[-2,59],[6,58],[10,57.6]]]]},
{"id":"celtix","name":"Celtix Connected","price":0.7,"age":"mid","blurb":"Dublin to London across the Irish Sea.","pairs":[["dub","lon",[[-5,53.4]]]]},
{"id":"falcon","name":"Falcon Punch","price":0.9,"age":"mid","blurb":"Dubai to Mumbai. Hits hard.","pairs":[["dxb","bom",[[57,25.5],[60,23],[66,21],[71,19]]]]},
{"id":"eig","name":"Eye-Gee","price":1.0,"age":"mid","blurb":"Europe-India Gateway-ish, through the Red Sea.","pairs":[["dxb","mrs",[[57,25],[59,22],[55,16],[48,12.8],[43.2,11.92],[40.2,14.62],[37.2,20.62],[34.2,25.62],[32.2,29.12],[31.599999999999998,30.82],[29.2,31.62],[19.2,33.620000000000005],[11.2,37.120000000000005],[5.2,42.02]]]]},
{"id":"clion","name":"C-Lion King","price":1.0,"age":"new","blurb":"Helsinki to Germany under the Baltic. Anchors keep finding it.","pairs":[["hel","fra",[[24,59.8],[20,57.5],[15,55.2],[12.2,54.3]]]]},
{"id":"uly","name":"Ulysses-ish","price":0.8,"age":"old","blurb":"Short hop across the North Sea. An odyssey it is not.","pairs":[["lon","ams",[[2,51.8]]]]},
{"id":"chn","name":"Channel Hopper","price":0.7,"age":"mid","blurb":"London to Paris under the Channel. Cheaper than the train.","pairs":[["lon","par",[[1,50.5]]]]},
{"id":"medn","name":"Med-Nauti-lust","price":0.9,"age":"mid","blurb":"Across the Mediterranean, Egypt to France. Romantic, in a cable way.","pairs":[["cai","mrs",[[29.9,31.4],[28,32.5],[20,34.5],[12,38],[6.5,42.6]]]]},
{"id":"eassy","name":"EASSy Peasy","price":0.95,"age":"mid","blurb":"East Africa up to Europe via the Red Sea. Lemon squeezy.","pairs":[["nbo","mrs",[[39.7,-4],[42,-1],[45,2],[51,10.5],[45,12.3],[43.4,12.0],[40.4,14.7],[37.4,20.700000000000003],[34.4,25.700000000000003],[32.4,29.200000000000003],[31.799999999999997,30.900000000000002],[29.4,31.700000000000003],[19.4,33.7],[11.4,37.2],[5.4,42.1]]]]},
{"id":"teams","name":"TEAMS-work","price":0.9,"age":"mid","blurb":"Kenya to the Gulf. Makes the dream work.","pairs":[["nbo","dxb",[[39.7,-4],[44,0],[52,8],[58,18],[59,22.5],[57,25]]]]},
];
const CAB=Object.fromEntries(CABLES.map(c=>[c.id,c]));
const CABLE_PAIRS=CABLES.flatMap(c=>c.pairs.map(([a,b,mid])=>{const A=CITY[a],B=CITY[b];const near=(x,ref)=>x+W*Math.round((ref-x)/W);
const mp=mid.map(q=>proj(q[0],q[1]));const pts=[[near(A.x,mp[0][0]),A.y]].concat(mp,[[near(B.x,mp[mp.length-1][0]),B.y]]);
const ll=[[A.lon,A.lat]].concat(mid,[[B.lon,B.lat]]);let L=0;for(let i=1;i<ll.length;i++)L+=hav(ll[i-1][0],ll[i-1][1],ll[i][0],ll[i][1]);
return {cid:c.id,a,b,pts,km:Math.round(L)};}));
function cablesOk(a,b){const ban=S&&S.ev&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city);return ban?[]:cablesFor(a,b);}
function cablesFor(a,b){return CABLE_PAIRS.filter(c=>(c.a===a&&c.b===b)||(c.a===b&&c.b===a));}
function cablePair(cid,a,b){const c=CABLE_PAIRS.find(x=>x.cid===cid&&((x.a===a&&x.b===b)||(x.a===b&&x.b===a)));if(!c)return null;return c.a===a?c:{...c,pts:c.pts.slice().reverse()};}
const ALLC=CITIES.filter(c=>!c.cn&&!c.ru&&!c.ixOnly).map(c=>c.id);
const ruCity=c=>!!CITY[c].ru;
const cnCity=c=>!!CITY[c].cn;
const BIGC=['ber','zrh','nbo','cai','jkt','mnl','per','akl','dub','lax','tor','mex','dxb','cph','icn','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mrs','mad','sto','bom','sin','hkg','tok','syd','jnb','lag'];
const MIDC=['ber','zrh','jkt','mnl','dub','lax','tor','dxb','icn','sjc','ash','nyc','chi','dal','mia','lon','ams','fra','par','mad','sin','hkg','tok','syd','bom','sao'];
/* ================= NETWORKS ================= */
const NETS=[
{id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad'],ix:[],blurb:'Grew from a seedling into a global backbone. Leaves no route behind.'},
{id:'ntt',name:'Not That Telecom',asn:2941,type:'t1',pol:'restrictive',share:.06,price:8,col:'#4B3FC4',pops:['jkt','mnl','per','lax','dxb','icn','sea','sjc','dal','ash','nyc','lon','ams','fra','sin','hkg','tok','syd'],ix:[],blurb:'Huge in Asia. "Which telecom?" "Not that one."'},
{id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin'],ix:[],blurb:'Nordic backbone that tells you exactly where your packets went.'},
{id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['bcn','ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','mrs','sto','sin','hkg','tok'],ix:[],blurb:'Cheapest transit on the map. Famously gentle, except during peering spats.'},
{id:'tat',name:'Ta-Ta Comms',asn:6543,type:'t1',pol:'restrictive',share:.04,price:9,col:'#6A4C93',pops:['nbo','cai','jkt','dxb','nyc','ash','lon','fra','mrs','lag','jnb','bom','sin','hkg','tok'],ix:[],blurb:'Waves goodbye to latency across the Indian Ocean.'},
{id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',pops:['bcn','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','hkg','sin','tok','syd','jnb'],ix:'ALL',blurb:'Will peer with anyone, anywhere. Rumored to mail out IPv6 cakes.'},
{id:'tng',name:'Tangerine Telecom',asn:5115,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['bcn','cai','nbo','dxb','par','mrs','mad','lon','ams','lag','jnb'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb'],blurb:'Juicy reach into Europe and Africa.'},
{id:'sgt',name:'SingTell',asn:7474,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom'],ix:['sin','hkg','tok','syd','bom'],blurb:'Sings your packets across Asia-Pacific.'},
{id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#E63946',pops:['nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag'],ix:['lon','fra','ams','mad','mrs','jnb','bom','lag'],blurb:'Mobile giant. The signal is real, the name is not.'},
{id:'ctc',name:'China Telecomet',asn:4314,type:'t2',pol:'restrictive',share:.02,price:22,premium:2.5,cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:'The biggest network in China. Its CN-Too premium route skips the congested border, for a price.'},
{id:'cun',name:'China Unicorn',asn:4837,type:'t2',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:'Number two in China, with a horn for every backbone.'},
{id:'cmb',name:'China Moble',asn:9880,type:'eye',pol:'paid',paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:'The largest mobile network on Earth. Paid peering only.'},
{id:'cmc',name:'Comecast',asn:7227,type:'eye',pol:'selective',minIx:10,minPni:30,share:.03,col:'#2C7A7B',pops:['ash','nyc','chi','sjc','sea','mia'],ix:['ash','nyc','chi','sjc','sea'],blurb:'Huge eyeball network. Come for the broadband, stay because there is no other choice.'},
{id:'dtk',name:'Doitsche Telekomm',asn:3203,type:'eye',pol:'paid',paidFee:9000,share:.03,col:'#E20074',pops:['fra','ams','lon'],ix:[],blurb:'Pink eyeball giant. Peering is available... for a monthly fee.'},
{id:'nfx',name:'NetChill',asn:2906,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.15,cache:{name:'Open Couch',min:12},col:'#C8102E',pops:ALLC,ix:'ALL',blurb:'Streams 40% of evening traffic. Hands out free caches if you send enough eyeballs.'},
{id:'ggl',name:'Goggle',asn:15961,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.13,cache:{name:'Goggle Global Cache',min:15},col:'#3A7BEA',pops:ALLC,ix:'ALL',blurb:'Search, video and goggles. Mostly goggles.'},
{id:'fbk',name:'Faceplant',asn:32943,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.08,cache:{name:'Faceplant Node Thingy',min:10},col:'#3B5BDB',pops:BIGC,ix:'ALL',blurb:'Social media. Everyone keeps falling for it.'},
{id:'akm',name:'Akamaybe',asn:20490,type:'cdn',pol:'open',share:.07,cache:{name:'Akamaybe Box',min:6},col:'#0099CC',pops:ALLC,ix:'ALL',blurb:'The original CDN. Maybe it is already in your rack.'},
{id:'cfl',name:'Crowdflare',asn:13353,type:'cdn',pol:'open',share:.05,col:'#F48120',pops:BIGC,ix:'ALL',blurb:'Shields half the web from crowds of bots.'},
{id:'amz',name:"Amazin' Web Services",asn:16590,type:'cdn',pol:'selective',minIx:8,minPni:30,share:.05,col:'#FF9900',pops:MIDC,ix:'ALL',blurb:"The cloud. It's just someone else's Ashburn."},
{id:'msf',name:'Microsnoft',asn:8705,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.04,col:'#00A4EF',pops:MIDC,ix:'ALL',blurb:'Updates. So many updates.'},
{id:'bdc',name:'BiteDance',asn:39669,type:'cdn',pol:'open',share:.03,col:'#111111',pops:MIDC.concat(['pek','sha']),ix:'ALL',blurb:'Short videos, very long traffic graphs.'},
{id:'slw',name:'Slowly',asn:54311,type:'cdn',pol:'open',share:.02,col:'#E5383B',pops:MIDC,ix:'ALL',blurb:'An edge cloud that is, despite the name, quite fast.'},
];
NETS.push(
{id:'tcs',name:'TenCents',asn:45900,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.02,cn:true,col:'#1AAD19',pops:['pek','sha','hkg','sin','tok','fra','sjc'],ix:['hkg','sin','tok','fra','sjc'],blurb:'Chat, games and payments. Every message costs ten cents.'},
{id:'abc',name:'AliBubble Cloud',asn:37936,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.015,cn:true,col:'#FF6A00',pops:['pek','sha','hkg','sin','tok','fra','sjc','syd'],ix:['hkg','sin','tok','fra','sjc'],blurb:'Shopping festivals that melt traffic graphs.'},
{id:'byd',name:'Bye-du',asn:38635,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.01,cn:true,col:'#2932E1',pops:['pek','sha','hkg'],ix:['hkg'],blurb:'Search, maps and a cheerful goodbye.'});
NETS.push(
{id:'rtc',name:'Rostelecomedy',asn:12389,type:'t2',pol:'selective',minIx:20,minPni:40,share:.01,price:6,col:'#7700FF',pops:['mos','hel','sto','fra','ams'],ix:['mos','fra','ams'],blurb:'The national carrier. Every punchline is pre-approved.'},
{id:'ydx',name:'Yawndex',asn:13238,type:'cdn',pol:'open',share:.008,col:'#FC3F1D',pops:['mos','hel','fra','ams'],ix:['mos','hel','fra','ams'],blurb:'Search, taxis and maps. Slightly sleepy.'},
{id:'vkl',name:'VKontakt-lens',asn:47541,type:'cdn',pol:'open',share:.006,col:'#0077FF',pops:['mos','hel'],ix:['mos','hel'],blurb:'Social network with perfect vision.'},
{id:'ets',name:'Etis-a-lot',asn:5384,type:'eye',pol:'paid',paidFee:8000,share:.006,col:'#719E19',pops:['dxb','mrs','lon','fra','sin'],ix:[],blurb:'Charges a lot. Paid peering only, and the name says it all.'},
{id:'tmx',name:'Tel-Mess',asn:8151,type:'eye',pol:'paid',paidFee:7000,share:.008,col:'#00A0DF',pops:['mex','dal','lax','mia'],ix:[],blurb:'Mexico’s giant. Paid peering only, and the pricing is a mess.'},
{id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['tor','mtl','nyc','chi'],ix:['tor','mtl'],blurb:'Polite, enormous, and sorry about the bill.'});
NETS.push(
{id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:'Indonesia’s mobile giant. Every packet poses for a photo first.'},
{id:'pld',name:'PLDTea Time',asn:9299,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,col:'#D62027',pops:['mnl','hkg','sin'],ix:['mnl','hkg'],blurb:'Philippine giant. Peering requests are reviewed over a cup of tea.'},
{id:'spk',name:'Spark-le',asn:4771,type:'eye',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd'],ix:['akl','syd'],blurb:'New Zealand’s shiniest ISP.'},
{id:'tsy',name:'Telstraya',asn:1221,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['syd','per','sin','hkg','lax'],ix:['syd','per','sin','hkg'],blurb:'Australia’s big one. G’day, that will be nine dollars a megabit. Sorry, gigabit.'});
NETS.push(
{id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#4CB848',pops:['nbo'],ix:['nbo'],blurb:'Kenya’s mobile giant. Pays you in M-Pesos.'},
{id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:'Owns the land crossing every Red Sea cable needs. Collects tolls like a pharaoh.'});
const NET=Object.fromEntries(NETS.map(n=>[n.id,n]));
const NSH={}; {const t=NETS.reduce((a,n)=>a+n.share,0); NETS.forEach(n=>NSH[n.id]=n.share/t);}
const CN_W={ctc:.2,cun:.14,cmb:.08,tcs:.22,abc:.14,byd:.08,bdc:.08,akm:.02,msf:.02,amz:.01,drz:.01};
const RU_W={ydx:.24,vkl:.12,rtc:.14,ggl:.12,bdc:.08,akm:.05,cfl:.06,msf:.04,amz:.03,tly:.02,cog:.02,drz:.01};
const NSH_RU={}; {const t=Object.values(RU_W).reduce((a,b)=>a+b,0); for(const k in RU_W)NSH_RU[k]=RU_W[k]/t;}
const NSH_CN={}; {const t=Object.values(CN_W).reduce((a,b)=>a+b,0); for(const k in CN_W)NSH_CN[k]=CN_W[k]/t;}
const CN_BLOCKED=NETS.filter(n=>!CN_W[n.id]&&n.type==='cdn').map(n=>n.name);
const TYPE_L={t1:'Tier 1',t2:'Tier 2',cdn:'CDN / content',eye:'Eyeballs'};
const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).map(w=>w[0]).join('').slice(0,3).toUpperCase();
/* ================= BUSINESSES ================= */
const BIZ_T={
dia:{l:'Enterprise DIA',opts:[1,2,5,10],rate:600},
game:{l:'Game servers',opts:[5,10,20,40],rate:120},
host:{l:'Hosting',opts:[10,20,40,80],rate:60},
isp:{l:'Downstream ISP (buys transit)',opts:[100,200,400,800],rate:15,lv:2},
l2vpn:{l:'L2VPN circuit',opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1},
stream:{l:'Streaming startup',opts:[50,100,200],rate:80,lv:2},
edu:{l:'University network',opts:[20,50,100],rate:90,lv:2},
gpu:{l:'AI GPU data center',opts:[200,400,800],rate:70,lv:3,names:['Neural Noodles AI','GPUs R Us','Hallucination Labs','Transformers & Sons','Token Burners Inc.','Very Large Language Co.','Prompt Engineering Ltd','DeepThought Farms','Parameter Pastures','Gradient Descent Diner','Attention Is All We Need LLC','Overfit Analytics']},
onramp:{l:'Cloud on-ramp',opts:[100,200,400],rate:0,l2:true,km:0.7,lv:3,names:["Amazin' Web Services on-ramp","Microsnoft Azzure on-ramp",'Goggle Cloud on-ramp','AliBubble Cloud on-ramp','Miracle Cloud on-ramp']},
ai:{l:'AI training interconnect',opts:[400,800,1600],rate:0,l2:true,div:true,km:0.9,lv:4,names:['Skynet-ish Compute','Galaxy Brain Training Run','Megawatt Minds','The Big Model Co.','Infinite Context Corp','Sentient Spreadsheet Inc.']},
hyper:{l:'Hyperscaler DCI',opts:[1600,3200,6400],rate:0,l2:true,div:true,km:0.5,lv:4,names:["Amazin' Web Services DCI","Microsnoft Azzure DCI",'Goggle Cloud DCI','Faceplant Infra DCI','AliBubble Cloud DCI']},
hft:{l:'High-frequency trading link',opts:[1,5,10],rate:0,l2:true,lat:true,km:6,lv:2,names:['Flash Boys Capital','Nanosecond Nancy Trading','Speed of Light Securities','Arbitrage & Sons','Front-Run Fund','Microwave Tower Capital','Tick-Tock Quant','Low Latency Larry LLC']},
bulk:{l:'Bulk backup transfer (latency does not matter)',opts:[100,200,400],rate:0,l2:true,scenic:true,km:0.1,lv:2,names:['Glacier Slow Storage','Tape Backup Tortoise','Scenic Route Archives','Cold Storage Cold Cuts','Sloth Sync','Eventually Consistent Inc.','Snail Mail Data Co.']},
event:{l:'Event network',opts:[100,200,400,800,1600,3200],rate:0,event:true,lv:2,names:['The World Cup-ish Final','NANOG-ish 99','Burning Router Festival','Eurovisión-ish Song Contest','Formula Ping Grand Prix','The Big Game','Olympic Pings','A Pop Megastar Stadium Tour','LAN Party of the Century','The Keynote (One More Thing)','Gamescom-ish Expo','Oktoberfest-ish Livestream']},
sdwan:{l:'SD-WAN for a chain',opts:[1,2,5,10],rate:0,l2:true,sdwan:true,km:0,lv:2,names:['Kebab Kingdom','Pretzel Palace','Burger Router Inc.','Café Latte-ncy','Hardware Hut Stores','Pharma-See Pharmacies','Bank of Tiny Branches','Supermarket Superhighway','Fitness Pings Gyms','Hotel Hops Group','Doughnut Data Diners']},
wwave:{l:'Wholesale wave',opts:[1],rate:0,fiber:true,lv:2,names:['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','GTT (Got Tangled Twice)','A Hyperscaler Who Shall Not Be Named','Megapork','youNetworks']},
dfpair:{l:'Dark fiber pair lease',opts:[1],rate:0,fiber:true,lv:3,names:['A Hyperscaler Who Shall Not Be Named','Goggle Fiber Division','Faceplant Infra','Amazin’ Backbone Team','A Very Secretive Trading Firm']},
scrub:{l:'DDoS protection + DIA',opts:[1,5,10,20],rate:900},
};
const LEVELS=[
{n:'Local ISP',req:'Start here',unlock:'Enterprises, game servers, hosting, L2VPNs and DDoS protection.'},
{n:'Regional player',req:'peak 200 Gbps and 3 POPs',unlock:'Downstream ISPs, streaming startups and universities. Gear: Edge Lord 400 routers, dark fiber leases, Rainbow-in-a-Box DWDM, Ackackia 400ZR+ optics.'},
{n:'Serious backbone',req:'peak 1 Tbps and 6 POPs',unlock:'AI GPU data centers and cloud on-ramps. Gear: Chonk 800 routers, Sizzle 800ZR+ optics, ROADMaster 9000 line systems, building your own fiber.'},
{n:'Big league',req:'peak 3 Tbps, 10 POPs, 3 continents',unlock:'AI training interconnects and hyperscaler DCI deals in the terabits. Gear: Absolute Unit 1.6T routers, Sienna WaveMagic 1.6T transponders.'},
];
const lvl=()=>(S&&S.lvl)||1;
function custLevel(){const pops=Object.keys(S.pops).length,pk=S.stats.peak;if(pk>=3000&&pops>=10&&regionsCount()>=3)return 4;if(pk>=1000&&pops>=6)return 3;if(pk>=200&&pops>=3)return 2;return 1;}
const BIZ_N=['Byte-Size Bakery','Hamster Wheel Power Co.','Llama Logistics','Cloud Nine Hosting','Rural Rabbit Broadband','Tiny Telco','Pixel Pirates Games','Moo-Moo Dairy Corp','Snack Overflow','Git Happens Ltd','Kernel Sanders Fried Code','Lag-Free Llamas','404 Bistro','Ping Pong Sports','Null Pointer Pets','Buffer Bloat Boats','Packet Pizza','Latency Lattes','Ctrl-Alt-Deli','Sudo Sandwiches','Cache Me Outside','Hertz So Good Radio','Jitterbug Dance Hall','Bit Barn Hosting','Fiber Optimists','The Daily Ping','Squirrel Mesh Wireless','Spam & Eggs Diner','Router Rooter Plumbing','Kilobyte Kebab','Gigglebit Studios','Uptime Funk Records','Ohm Sweet Ohm','Dial-Up Nostalgia Club','Two-Factor Tacos'];
/* ================= GOALS ================= */
const GOALS=[
{id:'bb',t:'Light up your first customers',d:'Open your home city and press “Launch broadband”. Eyeballs are people at home watching cat videos. They pay you every month.',r:5000,ok:()=>Object.values(S.pops).some(p=>p.bb)},
{id:'tr',t:'Reach the whole internet',d:'Your eyeballs want everything. Buy IP transit from a Tier 1 or Tier 2 in your city. Transit gives you the full routing table.',r:5000,ok:()=>S.transit.length>0},
{id:'ix',t:'Join an Internet Exchange',d:'Get a port at an IX: a big shared switch where networks swap traffic for free instead of paying transit.',r:7500,ok:()=>Object.keys(S.ixp).length>0},
{id:'p5',t:'Make 5 peering friends',d:'On the Peering tab, request sessions, or join the route server to peer with every open network at once.',r:10000,ok:()=>R.sessions>=5},
{id:'ln',t:'Lay your first fiber',d:'Drag from your pink router to another city. Short hops are cheap. Oceans are not.',r:10000,ok:()=>S.links.length>0},
{id:'bz',t:'Sign a business customer',d:'Businesses show up with a $ bubble. You need a POP in their city. Check the Deals tab.',r:12500,ok:()=>S.biz.length>0},
{id:'rd',t:'Survive a failure',d:'Things break all the time. Build a second path or a second upstream so traffic reroutes when something dies.',r:12500,ok:()=>S.stats.survived>0},
{id:'ca',t:'Host an embedded cache',d:'Big CDNs give you free cache boxes once you send them enough traffic. Free bandwidth, just add power.',r:12500,ok:()=>S.caches.length>0},
{id:'pn',t:'Set up a PNI',d:'A private cross-connect to one network in the same data center, for when traffic outgrows the IX.',r:15000,ok:()=>S.pni.length>0},
{id:'c3',t:'Go global',d:'Have POPs on 3 continents. Subsea cables cost a fortune, so plan the route.',r:50000,ok:()=>regionsCount()>=3},
{id:'t2',t:'Become a Tier 2',d:'5+ POPs, ports on 3+ IXs and 15+ peering sessions.',r:50000,ok:()=>isTier2()},
{id:'tb',t:'Serve 1 Tbps',d:'A terabit per second of happy traffic.',r:75000,ok:()=>R.served>=1000},
{id:'t1',t:'Go transit-free: Tier 1!',d:'Peer with all five Tier 1s over PNIs and cancel every transit port. Then nobody charges you to reach the internet.',r:0,win:true,ok:()=>isTier1()},
];
/* ================= STATE ================= */
let S=null, R=emptyR();
const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false};
let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++);
function emptyR(){return {egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{}};}
/* ================= BANKS & LOANS =================
Lenders make offers now and then (more often when you are broke). Each loan
is a fixed monthly payment that shows up in your costs; conditions are checked
daily and breaking one costs a penalty. */
const BANKS={
gs:{name:'Goldman Sacks',col:'#6F8FAF',min:'A',apr:[.07,.11],amt:[4,9],term:[24,48],covs:['peer30','continents2','golf'],blurb:'Only lends to people who do not need it.'},
db:{name:'Deutsche Bankrupt',col:'#0018A8',min:'BBB',apr:[.08,.13],amt:[3,7],term:[18,36],covs:['nocog','gen','fax'],blurb:'Very solid. Mostly.'},
jpm:{name:'JP Morgain',col:'#5B4636',min:'BBB',apr:[.09,.14],amt:[3,6],term:[12,36],covs:['uptime','logo'],blurb:'Lends you money and also a little bit of their own.'},
cs:{name:'Credit Sweaty',col:'#7A9CC6',min:'BB',apr:[.11,.17],amt:[2,5],term:[12,30],covs:['cash50','nochina'],blurb:'Nervous, but enthusiastic.'},
wf:{name:'Wells Far-Gone',col:'#D71E28',min:'BB',apr:[.12,.18],amt:[2,4],term:[12,24],covs:['nosub','logo'],blurb:'Opened three accounts for you while you read this.'},
spk:{name:'Spätzle-Sparkasse',col:'#E30613',min:'B',apr:[.05,.08],amt:[1,3],term:[24,60],covs:['spaetzle','kehrwoche'],blurb:'Cheap, patient, and very particular about Stuttgart.'},
rev:{name:'Revoloot',col:'#191C1F',min:'B',apr:[.13,.2],amt:[1,3],term:[6,18],covs:['app'],blurb:'Instant approval. Instant regret.'},
gov:{name:'Ministry of Tubes',col:'#2E7D32',min:'CCC',apr:[.01,.02],amt:[1,2],term:[36,60],covs:['rural','forms'],blurb:'Cheap state money for connecting the underserved. Bring a pen.'},
crypto:{name:'Crypto Bros Capital',col:'#F7931A',min:'CCC',apr:[.15,.25],amt:[2,6],term:[6,18],covs:['hodl'],crypto:true,blurb:'Pays out in TubeCoin. Value may vary. A lot.'},
vult:{name:'Venture Vultures',col:'#8E44AD',min:'CCC',amt:[6,12],share:[.1,.15],covs:['blitz'],equity:true,blurb:'No repayments, ever. Just a slice of your revenue, forever, and a lot of opinions.'},
shark:{name:'Loan Shark Telecom Finance',col:'#37474F',min:'C',apr:[.6,.9],amt:[1,2],term:[4,8],covs:[],shark:true,blurb:'Always open. Ask no questions. Do not be late.'},
};
const RATINGS=['C','CCC','B','BB','BBB','A','AA','AAA'];
const COVS={
peer30:{l:'Keep your peering ratio above 30%. The bank read a blog post about peering.',ok:()=>(R.peerShare||0)>=0.3},
continents2:{l:'Keep POPs on at least 2 continents. Diversification!',ok:()=>regionsCount()>=2},
golf:{l:'Your CEO plays golf with our CEO every Thursday.',ok:()=>true},
nocog:{l:'No Cogentle transit anywhere. Our CEO got de-peered once and has not recovered.',ok:()=>!S.transit.some(t=>t.net==='cog')},
gen:{l:'Every POP needs a backup generator. Our risk team saw one disaster movie.',ok:()=>Object.values(S.pops).every(p=>p.gen)},
fax:{l:'Send us your monthly report by fax.',ok:()=>true},
uptime:{l:'Deliver at least 95% of what your customers want.',ok:()=>!R.demand||R.served/R.demand>=0.95},
logo:{l:'Our logo goes on every router you own.',ok:()=>true},
cash50:{l:'Never let cash drop below $50k. It makes us sweat.',ok:()=>S.cash>=50000},
nochina:{l:'Stay out of mainland China. Compliance said so.',ok:()=>!Object.keys(S.pops).some(cnCity)},
nosub:{l:'No new subsea links while this loan runs. We are afraid of sharks.',ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)},
spaetzle:{l:'Peer at the Spätzle-IX in Stuttgart. Local money for local packets.',ok:()=>S.ixp.stg!==undefined},
kehrwoche:{l:'Do the Kehrwoche: keep your NOC free of incidents older than a week.',ok:()=>!S.inc.some(i=>S.day-i.start>7)},
app:{l:'Download our app and enable all notifications.',ok:()=>true},
rural:{l:'Run home broadband somewhere underserved (Asia, Africa or Oceania).',ok:()=>Object.keys(S.pops).some(c=>S.pops[c].bb&&['AS','AF','OC'].includes(CITY[c].reg))},
forms:{l:'Fill in form T-17b in triplicate, every month, forever.',ok:()=>true},
hodl:{l:'Never sell your TubeCoin. Diamond hands.',ok:()=>true},
blitz:{l:'Open a new POP at least every 90 days. Blitzscale or die.',ok:l=>S.day-Math.max(l.start,...Object.values(S.pops).map(p=>p.day||0))<=90},
};
function niceAmt(v){const m=Math.pow(10,Math.floor(Math.log10(Math.max(1,v)))-1);return Math.max(50000,Math.round(v/m)*m);}
function rating(){if(!S)return 'BB';const rev=R.revMo||0,pay=(R.cost&&R.cost.loans)||0;let sc=3;
if(rev>50000)sc++;if(rev>250000)sc++;if(rev>1000000)sc++;if(R.revMo>R.costMo)sc++;else sc--;
if(S.cash<0)sc-=2;if(rev&&pay/rev>0.3)sc--;if(rev&&pay/rev>0.6)sc--;sc-=Math.min(3,S.loanStrikes||0);
return RATINGS[clamp(sc,0,RATINGS.length-1)];}
const rIdx=r=>RATINGS.indexOf(r);
function annuity(P,apr,n){const r=apr/12;return r?P*r/(1-Math.pow(1+r,-n)):P/n;}
function spawnLoanOffer(emergency){
const rt=rating(),keys=Object.keys(BANKS).filter(k=>rIdx(rt)>=rIdx(BANKS[k].min)&&!S.loanOffers.some(o=>o.bank===k)&&!(BANKS[k].equity&&S.loans.some(l=>l.bank===k)));
let pool=emergency?keys.filter(k=>['shark','gov','crypto','vult','rev','spk'].includes(k)):keys.filter(k=>k!=='shark');if(!pool.length)pool=keys;if(!pool.length)return;
const k=pick(pool),B=BANKS[k],base=Math.max(60000,R.revMo||0),ra=(a)=>a[0]+Math.random()*(a[1]-a[0]);
const amount=niceAmt(base*ra(B.amt)*(emergency?0.6:1)),o={id:uid(),bank:k,amount,exp:S.day+(emergency?10:25),covs:B.covs.slice()};
if(B.equity){o.share=+ra(B.share).toFixed(3);}else{o.apr=+ra(B.apr).toFixed(3);o.term=Math.round(ra(B.term)/6)*6||6;o.pay=Math.round(annuity(amount,o.apr,o.term));}
S.loanOffers.push(o);
toast(`<b>${esc(B.name)} would like to lend you ${fmt$(amount)}.</b><br>${emergency?'They heard you might be in a spot of bother.':'Terms apply. Several terms.'}`,emergency?'bad':'goal',[{l:'Open bank',act:'bank',args:{}}]);
}
function loanTick(d){
// conditions: 15-day grace, then a penalty every 30 days while broken
for(const l of S.loans){const B=BANKS[l.bank];
const broken=l.covs.filter(c=>COVS[c]&&!COVS[c].ok(l));
if(d-l.start<15||!broken.length){l.breach=0;continue;}
l.breach=(l.breach||0)+1;
if(l.breach===1)toast(`<b>${esc(B.name)} is unhappy.</b><br>You broke a loan condition: ${esc(COVS[broken[0]].l)} Fix it within 10 days or pay a penalty.`,'bad',[{l:'Open bank',act:'bank',args:{}}]);
if(l.breach===10||(l.breach>10&&(l.breach-10)%30===0)){
if(B.equity){l.share=+(l.share+0.02).toFixed(3);toast(`<b>${esc(B.name)} are circling.</b><br>They now take ${pct(l.share)} of your revenue.`,'bad');}
else{const fee=Math.round(l.bal*0.05);l.bal+=fee;l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left)));S.loanStrikes=(S.loanStrikes||0)+1;toast(`<b>Penalty from ${esc(B.name)}: ${fmt$(fee)}</b><br>Added to what you owe. Your monthly payment is now ${fmt$(l.pay)}.`,'bad');}
sfx('err');}}
// monthly statement: payments already leave your cash daily as part of costs
for(const l of S.loans.slice()){if(BANKS[l.bank].equity||(d-l.start)%30!==0||d===l.start)continue;
l.bal=Math.max(0,l.bal*(1+l.apr/12)-l.pay);l.left--;
if(l.left<=0||l.bal<1){S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');toast(`<b>Loan from ${esc(BANKS[l.bank].name)} paid off!</b><br>They sent a fruit basket. It is mostly bananas.`,'good');sfx('coin');}}
// the shark's collectors come by when you are broke
if(S.cash<0&&S.loans.some(l=>BANKS[l.bank].shark)&&Math.random()<0.03){const c=pick(Object.keys(S.pops));const p=S.pops[c];p.down=Math.max(p.down||0,d+1);addInc({type:'shutdown',ref:c,until:d+1,msg:`Two very large gentlemen from Loan Shark Telecom Finance unplugged your router in ${CITY[c].name} "as a reminder".`,cost:0});toast(`<b>The loan shark sent a reminder.</b><br>Your POP in ${CITY[c].name} is dark until tomorrow.`,'bad');sfx('alert');}
// offers: now and then, and much more often when you are in trouble
S.loanOffers=S.loanOffers.filter(o=>o.exp>d);
const broke=S.cash<0;
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d>20&&Math.random()<1/40)))spawnLoanOffer(broke);
}
function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(Math.random()*15000),home,day:0,cash:START_CASH,
pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},
done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubAt:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0};
}
/* ================= HELPERS ================= */
const fmt$=v=>{const a=Math.abs(v),s=v<0?'-':'';if(a>=1e6)return s+'$'+(a/1e6).toFixed(a>=1e7?1:2)+'M';if(a>=1e3)return s+'$'+(a/1e3).toFixed(a>=1e5?0:1)+'k';return s+'$'+Math.round(a);};
const fmtG=g=>g>=1000?(g/1000).toFixed(g>=10000?1:2)+' Tbps':(g>=100?g.toFixed(0):g.toFixed(1))+' Gbps';
const pct=x=>Math.round(x*100)+'%';
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const pick=a=>a[Math.floor(Math.random()*a.length)];
const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function dateStr(d){const y=1+Math.floor(d/360),m=Math.floor(d/30)%12,dd=d%30+1;return `Y${y} · ${MONTHS[m]} ${dd}`;}
function wrapDx(a,b){let dx=b-a;if(dx>W/2)dx-=W;if(dx<-W/2)dx+=W;return dx;}
function kmBetween(a,b){const A=CITY[a],B=CITY[b];return Math.max(20,Math.round(hav(A.lon,A.lat,B.lon,B.lat)));}
const isSub=(a,b)=>CITY[a].land!==CITY[b].land;
const popUp=c=>S.pops[c]&&!(S.pops[c].down>S.day);
const regionsCount=()=>new Set(Object.keys(S.pops).map(c=>CITY[c].reg)).size;
/* IXs are keyed by city id for a city's main exchange. A second exchange in the same city gets
its own 'city:name' key in XIX, so ports, peers, route servers and outages stay separate. */
const XIX={
'ams:fries':{city:'ams',name:'FRIES-IX',freeTo:2,members:['drz','akm','cfl','slw','msf'],note:'Run by volunteers out of the Science Park. Ports up to 400G are free, sponsored by people who just like peering. Fewer members than HAMS-IX, but the price is hard to beat.'},
'mad:paella':{city:'mad',name:'Paella-NIX',fee:.6,members:['drz','akm','cfl','tng','vdp','bdc','slw','msf'],note:'The original Madrid exchange, around since long before Siesta-IX woke up. Neutral, cheap and run by the local ISPs themselves.'},
'fra:kley':{city:'fra',name:'KleyWrecks',fee:.5,members:['drz','akm','cfl','slw','bdc','ydx'],note:'The scrappy little exchange down the road from DE-KICKS. Half the price, a tenth of the members, and nobody wears a suit.'},
'lon:lonap':{city:'lon',name:'LO-NAPS',fee:.6,members:['drz','akm','cfl','slw','bdc','msf','fbk'],note:'Member-owned and not-for-profit. Smaller than LYNX, but the AGM has biscuits.'},
'nyc:kicks':{city:'nyc',name:'DE-KICKS New York',members:['drz','akm','cfl','nfx','ggl','amz','msf','cmc'],note:'The Frankfurt giant opened a branch in Manhattan. Same switches, worse bagels back home.'},
'jnb:jinx':{city:'jnb',name:'JINXED-IX',fee:.7,members:['drz','akm','cfl','tng','vdp'],note:'The older Johannesburg exchange, run by the local ISP association. Knock on wood before every maintenance window.'},
'syd:strayla':{city:'syd',name:'IX Strayla',fee:.7,members:['drz','akm','cfl','ggl','spk','tsy'],note:'The nationwide not-for-profit exchange. Cheaper ports than Roo-IX, same distance from everything else.'},
'tok:bb':{city:'tok',name:'BB-Kicks',members:['drz','akm','cfl','sgt','msf','amz'],note:'Tokyo has more exchanges than anyone can name. This one was started by a broadband giant and never fell asleep.'},
};
const ixCity=k=>XIX[k]?XIX[k].city:k;
function cityIxes(c){const a=[];if(S.myIx[c]||CITY[c].ix)a.push(c);for(const k in XIX)if(XIX[k].city===c)a.push(k);return a;}
function ixName(c){return XIX[c]?XIX[c].name:S.myIx[c]?S.myIx[c].name:CITY[c].ix;}
function ixMembers(c){if(XIX[c])return XIX[c].members.slice();if(S.myIx[c])return S.myIx[c].members.slice();if(!CITY[c].ix)return [];return NETS.filter(n=>n.ix==='ALL'||(Array.isArray(n.ix)&&n.ix.includes(c))).map(n=>n.id);}
// LAG: several identical ports bundled into one logical link. Flow hashing is never perfectly even, so a bundle carries ~95% of the sum.
const LAG_MAX=8;
function lagCap(g,n){n=n||1;return g*n*(n>1?0.95:1);}
function lagName(tier,n){return (n||1)>1?`${n}×${PORT[tier].n} LAG`:`${PORT[tier].n} port`;}
function ixCap(c){return S.myIx[c]?400:lagCap(PORT[S.ixp[c]].g,(S.ixn||{})[c])*(isRemote(c)?REMOTE_CAP:1);}
function ixSessions(c){
const s=new Set(); if(S.ixp[c]===undefined)return s;
for(const id of ixMembers(c)){const n=NET[id];
if(S.peers[id+'@'+c]&&!snub(id,c)&&!(isRemote(c)&&noRemote(id)))s.add(id);
else if(S.rs[c]&&n.pol==='open')s.add(id);
else if(S.myIx[c]&&(n.pol==='open'||n.pol==='selective'))s.add(id);}
return s;
}
function t1Club(){
const miss=[];const pops=Object.keys(S.pops).length;
if(regionsCount()<3)miss.push('POPs on 3+ continents');
if(pops<10)miss.push(`10+ POPs (${pops})`);
if(R.served<1500)miss.push(`serve 1.5 Tbps (${fmtG(R.served)})`);
if(R.sessions<20)miss.push(`20+ peering sessions (${R.sessions})`);
return {ok:!miss.length,missing:miss};
}
/* Big networks sometimes refuse to peer in a particular city, for a while. Each (network, city)
pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. */
const SNUB_WIN=150,SNUB_P=0.22;
const SNUB_IX=['Only peers over PNIs in this metro. Order a cross-connect instead.','Their IX port here is full until the next upgrade. They promise it is soon.','Moved everything in this city to PNIs. Please read their PearingDB page, all 40 pages of it.','The peering coordinator for this city is on a six-month sabbatical.','Their policy here says "IX peering by invitation only". You were not invited.'];
const SNUB_ALL=['Not accepting new peers in this region right now.','Region frozen while they renegotiate with the local incumbent.','Their routers in this city are "at capacity". They are not.','Already reach you through your transit provider here and think that is fine.','Their lawyers are reviewing every peering agreement in this country. Again.','A new VP wants to "monetise interconnection" in this market.'];
function hstr(t){let h=2166136261;for(let i=0;i<t.length;i++){h^=t.charCodeAt(i);h=Math.imul(h,16777619);}return h>>>0;}
function bigPeer(n){return !!n&&n.pol==='selective'&&n.share>=0.03;}
function snub(id,c){
const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c])return null;c=ixCity(c);
const off=hstr(id+c)%SNUB_WIN,ep=Math.floor((S.day+off)/SNUB_WIN),h=hstr(S.asn+'|'+id+'|'+c+'|'+ep);
if(h%1000>=SNUB_P*1000)return null;
const all=(h>>>10)%5<2,list=all?SNUB_ALL:SNUB_IX;
return {all,why:list[(h>>>13)%list.length],until:(ep+1)*SNUB_WIN-off};
}
/* Remote peering: offered, but discouraged. A reseller marks up the port, oversubscribes it,
and many selective networks refuse members who are not physically in the building. */
const REMOTE_FEE=1.5,REMOTE_CAP=0.8;
const REMOTE_WARN=`<p class="note" style="color:var(--bad)"><b>Remote peering is a last resort.</b> Ports come through a reseller at 1.5× the price, only 80% of the port is really yours, latency rides the fabric, one fabric outage drops every session, and many selective networks refuse remote members. A POP here is better.</p>`;
const REMOTE_WHY=['Policy: no remote peers. Be in the building or be in the transit bill.','Saw your session come in over a fabric and said "we can smell the VXC from here".','Only peers with members they can reach without a 1,500 km hairpin.','Their PearingDB entry says "Remote peering: No (we mean it)".','Tried a remote peer once. It flapped during a product launch. Never again.'];
function isRemote(c){return S.ixp[c]!==undefined&&!S.pops[ixCity(c)]&&!S.myIx[c];}
function noRemote(id){const n=NET[id];if(!n||n.pol!=='selective')return false;return hstr(id+'|remote')%100<(n.share>=0.03?60:30);}
function ixPortMo(c,tier){const x=XIX[c];if(x&&tier<=(x.freeTo??-1))return 0;return Math.round(PORT[tier].ix*(x&&x.fee||1)*(S.pops[ixCity(c)]?1:REMOTE_FEE));}
function snubWhy(sn){const d=Math.max(1,sn.until-S.day);return `${sn.why} They will reconsider in ${d} day${d===1?'':'s'}.`;}
function peerOk(id,via,city){
const n=NET[id],dem=R.demTo[id]||0;
const sn=snub(id,city);if(sn&&(via==='ix'||sn.all))return {ok:false,snub:true,why:snubWhy(sn)};
if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]};
if(n.pol==='open')return {ok:true};
if(n.pol==='selective'){const need=via==='pni'?n.minPni:n.minIx;return dem>=need?{ok:true}:{ok:false,why:`Wants ≥ ${need} Gbps of traffic from you (you send ${dem.toFixed(1)})`};}
if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:'Paid peering only, over a PNI'};
if(via!=='pni')return {ok:false,why:'Tier 1s never peer at IXs'};
const c=t1Club();return c.ok?{ok:true}:{ok:false,why:'Not big enough yet: '+c.missing.join(', ')};
}
function isTier2(){return Object.keys(S.pops).length>=5&&Object.keys(S.ixp).length>=3&&R.sessions>=15;}
function isTier1(){return NETS.filter(n=>n.type==='t1').every(n=>S.pni.some(p=>p.net===n.id))&&S.transit.length===0&&R.reach>0.999;}
function tierLabel(){return S.won?'Tier 1':isTier2()?'Tier 2':'Tier 3';}
/* ================= SIMULATION ================= */
function compute(){
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp);
const remote=remoteCities(),adj={}; pops.concat(remote).forEach(p=>adj[p]=[]);
const edges={};
for(const l of S.links){if(linkDown(l)||!adj[l.a]||!adj[l.b])continue;const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[]};adj[l.a].push([l.b,e]);adj[l.b].push([l.a,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f);e.lat=Math.min(e.lat,linkLat(l));}
const SP={};
for(const s of pops){const dist={[s]:0},prev={},done=new Set();
for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);
for(const [v,l] of adj[u]){const nd=ud+l.w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
SP[s]={dist,prev};}
const prevU=e=>{let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;return e.cap?ld/e.cap:0;};
const dijk=(s0,mode)=>{const dist={[s0]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,e] of adj[u]){const nd=ud+(mode==='fast'?e.lat+0.05:e.w*(1+10*prevU(e)));if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=e;}}}return {dist,prev};};
const E=[], ev=S.ev;
const depeer=ev.depeer>day, leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
for(const t of S.transit){if(!popUp(t.city)||t.down>day)continue;
E.push({k:'t',prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:NET[t.net].name+' transit',id:t.id,city:t.city,cap:lagCap(PORT[t.tier].g,t.n),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak});}
for(const c in S.ixp){const cc=ixCity(c);if(!(popUp(cc)||remote.includes(cc))||(S.ev.ixdown&&S.ev.ixdown[c]>day))continue;const set=ixSessions(c);R2.sessions+=set.size;
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:ixName(c)+' peering',id:c,city:cc,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n)});}
for(const p of S.pni){R2.sessions++;if(!popUp(p.city))continue;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:'PNI with '+NET[p.net].name,id:p.id,city:p.city,cap:lagCap(PORT[p.tier].g,p.n),used:0,rank:1,ok:n=>n===p.net});}
for(const c of S.caches){if(!popUp(c.city))continue;E.push({k:'c',pref:'normal',lab:NET[c.net].cache.name+' cache',id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net});}
{const rp=ev.rpki&&ev.rpki.until>day?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);}}
for(const n of NETS){R2.reachable[n.id]=E.some(e=>e.rank>0&&e.ok(n.id));if(R2.reachable[n.id])R2.reach+=NSH[n.id];}
const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net));
const viral=ev.viral>day?1.25:1;
const flows=[];
for(const c of Object.keys(S.pops)){
const p=S.pops[c],SH=cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cnCity(c)&&ev.golden>day?1.4:1);const biz=S.biz.filter(b=>b.city===c&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&(!BIZ_T[b.type].event||eventLive(b))).reduce((a,b)=>a+b.bw,0);const d=eye+biz;
R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d;
for(const n of NETS)R2.demTo[n.id]=(R2.demTo[n.id]||0)+d*(SH[n.id]||0);
if(!popUp(c))continue;
const dd=ev.ddos&&ev.ddos.city===c&&ev.ddos.until>day?d*0.7*(S.scrubAt?0.15:1):0;
if(dd)for(const n of NETS)flows.push({c,n:n.id,rem:dd*NSH[n.id],junk:true});
R2.cityBlocked=R2.cityBlocked||{};
for(const n of NETS){const a=d*(SH[n.id]||0);if(a<=0)continue;
if(cacheNets.has(n.id)){flows.push({c,n:n.id,rem:a*0.85,cache:true});flows.push({c,n:n.id,rem:a*0.15});}
else flows.push({c,n:n.id,rem:a});}
}
const res={},eload={},nres={};for(const k in edges)res[k]=edges[k].cap;for(const c of pops){nres[c]=nodeCap(c);R2.nodeCap[c]=nres[c];}
for(const b of S.biz){if(!BIZ_T[b.type].l2)continue;
// An SD-WAN is hub-and-spoke: one circuit from the first site to each of the others.
const pairs=b.sites?b.sites.slice(1).map(x=>[b.sites[0],x]):[[b.city,b.city2]];let minF=1,maxLat=0,tot=0;
for(const [A,B] of pairs){let amt=0;
if(popUp(A)&&popUp(B)&&SP[A]&&SP[A].dist[B]!==undefined){
const sp=b.route&&b.route!=='normal'?dijk(A,b.route):SP[A],path=[],ns=[B];let v=B;while(v!==A){const l=sp.prev[v];path.push(l);v=l.a===v?l.b:l.a;ns.push(v);}
amt=b.bw;for(const l of path)amt=Math.min(amt,res[l.id]);for(const n of ns)if(nres[n]!==undefined)amt=Math.min(amt,nres[n]);amt=Math.max(0,amt);maxLat=Math.max(maxLat,path.reduce((x,e)=>x+e.lat,0)+path.length*0.05);
for(const n of ns)if(nres[n]!==undefined){nres[n]-=amt;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+amt;}
const ek='l2:'+b.id;R2.egDesc[ek]={lab:(b.sites?'SD-WAN for ':'L2VPN for ')+b.name,city:A,k:'l2'};
for(const l of path){res[l.id]-=amt;eload[l.id]=(eload[l.id]||0)+amt;const rec=R2.ef[l.id]||(R2.ef[l.id]={eg:{},net:{},dst:{}});rec.eg[ek]=(rec.eg[ek]||0)+amt;rec.net.l2vpn=(rec.net.l2vpn||0)+amt;rec.dst[B]=(rec.dst[B]||0)+amt;}}
minF=Math.min(minF,amt/b.bw);tot+=amt;}
R2.l2lat[b.id]=maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;if((b.reqs||[]).includes('diverse'))R2.div[b.id]=diversePaths(b.city,b.city2);}
for(let rank=0;rank<5;rank++){
const Er=E.filter(e=>(e.pref==='low'?4:e.rank)===rank);if(!Er.length)continue;const sorted={};
for(const f of flows){
if(f.rem<=1e-6||(rank===0&&!f.cache))continue;
const sp=SP[f.c];
const srt=sorted[f.c]||(sorted[f.c]=Er.filter(e=>sp.dist[e.city]!==undefined).sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||sp.dist[a.city]-sp.dist[b.city]));
const cands=srt.filter(e=>e.used<e.cap&&e.ok(f.n));
for(const e of cands){
let amt=Math.min(f.rem,e.cap-e.used);if(amt<=1e-6)continue;
const path=[],ns=[e.city];let v=e.city;while(v!==f.c){const l=sp.prev[v];path.push(l);v=l.a===v?l.b:l.a;ns.push(v);}
for(const l of path)amt=Math.min(amt,res[l.id]);for(const n of ns)if(nres[n]!==undefined)amt=Math.min(amt,nres[n]);
if(amt<=1e-6)continue;
for(const n of ns)if(nres[n]!==undefined){nres[n]-=amt;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+amt;}
const ek=e.k+':'+e.id;R2.egDesc[ek]={lab:e.lab,city:e.city,k:e.k};
for(const l of path){res[l.id]-=amt;eload[l.id]=(eload[l.id]||0)+amt;const rec=R2.ef[l.id]||(R2.ef[l.id]={eg:{},net:{},dst:{}});rec.eg[ek]=(rec.eg[ek]||0)+amt;const nk=f.junk?'junk':f.n;rec.net[nk]=(rec.net[nk]||0)+amt;rec.dst[f.c]=(rec.dst[f.c]||0)+amt;}
e.used+=amt;f.rem-=amt;
if(!f.junk){let ok=amt;const fc=cnCity(f.c),ec=cnCity(e.city),nc=!!NET[f.n].cn;
if(fc!==ec||(fc&&!nc)||(!fc&&nc&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
if(f.n==='ggl'&&ruCity(f.c))ok*=0.5;
R2.citySrv[f.c]+=ok;R2.served+=ok;if(e.rank<=2)R2.peered+=ok;R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=R2.netEg[f.n]||(R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;}
if(f.rem<=1e-6)break;
}
}
}
for(const k in edges){const e=edges[k],ld=eload[k]||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;}
R2.peerShare=R2.served>0?R2.peered/R2.served:0;
for(const e of E){if(e.k==='t')R2.useT[e.id]=e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}
// money
const C=R2.cost,V=R2.rev,pm=S.priceMul;
C.pops=Object.values(S.pops).reduce((a,p)=>a+POP_MO+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0);
C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0);
C.links=S.links.reduce((a,l)=>a+(l.mo||0),0);
C.nni=(S.nni||[]).reduce((a,x)=>a+NNI[x.tier].mo,0);
C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0);R2.p95[t.id]=q;const n=t.n||1;return a+Math.max(q,PORT[t.tier].g*n*0.2)*NET[t.net].price*(t.premium&&t.city==='hkg'?NET[t.net].premium:1)*pm*regionMult(t.city)+PORT[t.tier].tmo*n;},0);
C.ix=Object.keys(S.ixp).reduce((a,c)=>a+(S.myIx[c]?MYIX_MO:ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1)),0);
C.pni=S.pni.reduce((a,p)=>a+PORT[p.tier].pni*(p.n||1)+(NET[p.net].pol==='paid'?NET[p.net].paidFee:0),0);
C.caches=S.caches.length*CACHE_MO;
C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.pay),0);
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+(S.scrubAt?SCRUB_MO:0)+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO;
V.eyeballs=0;V.business=0;V.ix=0;
for(const c in S.pops){const sf=sfOf(R2,c);V.eyeballs+=R2.cityEye[c]*sf*EYE_RATE*(CITY[c].arpu||1);}
for(const b of S.biz){const sf=BIZ_T[b.type].fiber?(fiberOk(b)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);}
for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE;
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?l.share:0),0)*(V.eyeballs+V.business+V.ix);
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);
R2.revMo=V.eyeballs+V.business+V.ix;
R=R2;
}
function p95(t,cur){const h=(t.hist||[]).slice(-29).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];}
function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);}
function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);}
function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0);}
function nniPort(c,prov){return (S.nni||[]).find(x=>x.city===c&&x.prov===prov);}
function migrate(s){s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave';
for(const c in s.pops){const p=s.pops[c];if(p.rgen===undefined){let g=0;const need=(i,key)=>{const k=RG.findIndex(r=>r[key]>=i);if(k>g)g=k;};
for(const l of s.links||[])if((l.a===c||l.b===c)&&l.kind==='wave')need(l.tier,'maxLT');
for(const t of s.transit||[])if(t.city===c)need(t.tier,'maxP');for(const x of s.pni||[])if(x.city===c)need(x.tier,'maxP');for(const k in s.ixp||{})if(ixCity(k)===c)need(s.ixp[k],'maxP');p.rgen=g;}}for(const b of s.biz||[])if(!b.reqs)b.reqs=BIZ_T[b.type]&&BIZ_T[b.type].div?['diverse']:[];for(const o of s.offers||[])if(!o.reqs)o.reqs=[];if(!s.lvl)s.lvl=1;s.nni=s.nni||[];s.cnLic=s.cnLic||{state:'none'};if(s.scrubAt===undefined)s.scrubAt=null;s.ev=s.ev||{};for(const l of s.links){if(!l.kind)l.kind='wave';if(l.mo===undefined)l.mo=Math.round(waveMo(l.km,l.sub,l.tier)*(l.mult||1));}for(const c in s.pops){if(!s.pops[c].routers)s.pops[c].routers=1;}return s;}
const REQS={
lat:{only:true,l2:true,bonus:0,l:o=>`One-way latency within ${o.latMax} ms (best now: ${(()=>{const v=R.l2lat[o.id]!==undefined?R.l2lat[o.id]:bestLat(o.city,o.city2);return isFinite(v)?v.toFixed(1)+' ms':'no path'})()})`,ok:b=>(R.l2lat[b.id]!==undefined?R.l2lat[b.id]:bestLat(b.city,b.city2))<=b.latMax},
diverse:{l:'Two paths that share no trench or fabric',bonus:.25,l2:true,ok:b=>R.div[b.id]!==undefined?!!R.div[b.id]:diversePaths(b.city,b.city2)},
sharks:{l:'Afraid of sharks: needs a path with no subsea cable',bonus:.2,l2:true,ok:b=>terrestrialPath(b.city,b.city2)},
nocog:{l:'Refuses Cogentle transit anywhere on your network (long story)',bonus:.15,ok:()=>!S.transit.some(t=>t.net==='cog')},
ipv6:{l:'IPv6 or bust: you must peer with Drizzle Electric',bonus:.1,ok:()=>Object.keys(S.ixp).some(c=>ixSessions(c).has('drz'))||S.pni.some(p=>p.net==='drz')},
netchill:{l:'Wants NetChill on-net: a cache or a PNI',bonus:.15,ok:()=>S.caches.some(c=>c.net==='nfx')||S.pni.some(p=>p.net==='nfx')},
gen:{l:'Backup generator in every city they touch',bonus:.15,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].gen)},
routers:{l:'Insists on two routers in their city',bonus:.15,ok:b=>((S.pops[b.city]&&S.pops[b.city].routers)||1)>=2},
local:{l:'Local breakout: transit or an IX port in their own city',bonus:.2,ip:true,ok:b=>S.transit.some(t=>t.city===b.city)||Object.keys(S.ixp).some(k=>ixCity(k)===b.city)},
twoup:{l:'Wants two different transit providers (or none at all)',bonus:.15,ip:true,ok:()=>new Set(S.transit.map(t=>t.net)).size>=2||S.transit.length===0},
china:{l:'Needs low-loss reach into China',bonus:.3,ip:true,ok:()=>S.transit.some(t=>t.premium&&t.city==='hkg')||S.links.some(l=>l.premium)||S.pni.some(p=>NET[p.net].cn)},
scrubbed:{l:'Will only sign with a network that runs a DDoS scrubbing center',bonus:.15,ok:()=>!!S.scrubAt},
puns:{l:'Their CEO hates puns. Please do not mention the network names.',bonus:.05,ok:()=>true},
};
function terrestrialPath(a,b){const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b));
function reqList(o){return (o.reqs||[]).map(k=>{const ok=REQS[k].ok(o),lab=typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l;return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(lab)}</div>`;}).join('');}
function diversePaths(a,b){
const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);
const live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));}
function fiberOk(b){const l=S.links.find(x=>x.id===b.link);return !!l&&!linkDown(l);}
function soldSlots(l){return S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);}
function bizSf(b){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):sfOf(R,b.city);}
function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);}
function bHas(o){return bCities(o).every(c=>S.pops[c]);}
function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day<b.start+b.dur;}
function bTerms(o){const T=BIZ_T[o.type];
if(T.event){const live=S.day>=o.start;return `${fmtG(o.bw)} extra for ${o.dur} days, ${live?`day ${S.day-o.start+1} of ${o.dur}`:`starting in ${o.start-S.day}d`} · pays ${fmt$(o.fee)} when it is over`;}
if(T.sdwan)return `${o.sites.length} sites: ${o.sites.map(c=>CITY[c].name).join(', ')} · ${fmtG(o.bw)} per site · ${fmt$(o.bw*o.rate)}/mo`;
if(T.fiber)return `${esc(o.what)} · ${fmt$(o.rate)}/mo`;
return `${fmtG(o.bw)} · ${fmt$(o.bw*o.rate)}/mo`;}
// Events are paid once at the end, prorated by how much of the crowd you served.
function eventTick(b,d){if(!BIZ_T[b.type].event)return false;if(d<b.start)return true;
if(d<b.start+b.dur){b.srv=(b.srv||0)+sfOf(R,b.city);b.srvDays=(b.srvDays||0)+1;if(d===b.start)toast(`<b>${esc(b.name)} starts today!</b><br>${fmtG(b.bw)} of extra demand in ${CITY[b.city].name} for ${b.dur} days.`,'goal',[{l:'Show me',act:'focusCity',args:{city:b.city}}]);return true;}
const avg=b.srvDays?b.srv/b.srvDays:0,pay=avg>=0.95?b.fee:avg>=0.7?Math.round(b.fee*avg):-Math.round(b.fee*0.2);S.cash+=pay;S.biz=S.biz.filter(x=>x!==b);
toast(pay>=0?`<b>${esc(b.name)} is over: +${fmt$(pay)}</b><br>You delivered ${pct(avg)} of what the crowd wanted.${avg>=0.95?' Flawless.':''}`:`<b>${esc(b.name)} was a disaster.</b><br>Only ${pct(avg)} delivered, and it trended on social media. Penalty: ${fmt$(-pay)}.`,pay>=0?'good':'bad');sfx(pay>=0?'coin':'err');return true;}
function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=S.lvl||1;
const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(T.names);S.usedNames.push(n);return n;};
if(T.event){const city=Math.random()<0.85&&mine.length?pick(mine):pick(ALLC);const bw=pick(T.opts.slice(0,Math.min(T.opts.length,lv+2)));const dur=3+Math.floor(Math.random()*5),start=S.day+12+Math.floor(Math.random()*14);
S.offers.push({id:uid(),city,city2:null,name:nm()+' in '+CITY[city].name,type:t,bw,rate:0,reqs:[],start,dur,fee:Math.round(bw*dur*70),exp:start-2});return;}
if(T.sdwan){const hub=pick(mine),n=3+Math.floor(Math.random()*4),pool=(Math.random()<0.85?mine:ALLC).filter(c=>c!==hub),sites=[hub];
while(sites.length<n&&pool.length)sites.push(pool.splice(Math.floor(Math.random()*pool.length),1)[0]);if(sites.length<3)return;
S.offers.push({id:uid(),city:hub,city2:null,sites,name:nm(),type:t,bw:pick(T.opts),rate:700*sites.length,reqs:[],exp:S.day+40});return;}
const ready=S.links.filter(l=>l.kind==='df'&&l.ready<=S.day);
if(t==='wwave'){const free=l=>DF_SYS[l.sys].max-(l.ch||[]).length-soldSlots(l);const ls=ready.filter(l=>free(l)>=1&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls),slots=1+Math.floor(Math.random()*Math.min(4,free(l)));
S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,slots,what:`${slots}× 400G alien wave${slots>1?'s':''} on your ${CITY[l.a].name}–${CITY[l.b].name} fiber`,name:nm(),type:t,bw:1,rate:Math.round(waveMo(l.km,false,2)*0.55*slots),reqs:[],exp:S.day+30});return;}
if(t==='dfpair'){const ls=ready.filter(l=>l.own&&S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length<2&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls);
S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:`a spare fiber pair in your ${CITY[l.a].name}–${CITY[l.b].name} trench`,name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9),reqs:[],exp:S.day+30});}
}
function cnOk(){return S.cnLic&&S.cnLic.state==='ok';}
function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;return C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:1;}
function landMult(a,b){return !isSub(a,b)&&CITY[a].reg!==CITY[b].reg?2.5:1;}
function linkLat(l){const f=l.kind==='df'?(l.own?1.1:1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;}
function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let via=UI.via;
if(!cabs.find(c=>c.cid===via))via=sub?(cabs[0]?cabs[0].cid:null):(via==='land'||!via?'land':'land');
if(!via)return null;const bf=border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1;
if(via==='land')return {via,cabs,cab:null,km:kmBetween(a,b),sub:false,wm:mult*landMult(a,b)};
const c=cabs.find(x=>x.cid===via);return {via,cabs,cab:via,km:c.km,sub:true,wm:bf*CAB[via].price};}
function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`<p class="note">Overland between continents crosses a dozen borders: 2.5× the price.</p>`:'';const wr=waveRoute(a,b,1,false);
const opts=(sub?[]:[{v:'land',l:`Overland <small>${landMult(a,b)>1?'2.5× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms</small>`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} <small>${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · old, cuts often':''}</small>`})));
return `<h4 class="sub4">Route</h4><div class="seg">${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}</div>${wr&&wr.cab?`<p class="note">${esc(CAB[wr.cab].blurb)} All your waves on one cable share its fate when it is cut.</p>`:''}`;}
function bestLat(a,b){const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;}
const RT={normal:'Follow metrics',fast:'Lowest latency',scenic:'Scenic (quietest links)'};
function routeCtl(b){const lt=R.l2lat[b.id];return `<div class="btns"><span class="meta" style="align-self:center">Route:</span>${Object.keys(RT).map(m=>btn(RT[m],'setRoute',{id:b.id,m},(b.route||'normal')===m?'pink sm':'ghost sm')).join('')}</div><div class="meta">Path latency: <b>${lt!==undefined?lt.toFixed(1)+' ms one-way':'no path yet'}</b>${b.latMax?` · budget ${b.latMax} ms`:''}</div>`;}
function nodeCap(c){const p=S.pops[c];if(!p)return Infinity;const eff=(p.routers||1)-(p.rdown>S.day?1:0);return RG[p.rgen||0].cap*Math.max(1,eff)*(p.hot>S.day?0.5:1);}
function portOk(c,i){const p=S.pops[c];return i<=RG[p?(p.rgen||0):0].maxP;}
function waveOk(a,b,i){return [a,b].every(c=>i<=RG[S.pops[c]?(S.pops[c].rgen||0):0].maxLT);}
function waveNeed(i){const g=RG.find(r=>r.maxLT>=i);return g?g.n:'?';}
function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return g<RG.length-1&&RG[g].maxP<PORT.length-1?`<p class="note" style="margin-top:0">Your ${esc(RG[g].n)} here tops out at ${RG[g].pn} ports. Bigger ports need a router upgrade (Infra tab).</p>`:'';}
function sfOf(r,c){const d=r.cityDem[c]||0;return d<=1e-6?1:clamp(r.citySrv[c]/d,0,1);}
/* ---------- failures & events ---------- */
function addInc(o){o.id=uid();o.start=S.day;S.inc.push(o);S.stats.incidents++;}
const HARMLESS=[
['Certificate expired','The TLS certificate on your NOC dashboard expired. Nobody can see any graphs, so technically there are no problems.'],
['It was DNS','Someone deleted the DNS record for the internal wiki. The runbook for fixing DNS was on the wiki.'],
['Leap second','A leap second convinced one of your routers it is 1970. Uptime now reads minus 56 years. Traffic is fine.'],
['Change freeze','Management declared a change freeze. Someone made a change to announce the change freeze.'],
['Ticket of the week','A customer opened a P1 ticket: “the internet is slow”. Attached was a photo of their router, unplugged.'],
['Monitoring','Your monitoring system went down. You found out because nothing alerted. Very peaceful week.'],
['Load-bearing typo','Someone named a VLAN “prodcution”. It is now load-bearing and can never be renamed.'],
['IPv6 milestone','Your IPv6 traffic grew 400%. From one packet to five.'],
['Mystery link','You found a 10G link in the inventory that nobody ordered, nobody pays for, and that carries 3 Gbps of something.'],
['Spreadsheet IPAM','Your IP address spreadsheet hit 1,048,576 rows. Excel has opinions.'],
['Goose incident','A goose attacked the technician on the way to your amp hut. The goose won. Repair rescheduled, nothing broke.'],
['Latency test','A carrier pigeon beat one of your links in an informal latency test. Morale is low. Throughput is fine.'],
['Zombie route','A route you withdrew in Year 1 is still visible somewhere in the internet. Nobody knows where. It is fine. Probably.'],
['Auditor visit','An auditor asked for a network diagram. You sent the game map. They approved it.'],
['Open to work','Your peering coordinator updated their profile to “open to work”. Three Tier 1s suddenly want to chat. Nothing happened, but it felt nice.'],
['Hold music','Your upstream support line plays the same 11 seconds of hold music. Your on-call engineer can now hum it in four keys.'],
['Naming committee','A two-hour meeting about router hostnames ended with a vote for “router-final-v2-NEW”.'],
['Vendor TAC','Vendor support asked you to “try turning it off and on again”. For the router you already rebooted. Ticket closed.'],
];
function fireFailure(){
const opts=[];
const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))];
if(live.length){opts.push(['cut',2+Math.min(6,live.length/2)]);}
if(Object.keys(S.pops).length)opts.push(['crash',3],['power',2]);
if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]);
if(Object.keys(S.ixp).length)opts.push(['ixloop',2]);
if(S.transit.length&&S.day>60)opts.push(['leak',2]);
if(S.day>40)opts.push(['ddos',2]);
if(fabsUsed.length)opts.push(['fabric',1.5]);
const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0);if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]);
opts.push(['funny',4]);
if(!opts.length)return;
let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0];
for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}
if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label');if(Object.keys(S.ixp).length)f.push('maxpfx');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.length)f.push('roadmff');type=pick(f);}
const before=R.served;
if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`<b>${m[0]}</b><br>${m[1]}`,'goal');sfx('alert');return;}
if(type==='ac'){const c=pick(Object.keys(S.pops)),pp=S.pops[c];pp.hot=S.day+2;
addInc({type,ref:c,until:pp.hot,msg:pick([`The A/C at ${CITY[c].dc} died on the hottest day of the year. Your routers in ${CITY[c].name} throttled to half capacity.`,`Someone set the data center thermostat in ${CITY[c].name} to Fahrenheit thinking it was Celsius. Routers are cooking at half speed.`,`The cooling contractor in ${CITY[c].name} replaced the chillers with a very confident fan. Half capacity for two days.`]),cost:2000,fix:'Buy 40 desk fans'});
}else if(type==='fatwave'||type==='label'){
const l=pick(live),dur=1+Math.floor(Math.random()*2),A=CITY[l.a].name,B=CITY[l.b].name,W=pick(WAVECO);l.cut=Math.max(l.cut||0,S.day+dur);
const msg=type==='label'?pick([`Someone in ${CITY[l.a].dc} labeled every patch cable “DO NOT UNPLUG”. Someone else unplugged one anyway: your ${A}–${B} link.`,`A remote-hands tech in ${A} was asked to clean the fiber on port 1. They cleaned it with a sandwich. ${A}–${B} is down.`,`A new tech in ${A} “tidied up” the cable mess. Your ${A}–${B} link was part of the mess.`])
:l.kind==='df'?pick([`The landlord in ${A} re-routed the building riser and pinched your dark fiber to ${B}.`,`A splicer fusing someone else’s cable in a manhole near ${B} fused yours instead.`])
:pick([`${W} fat-fingered a cross-connect and patched your ${A}–${B} wave into a pizza oven.`,`${W} did “quick maintenance” on the wrong wavelength. Your ${A}–${B} wave is now carrying someone else's cat videos.`,`${W} scheduled maintenance in UTC. Your team read it as local time. ${A}–${B} went dark at peak.`,`An engineer at ${W} swapped Tx and Rx on your ${A}–${B} wave. Light goes in, confusion comes out.`,`${W} decommissioned your ${A}–${B} wave because the ticket said “decom” instead of “docs”.`]);
addInc({type,ref:l.id,until:l.cut,msg,cost:1500,fix:'Bribe their NOC with donuts'});
}else if(type==='mtu'){
const l=pick(live);l.deg=S.day+3;addInc({type,ref:l.id,until:l.deg,msg:`MTU mismatch on ${CITY[l.a].name}–${CITY[l.b].name}: jumbo frames keep getting stuck in the tube. Usable capacity halved.`,cost:800,fix:'Set MTU 9216 everywhere'});
}else if(type==='oops'||type==='cleaner'){
const c=pick(Object.keys(S.pops)),pp=S.pops[c],C=CITY[c].name;
if(type==='cleaner'&&(pp.routers||1)>=2){S.stats.incidents++;S.stats.survived++;toast(`<b>Vacuum incident in ${C}</b><br>The cleaner at ${CITY[c].dc} unplugged one of your routers to plug in a vacuum. The other one kept going. The floor is spotless.`,'good');sfx('alert');return;}
pp.down=Math.max(pp.down||0,S.day+1);
const msg=type==='cleaner'?`The cleaner at ${CITY[c].dc} unplugged your router to plug in a vacuum. The floor is spotless.`:pick([`Your on-call engineer typed “clear bgp *” in production in ${C} at 3am. It cleared.`,`An intern pushed an ACL in ${C} that denies 0.0.0.0/0. Very secure. Very offline.`,`Someone ran “reload” on the ${C} router, thinking it was their laptop terminal.`,`A config template rendered “{{ router_id }}” literally in ${C}. The router took it personally.`,`Someone committed a config in ${C} with “commit confirmed 1” and went to lunch.`,`Someone deployed to ${C} on a Friday at 16:59.`,`A cosmic ray flipped a bit in your ${C} router. It now believes 10.0.0.0/8 lives in Antarctica.`,`An automation script in ${C} ran “sed” on the whole config instead of one line. Every interface is now named “TODO”.`]);
addInc({type,ref:c,until:pp.down,msg:msg+(type==='oops'&&(pp.routers||1)>=2?' Automation pushed it to every router, so redundancy did not help.':''),cost:1500,fix:type==='oops'?'Roll back the config':'Hide the vacuum'});
}else if(type==='maxpfx'){
const c=pick(Object.keys(S.ixp));S.ev.ixdown=S.ev.ixdown||{};S.ev.ixdown[c]=Math.max(S.ev.ixdown[c]||0,S.day+1+Math.floor(Math.random()*2));
addInc({type,ref:c,until:S.ev.ixdown[c],msg:`A member at ${ixName(c)} leaked the full routing table into the route server. Max-prefix limits tripped everywhere. Peering there is down.`,cost:0});
}else if(type==='prepend'){
const t=pick(S.transit);t.down=Math.max(t.down||0,S.day+2);addInc({type,ref:t.id,until:t.down,msg:`${NET[t.net].name} fat-fingered a route-map and prepended your AS ${30+Math.floor(Math.random()*60)} times in ${CITY[t.city].name}. Nobody wants that path.`,cost:0});
}else if(type==='rpki'){
S.ev.rpki={until:S.day+3,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.5)};addInc({type,ref:'rpki',until:S.day+3,msg:'Your ROA expired over the weekend. Your prefixes are RPKI-invalid and about half the internet is dropping them.',cost:1000,fix:'Renew the ROA'});
}else if(type==='amp'||type==='roadmff'){
const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur;
const msg=type==='roadmff'?`You fat-fingered the channel plan on ${A}–${B} and lit a new channel right on top of every existing one.`:pick([`An in-line amplifier hut between ${A} and ${B} lost power. A family of mice had moved in.`,`Someone stole the copper grounding from an amp hut on ${A}–${B}. All channels dark.`,`A firmware bug in the ${DF_SYS[l.sys].n} at ${A} set every channel to “maintenance”.`,`Lightning hit an amp site on ${A}–${B}. The surge protector was decorative.`]);
addInc({type,ref:l.id,until:l.eqDown,msg:msg+(type==='amp'&&l.spares?' Your spares kit gets it back tomorrow.':''),cost:type==='amp'&&!l.spares?AMP_COST:0,fix:'Truck a spare amp out'});
}else if(type==='optic'){
const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,o=pick(l.ch),dur=l.spares?1:4;l.chFail={n:1,o,until:S.day+dur};
addInc({type,ref:l.id,until:S.day+dur,msg:pick([`A ${OPT[o].n} on ${A}–${B} overheated and is now a very expensive keychain.`,`The laser in a ${OPT[o].n} on ${A}–${B} died. One channel dark.`,`A ${OPT[o].n} on ${A}–${B} started reporting a temperature of 900°C. It was wrong, but it shut down anyway.`])+(l.spares?' Swapped from your spares kit by tomorrow.':''),cost:l.spares?0:OPT[o].cost,fix:'Buy a replacement'});
}else if(type==='cut'){
const l=pick(live.flatMap(x=>x.cable&&CAB[x.cable].age==='old'?[x,x,x]:[x])),dur=10+Math.floor(Math.random()*8),tr=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===tr);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));
const A=CITY[l.a].name,B=CITY[l.b].name;
const msg=l.sub?pick([`A curious shark bit your subsea cable ${A}–${B}.`,`A ship dragged its anchor across your ${A}–${B} cable.`,`An undersea landslide snapped ${A}–${B}.`]):pick([`A backhoe found your fiber between ${A} and ${B}.`,`Squirrels chewed through ${A}–${B}. They regret nothing.`,`Road works cut ${A}–${B}. Nobody called before digging.`]);
addInc({type,ref:tr,until:S.day+dur,msg:msg+(hit.length>1?` All ${hit.length} links in that trench went down with it.`:''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))});
}else if(type==='crash'||type==='power'){
const c=pick(Object.keys(S.pops)),pp=S.pops[c],dur=(type==='crash'?2+Math.floor(Math.random()*2):3+Math.floor(Math.random()*3))*(type==='crash'&&S.ev.sanction>S.day?2:1);
if(type==='crash'&&(pp.routers||1)>=2){pp.rdown=S.day+dur;S.stats.incidents++;S.stats.survived++;toast(`<b>Router crash in ${CITY[c].name}</b><br>One router panicked and its twin took over. Capacity there is down one router for ${dur} days.`,'good');sfx('alert');return;}
if(type==='power'&&pp.gen){S.stats.incidents++;S.stats.survived++;toast(`<b>Power cut in ${CITY[c].name}</b><br>Your backup generator kicked in. Lights stayed on.`,'good');sfx('alert');return;}
pp.down=Math.max(pp.down||0,S.day+dur);
const msg=type==='crash'?pick([`Your router in ${CITY[c].name} crashed. Kernel panic, packet panic.`,`A firmware update bricked your router in ${CITY[c].name}.`]):`Power outage at ${CITY[c].dc} in ${CITY[c].name}. The generator did not start.`;
addInc({type,ref:c,until:S.pops[c].down,msg,cost:type==='crash'?2500:7000,fix:type==='crash'?'Turn it off and on again':'Rent a generator'});
}else if(type==='transit'){
const t=pick(S.transit.filter(t=>!(t.down>S.day)));t.down=S.day+3+Math.floor(Math.random()*3);
addInc({type,ref:t.id,until:t.down,msg:`${NET[t.net].name} is having an outage in ${CITY[t.city].name}. Your transit port there is dark.`,cost:0});
}else if(type==='ixloop'){
const c=pick(Object.keys(S.ixp));S.ev.ixdown=S.ev.ixdown||{};S.ev.ixdown[c]=Math.max(S.ev.ixdown[c]||0,S.day+2+Math.floor(Math.random()*2));
addInc({type,ref:c,until:S.ev.ixdown[c],msg:`Someone plugged a loop into the ${ixName(c)} fabric. Broadcast storm! All peering there is down.`,cost:0});
}else if(type==='leak'){
const n=pick(['nfx','ggl','fbk','amz','msf']);S.ev.leak={net:n,until:S.day+4};
addInc({type,ref:n,until:S.day+4,msg:`BGP route leak: a small ISP is announcing ${NET[n].name}'s prefixes. Traffic to them over transit is black-holed. Direct peering still works.`,cost:0});
}else if(type==='fabric'){
const f=pick(fabsUsed);S.ev.fab=S.ev.fab||{};S.ev.fab[f]=S.day+2+Math.floor(Math.random()*3);
addInc({type,ref:f,until:S.ev.fab[f],msg:`${FAB[f].name} is having a bad day. Every virtual circuit on their fabric is down.`,cost:0});
}else if(type==='ddos'){
const c=pick(Object.keys(S.pops));S.ev.ddos={city:c,until:S.day+4};
if(S.scrubAt){S.stats.survived++;toast(`<b>DDoS on ${CITY[c].name}</b><br>A botnet of smart toasters tried. Your scrubbing center in ${CITY[S.scrubAt].name} ate most of it.`,'good');sfx('alert');addInc({type,ref:c,until:S.day+4,msg:'Mostly absorbed by scrubbing.',cost:0});return;}
addInc({type,ref:c,until:S.day+4,msg:`A botnet of smart toasters is DDoSing ${CITY[c].name}. Junk traffic is eating your capacity.`,cost:6000,fix:'Buy scrubbing'});
}
compute();
const last=S.inc[S.inc.length-1];
last.impact=Math.max(0,before-R.served);
if(before>1&&last.impact<before*0.03&&type!=='ddos'){S.stats.survived++;toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)} Traffic rerouted, customers barely noticed.`,'good');}
else toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}`,'bad',last.cost?[{l:`${last.fix||'Rush repair'} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]);
sfx('alert');
}
function incTitle(t){return {cut:'Fiber cut',crash:'Router crash',power:'Power outage',transit:'Upstream outage',ixloop:'IX meltdown',leak:'Route leak',ddos:'DDoS attack',fabric:'Fabric outage',depeer:'Peering spat',fatwave:'Fat-fingered wave',label:'Patch panel mishap',mtu:'MTU mismatch',oops:'Oops',cleaner:'Vacuum incident',maxpfx:'Max-prefix meltdown',prepend:'Prepend-ageddon',rpki:'RPKI invalid',amp:'Amplifier failure',roadmff:'Fat-fingered ROADM',optic:'Dead optic',maint:'Maintenance window',ac:'Cooling failure',hijack:'BGP hijack',shutdown:'Government shutdown',redsea:'Geopolitical cable cut'}[t]||'Incident';}
const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic'];
function remainUntil(pred){let u=0;for(const x of S.inc)if(pred(x))u=Math.max(u,x.until);return u;}
// Remove an incident, then restore each affected thing to whatever other incidents still hold it down.
function clearInc(i){
S.inc=S.inc.filter(x=>x!==i);const T=i.type;
if(LINKCUT_TR.includes(T)||LINKCUT_ID.includes(T)){const ls=LINKCUT_TR.includes(T)?S.links.filter(l=>(l.trench||l.id)===i.ref):S.links.filter(l=>l.id===i.ref);
for(const l of ls)l.cut=remainUntil(x=>(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id));}
else if(POPDOWN.includes(T)){if(S.pops[i.ref])S.pops[i.ref].down=remainUntil(x=>POPDOWN.includes(x.type)&&x.ref===i.ref);}
else if(IXDOWN.includes(T)){if(S.ev.ixdown)S.ev.ixdown[i.ref]=remainUntil(x=>IXDOWN.includes(x.type)&&x.ref===i.ref);}
else if(TDOWN.includes(T)){const t=S.transit.find(x=>x.id===i.ref);if(t)t.down=remainUntil(x=>TDOWN.includes(x.type)&&x.ref===i.ref);}
else if(T==='rpki'||T==='hijack'){if(!S.inc.some(x=>x.type==='rpki'||x.type==='hijack'))S.ev.rpki=null;}
else if(T==='leak'){S.ev.leak=null;}
else if(T==='ddos'){S.ev.ddos=null;}
else if(T==='fabric'){if(S.ev.fab)S.ev.fab[i.ref]=remainUntil(x=>x.type==='fabric'&&x.ref===i.ref);}
else if(T==='mtu'){const l=S.links.find(x=>x.id===i.ref);if(l)l.deg=remainUntil(x=>x.type==='mtu'&&x.ref===i.ref);}
else if(T==='ac'){if(S.pops[i.ref])S.pops[i.ref].hot=remainUntil(x=>x.type==='ac'&&x.ref===i.ref);}
else if(T==='amp'||T==='roadmff'){const l=S.links.find(x=>x.id===i.ref);if(l)l.eqDown=remainUntil(x=>(x.type==='amp'||x.type==='roadmff')&&x.ref===i.ref);}
else if(T==='optic'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='optic'&&x.ref===i.ref))l.chFail=null;}
}
function purgeInc(){S.inc=S.inc.filter(i=>{const T=i.type;if(LINKCUT_TR.includes(T))return S.links.some(l=>(l.trench||l.id)===i.ref);if(LINKCUT_ID.includes(T)||LINKEQ.includes(T))return S.links.some(l=>l.id===i.ref);if(TDOWN.includes(T))return S.transit.some(t=>t.id===i.ref);if(IXDOWN.includes(T))return S.ixp[i.ref]!==undefined;if(POPDOWN.includes(T)||T==='ac')return !!S.pops[i.ref];return true;});}
function fireEvent(){
const opts=['viral','price','grant'];
if(S.day>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
if(Object.keys(S.pops).some(ruCity))opts.push('runet','runet');
if(['mnl','hkg','tok','icn','sha','jkt'].some(c=>S.pops[c]))opts.push('typhoon');
if(Object.keys(S.pops).some(cnCity)||R.gfwCross>1)opts.push('golden','gfw');
if(S.transit.some(t=>t.net==='cog'))opts.push('depeer','depeer');
if(Object.keys(S.peers).some(k=>k.startsWith('drz@'))||Object.keys(S.rs).length)opts.push('cake');
const e=pick(opts);
if(e==='sanction'){S.ev.sanction=S.day+60;toast('<b>Sanctions!</b><br>The Republic of Paperworkistan sanctioned your router vendor’s favorite screw supplier. Spare parts are slow: router crashes take twice as long to fix for 60 days.','bad');sfx('alert');return;}
if(e==='tariff'){S.ev.tariff=S.day+90;toast('<b>Trade war on optics</b><br>Two governments slapped tariffs on each other’s lasers. Optics cost 40% more for 90 days.','bad');sfx('alert');return;}
if(e==='hijack'){S.ev.rpki={until:S.day+1,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.6)};addInc({type:'hijack',ref:'rpki',until:S.day+1,msg:'A state-owned ISP “accidentally” announced your prefixes for 18 minutes. Their apology press release was suspiciously well written. Many networks are still routing your traffic into the void.',cost:1500,fix:'Call everyone you know'});toast('<b>BGP hijack</b><br>Someone else is announcing your prefixes. Reach is down until it is cleaned up.','bad');sfx('alert');return;}
if(e==='landban'){const lc=[...new Set(CABLE_PAIRS.flatMap(c=>[c.a,c.b]))];const c=pick(lc);S.ev.landban={city:c,until:S.day+45};toast(`<b>Landing permit dispute in ${CITY[c].name}</b><br>Two ministries both claim the beach. No new subsea links can land there for 45 days.`,'bad');return;}
if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:`Regulators ordered every network in ${CITY[c].name} to switch off for a day during national school exams. Yes, this really happens.`,cost:0});toast(`<b>Ordered offline in ${CITY[c].name}</b><br>A government exam-day shutdown. Your POP there is dark for a day.`,'bad');sfx('alert');return;}
if(e==='typhoon'){const c=pick(['mnl','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick(['Typhoon Bandwidth','Typhoon Latency','Typhoon Jitter','Typhoon Packet-Loss']);
if(p.gen){S.stats.survived++;toast(`<b>${nm} hits ${CITY[c].name}</b><br>The grid is down, but your backup generator kept the routers running.`,'good');sfx('alert');return;}
p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:`${nm} knocked out power in ${CITY[c].name}. Your POP has no generator.`,cost:7000,fix:'Rent a generator'});toast(`<b>${nm} hits ${CITY[c].name}</b><br>Power is out and your POP is dark for two days. A generator would have saved it.`,'bad');sfx('alert');compute();return;}
if(e==='runet'){S.ev.runet=S.day+1;toast('<b>Sovereign internet drill</b><br>Moscow unplugged itself from the rest of the internet for a day to see what happens. Everything leaving Russia is dark until tomorrow.','bad');sfx('alert');compute();return;}
if(e==='baltic'){const BAL=['clion','havf','danice'];const hit=S.links.filter(l=>l.cable&&BAL.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast('<b>Baltic cable damaged</b><br>A cargo ship dragged its anchor for 100 km and swears it noticed nothing. You have no links on those cables.','goal');return;}
const dur=15+Math.floor(Math.random()*15);for(const tr of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tr).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tr,until:S.day+dur,msg:'A cargo ship dragged its anchor along the Baltic seabed for 100 km and swears it noticed nothing. Investigators are “looking into it”.',cost:0});}
toast(`<b>Baltic cable damaged</b><br>${hit.length} of your links are down for about ${dur} days.`,'bad');sfx('alert');compute();return;}
if(e==='redsea'){const RED=['twoaf','smw6','peace','aae','eig','eassy'];const hit=S.links.filter(l=>l.cable&&RED.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast('<b>Cables cut in the Red Sea</b><br>A ship dragged its anchor across several cables. Everyone blames everyone. Luckily you do not use those cables.','goal');return;}
const dur=20+Math.floor(Math.random()*15);for(const tr of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tr).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tr,until:S.day+dur,msg:`A ship drifting without power dragged its anchor through the Red Sea cables. Everyone blames everyone. Repair ships need permits from three governments.`,cost:0});}
toast(`<b>Cables cut in the Red Sea</b><br>${hit.length} of your subsea links are down for about ${dur} days while the diplomats argue about repair ships.`,'bad');sfx('alert');compute();return;}
if(e==='golden'){S.ev.golden=S.day+7;toast('<b>Golden Week!</b><br>Demand in mainland China is up 40% for a week.','goal');return;}
if(e==='gfw'){S.ev.gfw=S.day+10;toast('<b>The border got stricter.</b><br>Cross-border packet loss rises to 35% for 10 days. Premium routes are barely affected.','bad');sfx('alert');return;}
if(e==='viral'){S.ev.viral=S.day+8;toast('<b>New season of “Stranger Pings” just dropped!</b><br>Eyeball demand is up 25% for a week. Got headroom?','goal');}
else if(e==='price'){S.priceMul*=0.92;toast('<b>Transit prices fell 8%.</b><br>They do this every year. Nobody knows where the bottom is.','good');}
else if(e==='grant'){S.cash+=30000;toast('<b>Rural broadband grant: +$30k</b><br>The Ministry of Tubes likes what you are doing.','good');sfx('coin');}
else if(e==='depeer'){S.ev.depeer=S.day+20;addInc({type:'depeer',ref:'cog',until:S.day+20,msg:'Cogentle and Goggle are in a peering spat. Goggle is unreachable through Cogentle transit.',cost:0});toast('<b>Peering spat!</b><br>Cogentle de-peered Goggle for 20 days. Goggle traffic over Cogentle transit is gone. Peer with Goggle directly or use another upstream.','bad');sfx('alert');}
else if(e==='cake'){S.cash+=8000;toast('<b>Drizzle Electric sent you an IPv6 cake.</b><br>You sold it for $8k.','good');sfx('coin');}
}
/* ---------- daily tick ---------- */
function dayTick(){
if(!S||S.lost)return;
S.day++;
const d=S.day;
for(const k in S.peers){const [id,c]=k.split('@'),sn=snub(id,c);if(!sn)continue;delete S.peers[k];
toast(`<b>${esc(NET[id].name)} de-peered you in ${esc(CITY[c].name)}.</b><br>${esc(sn.why)} Traffic falls back to your next best path.`,'bad');}
if(S.cnLic&&S.cnLic.state==='pending'&&d>=S.cnLic.ready){S.cnLic.state='ok';toast('<b>License granted!</b><br>Your joint venture can now build POPs in mainland China.','goal');sfx('coin');}
// resolve incidents
for(const i of S.inc.slice())if(i.until<=d){clearInc(i);toast(`<b>Resolved:</b> ${incTitle(i.type).toLowerCase()} is fixed.`,'good');}
// eyeball growth / churn uses last computed service
for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c),P=CITY[c].P;
if(sf>=0.9){const g=0.025*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);}
else p.bb.d=Math.max(3,p.bb.d*(1-(0.9-sf)*0.04));}
compute();
for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();}
S.cash+=(R.revMo-R.costMo)/30;
S.stats.peak=Math.max(S.stats.peak,R.served);
S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift();
{const lv=custLevel();if(lv>(S.lvl||1)){S.lvl=lv;track('level_'+lv);toast(`<b>Customer level ${lv}: ${LEVELS[lv-1].n}</b><br>New customers unlocked: ${LEVELS[lv-1].unlock}`,'goal');sfx('coin');}}
for(const l of S.links){if(l.kind!=='df')continue;
if(l.ready===d){toast(`<b>${l.own?'Your fiber is finished':'Dark fiber handed over'}: ${CITY[l.a].name}–${CITY[l.b].name}</b><br>${(l.ch||[]).length?'Channels are lighting up now.':'It is dark. Add optics to light it up.'}`,'goal',[{l:'Open',act:'selLink',args:{id:l.id}}]);sfx('coin');}
if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);l.ready+=extra;toast(`<b>Construction delay: +${extra} days</b><br>${pick(['Archaeologists found a Roman bathhouse on your route.','A protected hamster species lives along the right-of-way.','The railway changed its mind about the easement.','The drilling crew hit a granite boulder the size of a bus.','A town council wants a public hearing. About the color of the manhole covers.','Somebody else’s gas main was exactly where the map said it was not.','The permit office lost your permit. And then the replacement.'])} (${CITY[l.a].name}–${CITY[l.b].name})`,'bad');}}
// businesses mood
for(const b of S.biz.slice()){if(eventTick(b,d))continue;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99,scrubOk=b.type!=='scrub'||!!S.scrubAt,divOk=reqOk(b);
if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2);
else if(S.day-(b.since||0)<15){}
else{b.mood-=(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));
if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(`<b>${esc(b.name)} cancelled.</b><br>Too many outages and too little bandwidth in ${CITY[b.city].name}.`,'bad');sfx('err');}
else if(b.mood<30&&!b.warned){b.warned=true;toast(`<b>${esc(b.name)} is furious.</b><br>Fix service in ${CITY[b.city].name} or they leave.`,'bad',[{l:'Show me',act:'focusCity',args:{city:b.city}}]);}}
if(b.mood>60)b.warned=false;}
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<12){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
if(cands.length){cands.sort((a,b)=>(a.pol==='open'?0:1)-(b.pol==='open'?0:1)||b.share-a.share);const n=Math.random()<.6?cands[0]:pick(cands);m.members.push(n.id);toast(`<b>${esc(n.name)} joined ${esc(m.name)}!</b><br>Another member paying ${fmt$(MYIX_FEE)}/mo for a port.`,'good');sfx('coin');}
m.next=d+8+Math.floor(Math.random()*10);}}
loanTick(d);
// offers
S.offers=S.offers.filter(o=>o.exp>d);
if(S.offers.length<5&&Math.random()<0.05+0.01*(S.lvl||1))spawnOffer();
// failures & events
if(d>=S.nextFail){fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.max(22,50-size*1.5)+Math.floor(Math.random()*25);}
if(d>=S.nextEvent){fireEvent();S.nextEvent=d+45+Math.floor(Math.random()*45);}
compute();
// payday floaters
if(d%30===0){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-(CITY[c].arpu||1));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
checkGoals();
// money trouble
if(S.cash<0){S.neg++;if(S.neg===1)toast('<b>You are in the red.</b><br>Cancel something expensive, wait for revenue, or check the bank for a loan. At −$100k the bank takes your routers.','bad');}
else S.neg=0;
if(S.cash<-100000){S.lost=true;track('bankrupt');showLose();return;}
if(d%360===0&&[1,2,4].includes(d/360))track('game_year_'+(d/360+1),true);
if(d%10===0)save();
}
function spawnOffer(){
const mine=Object.keys(S.pops),lv=S.lvl||1;
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub');
if(lv>=2)types.push('isp','stream','edu','host','hft','bulk','event','event');if(mine.length>=3&&lv>=2)types.push('sdwan','sdwan');
if(S.links.some(l=>l.kind==='df'&&l.ready<=S.day))types.push('wwave','wwave');if(S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('dfpair');if(lv>=3)types.push('gpu','gpu','onramp','onramp');if(lv>=4)types.push('ai','ai','hyper','hyper');
const t=pick(types),T=BIZ_T[t];
if(T.event||T.sdwan||T.fiber){spawnSpecial(t);return;}
let city=(Math.random()<0.65&&mine.length)?pick(mine):pick(ALLC.concat(cnOk()?['pek','sha']:[])),city2=null;
if(T.l2){city=pick(mine);const pool=(Math.random()<(T.lv>=3?0.8:0.6)?mine:ALLC).filter(c=>c!==city);city2=pick(pool.length?pool:ALLC.filter(c=>c!==city));}
const bw=T.lv>=2?pick(T.opts):pick(T.opts.slice(0,mine.length>=4?4:3));
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));
let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999));
S.usedNames.push(name);
if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));}
const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate;
const reqs=T.div?['diverse']:T.lat?['lat']:[];const pool=Object.keys(REQS).filter(k=>!reqs.includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2));
if(Math.random()<(T.lv>=3?0.65:0.3))reqs.push(pick(pool));
if(T.lv>=3&&Math.random()<0.35){const more=pool.filter(k=>!reqs.includes(k));if(more.length)reqs.push(pick(more));}
const r2=Math.round(rate*(1+reqs.reduce((a,k)=>a+REQS[k].bonus,0)));
S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax:T.lat?+(kmBetween(city,city2)/200*1.35).toFixed(1):null,exp:S.day+40});
}
function checkGoals(){
for(const g of GOALS){if(S.done[g.id]!==undefined)continue;let ok=false;try{ok=g.ok();}catch(e){}
if(ok){S.done[g.id]=S.day;if(g.r){S.cash+=g.r;}
toast(`<b>Goal complete: ${esc(g.t)}</b>${g.r?`<br>Reward: +${fmt$(g.r)}`:''}`,'goal');sfx('coin');
track('goal_'+g.id);if(g.win&&!S.won){S.won=true;track('win_tier1');showWin();}}}
}
/* ================= ACTIONS ================= */
function spend(c){if(S.cash<c){toast('<b>Not enough cash.</b><br>Wait for revenue, or speed up time.','bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;}
const ACT={
speed:({v})=>{UI.speed=v;renderHUD();},
help:()=>showHelp(),
dash:()=>{if(!S)return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();},
dashClose:()=>{$('dash').hidden=true;},
bank:()=>{if(!S)return;$('dash').hidden=true;const b=$('bankBox');b.hidden=false;UI._bh=null;renderBank();},
bankClose:()=>{$('bankBox').hidden=true;},
takeLoan:({id})=>{const o=S.loanOffers.find(x=>x.id===id);if(!o)return;const B=BANKS[o.bank];let got=o.amount,note='';
if(B.crypto){const f=0.55+Math.random()*0.8;got=Math.round(o.amount*f);note=` TubeCoin moved ${f>=1?'up':'down'} ${Math.round(Math.abs(f-1)*100)}% on the way to your account.`;}
S.cash+=got;S.loanOffers=S.loanOffers.filter(x=>x!==o);
S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,bal:o.amount,apr:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,covs:o.covs,base:{sub:S.links.filter(x=>x.sub).length}});
track('loan_taken');toast(`<b>${fmt$(got)} from ${esc(B.name)} has landed.</b><br>${B.equity?`They now own ${pct(o.share)} of your revenue.`:`${fmt$(o.pay)}/mo for ${o.term} months.`}${note}`,'good');sfx('coin');after();renderBank();},
declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();},
repayLoan:({id})=>{const l=S.loans.find(x=>x.id===id);if(!l)return;const B=BANKS[l.bank];const cost=B.equity?Math.round(l.amount*3):Math.round(l.bal*1.02);
if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;if(!spend(cost)){renderBank();return;}S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');
toast(B.equity?`<b>You bought out ${esc(B.name)}.</b><br>They flew off to find another startup.`:`<b>Loan from ${esc(B.name)} repaid early.</b>`,'good');after();renderBank();},
dashLink:({id})=>{$('dash').hidden=true;UI.sel={type:'link',id};renderPanel();},
mute:()=>{UI.muted=!UI.muted;try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();},
closePanel:()=>{UI.sel=null;renderPanel();},
closeModal:()=>closeModal(),
tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();},
leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();},
toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();},
focusCity:({city})=>{selectCity(city);const C=CITY[city];cam.x=C.x;cam.y=C.y;cam.z=Math.max(cam.z,1.2);if(innerWidth<760)UI.leftOpen=false;renderLeft();},
selLink:({id})=>{UI.sel={type:'link',id};UI.confirm=null;renderPanel();},
buildPop:({city})=>{if(S.pops[city])return;if(cnCity(city)&&!cnOk()){toast('<b>You need a license first.</b><br>Foreign networks need a joint venture to build in mainland China.','bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};floater(CITY[city].x,CITY[city].y-30,'New POP!','#FF4F9A');UI.tab='cust';after();},
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:Math.max(8,C.P*0.03)};floater(C.x,C.y-30,'Eyeballs online!','#16A866');after();},
ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,'Ad campaign!','#FF8A3D');after();},
buyTransit:({city,net,tier})=>{tier=+tier;if(!S.pops[city]||!NET[net]||!NET[net].price||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0});toast(`<b>${esc(NET[net].name)} transit is live in ${CITY[city].name}.</b><br>Full table received: ~1,000,000 routes.`,'good');after();},
lagT:({id,d})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;toast(+d>0?`<b>LAG member added.</b><br>${esc(NET[t.net].name)} in ${CITY[t.city].name} is now ${lagName(t.tier,n)}.`:`<b>LAG member removed.</b>`,'good');after();},
lagP:({id,d})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&!spend(1500+PORT[p.tier].setup/2))return;p.n=n;sfx('build');after();},
lagIx:({city,d})=>{if(S.ixp[city]===undefined||S.myIx[city]||!S.pops[ixCity(city)])return;S.ixn=S.ixn||{};const n=(S.ixn[city]||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&!spend(ixPortMo(city,S.ixp[city])))return;S.ixn[city]=n;sfx('build');after();},
cancelTransit:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.transit=S.transit.filter(t=>t.id!==id);UI.confirm=null;after();},
buyIx:({city,tier})=>{tier=+tier;const cc=ixCity(city);if(!PORT[tier]||!ixName(city)||(!S.pops[cc]&&(!remoteCities().includes(cc)||tier>1))||(S.ixp[city]!==undefined&&tier<=S.ixp[city]))return;if(S.pops[cc]&&!portOk(cc,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const had=S.ixp[city]!==undefined;if(!spend(ixPortMo(city,tier)*(had?((S.ixn||{})[city]||1):1)))return;S.ixp[city]=tier;if(!had)toast(S.pops[cc]?`<b>Port up at ${esc(ixName(city))}!</b><br>Now request peering, or join the route server.`:`<b>Remote port up at ${esc(ixName(city))}.</b><br>It came through a reseller, so expect a markup, a crowded port and some networks that won't talk to you. The route server is your friend here.`,'good');after();},
cancelIx:({city})=>{if(UI.confirm!=='ix'+city){UI.confirm='ix'+city;renderPanel();return;}delete S.ixp[city];delete S.rs[city];if(S.ixn)delete S.ixn[city];for(const k in S.peers)if(k.endsWith('@'+city))delete S.peers[k];UI.confirm=null;after();},
rs:({city})=>{S.rs[city]=!S.rs[city];if(S.rs[city])toast('<b>Route server session up.</b><br>You now peer with every open network on this IX, in one go.','good');sfx('build');after();},
peer:({city,net})=>{const r=peerOk(net,'ix',city);if(!r.ok){toast(`<b>${esc(NET[net].name)} declined.</b><br>${esc(r.why)}`,'bad');sfx('err');return;}S.peers[net+'@'+city]=true;
toast(`<b>${esc(NET[net].name)} accepted!</b><br>${NET[net].pol==='selective'?'They checked your PearingDB page and liked the traffic numbers.':'BGP session established.'}`,'good');sfx('build');after();},
unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();},
pni:({city,net,tier})=>{tier=+tier;if(!S.pops[city]||!NET[net]||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const r=peerOk(net,'pni',city);if(!r.ok){toast(`<b>${esc(NET[net].name)} declined the PNI.</b><br>${esc(r.why)}`,'bad');sfx('err');return;}
const ex=S.pni.find(p=>p.city===city&&p.net===net);if(ex&&tier<=ex.tier)return;if(!spend((1500+PORT[tier].setup/2)*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.pni.push({id:uid(),city,net,tier});
toast(`<b>PNI with ${esc(NET[net].name)} is up.</b><br>A cross-connect in ${esc(CITY[city].dc)}. Private and fast.`,'good');after();},
cancelPni:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.pni=S.pni.filter(p=>p.id!==id);UI.confirm=null;after();},
cache:({city,net})=>{const n=NET[net];if(!n||!n.cache||!S.pops[city]||S.caches.filter(x=>x.city===city&&x.net===net).length>=4)return;if((R.demTo[net]||0)<n.cache.min){toast(`<b>${esc(n.name)} says not yet.</b><br>Send them ${n.cache.min}+ Gbps first.`,'bad');sfx('err');return;}
S.caches.push({id:uid(),city,net});toast(`<b>${esc(n.cache.name)} installed in ${CITY[city].name}!</b><br>${esc(n.name)} shipped it for free. You pay ${fmt$(CACHE_MO)}/mo power.`,'good');sfx('build');after();},
rmCache:({id})=>{S.caches=S.caches.filter(c=>c.id!==id);after();},
accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast('<b>You need a POP in every city on the contract first.</b>','bad');return;}
if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||DF_SYS[l.sys].max-(l.ch||[]).length-soldSlots(l)<o.slots){toast('<b>Not enough free channels on that fiber any more.</b>','bad');return;}}
if(BIZ_T[o.type].event&&S.day>=o.start){toast('<b>Too late: the event has already started.</b>','bad');return;}
S.offers=S.offers.filter(x=>x!==o);S.biz.push({id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what});
floater(CITY[o.city].x,CITY[o.city].y-30,'Signed!','#16A866');sfx('coin');after();},
decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();},
dropBiz:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();},
upLink:({id,tier})=>{tier=+tier;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='wave'||!LT[tier]||tier<=l.tier)return;if(!waveOk(l.a,l.b,tier)){toast(`<b>A ${LT[tier].n} wave needs ${esc(waveNeed(tier))} routers at both ends.</b>`,'bad');sfx('err');return;}const nm=Math.round(waveMo(l.km,l.sub,tier)*(l.mult||1));if(!spend(nm))return;l.mo=nm;l.tier=tier;after();},
rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);UI.sel=null;UI.confirm=null;after();},
fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i)return;if(!spend(i.cost))return;clearInc(i);toast(`<b>Fixed.</b> ${incTitle(i.type)} resolved early.`,'good');after();},
foundIx:({city})=>{if(!S.pops[city]||S.myIx[city]||CITY[city].ix||CITY[city].cn)return;if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;
S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(`<b>You founded ${esc(nm)}!</b><br>Networks will join over time and pay you for ports. Open members peer with you for free.`,'goal');after();},
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p)return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),same=sib.length>0&&UI.route==='same',border=cnCity(a)!==cnCity(b),mult=(sib.length&&!same?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if((cnCity(a)||cnCity(b))&&!cnOk())return;
if(!waveOk(a,b,tier)){toast(`<b>A ${LT[tier].n} wave needs ${esc(waveNeed(tier))} routers at both ends.</b>`,'bad');sfx('err');return;}
const wr=waveRoute(a,b,mult,border);if(!wr)return;const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b));
if(!spend(cost))return;if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};
const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(same?(sib[0].trench||sib[0].id):id),cut:0,day:S.day};S.links.push(l);closeModal();
if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';}
floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,`${LT[tier].n} lit!`,'#FF4F9A');after();},
buyNni:({city,prov,tier})=>{tier=+tier;const ex=nniPort(city,prov);if(ex&&nniUsed(city,prov)>NNI[tier].g){toast('<b>Too many circuits</b> for a smaller port.','bad');return;}if(!spend(NNI[tier].mo))return;if(ex)ex.tier=tier;else S.nni.push({id:uid(),city,prov,tier});toast(`<b>${esc(FAB[prov].name)} port is up in ${CITY[city].name}.</b><br>Now order virtual circuits to other cities on their fabric.`,'good');after();},
rmNni:({city,prov})=>{if(nniUsed(city,prov)>0){toast('<b>Cancel the circuits on this port first.</b>','bad');sfx('err');return;}S.nni=S.nni.filter(x=>!(x.city===city&&x.prov===prov));after();},
openVxc:(a)=>openVxcModal(a),
buyVxc:({a,b,prov,t})=>{t=+t;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>NNI[pa.tier].g){toast('<b>Not enough room on your fabric port.</b> Upgrade it first.','bad');sfx('err');return;}
if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>NNI[pb.tier].g){toast(`<b>Not enough room on your ${esc(FAB[prov].name)} port in ${CITY[b].name}.</b>`,'bad');sfx('err');return;}}
const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal();
toast(`<b>Circuit up in 59 seconds.</b><br>${VXC[t].n} over ${esc(FAB[prov].name)}: ${CITY[a].name} → ${CITY[b].name}.${S.pops[b]?'':' Now grab an IX port there for remote peering.'}`,'good');if(!S.pops[b])selectCity(b);after();},
upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(`<b>Fabric port in ${CITY[c].name} is full.</b>`,'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();},
cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();},
setPref:({kind,id,v})=>{if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();},
setMetric:({id,v})=>{const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();},
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':'peer';renderPanel();},
applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+45};toast('<b>Application filed.</b><br>Your local partner says about 45 days. Probably.','goal');after();},
togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.premium=!t.premium;sfx('click');after();},
scrub:({city})=>{if(S.scrubAt){if(UI.confirm!=='scrub'){UI.confirm='scrub';renderAll();return;}S.scrubAt=null;UI.confirm=null;after();return;}if(!spend(SCRUB_COST))return;S.scrubAt=city;toast(`<b>Scrubbing center online in ${CITY[city].name}.</b><br>DDoS attacks are now absorbed, and you can sell DDoS protection to businesses.`,'good');after();},
cnPrem:({v})=>{UI.cnPrem=!!+v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
via:({v})=>{UI.via=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
setRoute:({id,m})=>{const b=S.biz.find(x=>x.id===id);if(b){b.route=m;sfx('click');after();}},
route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);},
addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=4)return;if(!spend(routerCost(p.rgen||0)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,'Router added','#FF4F9A');after();},
rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;p.routers--;after();},
upRouter:({city})=>{const p=S.pops[city];if(!p)return;const g=(p.rgen||0)+1;if(!RG[g])return;if(RG[g].lvl>lvl()){toast(`<b>${esc(RG[g].n)} unlocks at customer level ${RG[g].lvl}.</b>`,'bad');sfx('err');return;}
const rt=p.routers||1;if(!spend(RG[g].cost*rt))return;p.rgen=g;
if(rt===1){p.down=Math.max(p.down||0,S.day+1);addInc({type:'maint',ref:city,until:S.day+1,msg:`Swapping the only router in ${CITY[city].name} for a ${RG[g].n}. Maintenance window: back tomorrow.`,cost:0});toast(`<b>Maintenance window in ${CITY[city].name}</b><br>One router means downtime during the swap. Back tomorrow.`,'bad');}
else toast(`<b>Rolling upgrade in ${CITY[city].name}</b><br>${rt} × ${esc(RG[g].n)}, swapped one at a time. Zero downtime.`,'good');
floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');after();},
dfMode:({m})=>{UI.lmode=m;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
dfSrc:({v})=>{UI.dfSrc=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
dfSys:({v})=>{UI.dfSys=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
orderDf:()=>{const p=UI.pending;if(!p)return;const {a,b}=p,km=kmBetween(a,b);if(isSub(a,b)||!dfAllowed(a,b))return;
const own=UI.dfSrc==='build'&&lvl()>=3,sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite';if(lvl()<2)return;
const up=(own?dfBuildCost(km):0)+DF_SYS[sys].cost+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return;
if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};
const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid();
const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:false,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):30),spares:false};
S.links.push(l);closeModal();UI.sel={type:'link',id};
toast(own?`<b>Groundbreaking!</b><br>Your own fiber from ${CITY[a].name} to ${CITY[b].name}. Permits and digging take about ${dfBuildDays(km)} days.`:`<b>Dark fiber IRU signed.</b><br>${CITY[a].name}–${CITY[b].name} will be spliced and handed over in about 30 days.`,'goal');after();},
addCh:({id,o})=>{const l=S.links.find(x=>x.id===id),O=OPT[o];if(!l||!O||l.kind!=='df')return;const why=chWhy(l,o);if(why){toast(`<b>Can't add ${O.n}.</b><br>${esc(why)}`,'bad');sfx('err');return;}if(!spend(optCost(o)))return;(l.ch=l.ch||[]).push(o);floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,`+${O.n}`,'#FF4F9A');after();},
rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l)return;const i=(l.ch||[]).lastIndexOf(o);if(i>=0)l.ch.splice(i,1);after();},
upSys:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.sys==='roadm'||lvl()<3)return;if(!spend(DF_SYS.roadm.cost))return;l.sys='roadm';if(l.ready<=S.day){l.eqDown=S.day+1;toast('<b>Line system swap</b><br>All channels are dark for a day while the ROADMs go in.','bad');}after();},
spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();},
crews:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.ready<=S.day)return;const c=Math.round(15000+l.km*6);if(!spend(c))return;l.ready=Math.max(S.day+1,l.ready-30);toast('<b>More crews on site.</b><br>Construction is 30 days ahead.','good');after();},
addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,'Generator!','#FF8A3D');after();},
start:()=>{const nm=(document.getElementById('nmIn').value||'Packet Pals').slice(0,24);newGame(nm,UI.startCity);track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[UI.startCity].x;cam.y=CITY[UI.startCity].y;cam.z=innerWidth<760?1.1:1.4;selectCity(UI.startCity);
toast(`<b>Welcome, ${esc(nm)}!</b><br>The RIPE-ish NCC assigned you AS${S.asn}. Your first router is humming in ${CITY[UI.startCity].name}.`,'goal');renderAll();save();},
pickStart:({city})=>{UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city));},
cont:()=>{migrate(S);track('game_continue',true);UI.started=true;closeModal();renderAll();},
newgame:()=>{try{localStorage.removeItem('sot-save-v1');}catch(e){}S=null;UI.started=false;UI.sel=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();},
keepPlaying:()=>{closeModal();},
resetAsk:()=>openModal(`<h2 style="font-size:26px">Start a new network?</h2><p class="tagline">${esc(S?S.name:'Your network')} and everything it owns will be deleted. This cannot be undone.</p><div class="btns">${btn('Delete and start over','newgame',{},'red big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`),
whatsNewShow:()=>whatsNew(true,true),
updateNow:()=>{save();location.reload();},
updateLater:()=>{$('update').hidden=true;UI.updLater=Date.now();},
helpClose:()=>{if(UI.started)closeModal();else showTitle();},
};
function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));}
function dfAllowed(a,b){return !isSub(a,b)&&cnCity(a)===cnCity(b);}
function optCost(o){return Math.round(OPT[o].cost*(S&&S.ev&&S.ev.tariff>S.day?1.4:1));}
function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return `Unlocks at customer level ${O.lvl}.`;if(O.sys==='roadm'&&l.sys!=='roadm')return 'Needs a ROADMaster 9000 line system.';if(l.km>O.reach)return `Reach is ${O.reach.toLocaleString()} km; this route is ${l.km.toLocaleString()} km.`;
if((l.ch||[]).length+soldSlots(l)>=DF_SYS[l.sys].max)return `${DF_SYS[l.sys].n} is full (${DF_SYS[l.sys].max} channels${soldSlots(l)?`, ${soldSlots(l)} sold to customers`:''}).`;
for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&(p.rgen||0)<O.rg)return `Needs ${RG[O.rg].n} routers at both ends (${CITY[c].name}).`;}return '';}
function bbCost(c){return 15000+CITY[c].P*20;}
function after(){if(S)purgeInc();compute();checkGoals();renderAll();save();}
function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(!S.pops[c])UI.tab='cust';renderPanel();}
/* ================= SAVE ================= */
function save(){if(!S||S.lost)return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};try{localStorage.setItem('sot-save-v1',JSON.stringify(S));}catch(e){}UI.lastSave=performance.now();}
// Save whenever the player might be leaving: tab hidden, page closing or reloading.
addEventListener('pagehide',()=>save());
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save();else checkUpdate();});
function loadSave(){try{const t=localStorage.getItem('sot-save-v1');if(t){const s=JSON.parse(t);if(s&&s.v===1&&!s.lost)return s;}}catch(e){}return null;}
/* ================= AUDIO ================= */
let AC=null;
function audioInit(){if(AC)return;try{AC=new (window.AudioContext||window.webkitAudioContext)();}catch(e){}}
function tone(f,t0,dur,type='square',vol=.05){if(!AC)return;const o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.value=f;g.gain.setValueAtTime(vol,AC.currentTime+t0);g.gain.exponentialRampToValueAtTime(.0001,AC.currentTime+t0+dur);o.connect(g).connect(AC.destination);o.start(AC.currentTime+t0);o.stop(AC.currentTime+t0+dur+.02);}
function sfx(k){if(UI.muted||!AC)return;try{
if(k==='coin'){tone(988,0,.08);tone(1319,.08,.18);}
else if(k==='build'){tone(523,0,.07,'triangle',.08);tone(784,.06,.12,'triangle',.08);}
else if(k==='err'){tone(180,0,.18,'sawtooth',.04);}
else if(k==='alert'){tone(880,0,.1,'square',.04);tone(660,.12,.1,'square',.04);tone(880,.24,.12,'square',.04);}
else if(k==='click'){tone(660,0,.04,'triangle',.05);}
}catch(e){}}
/* ================= DOM RENDER ================= */
const $=id=>document.getElementById(id);
const btn=(label,act,args={},cls='',dis=false,title='')=>`<button class="b ${cls}" data-act="${act}" data-args='${JSON.stringify(args)}'${dis?' disabled':''}${title?` title="${esc(title)}"`:''}>${label}</button>`;
const logo=n=>`<span class="logo" style="--c:${n.col}">${initials(n)}</span>`;
const barCls=u=>u>=0.9?'bad':u>=0.65?'warn':'';
function renderAll(){renderHUD();renderLeft();renderPanel();renderHint();}
function renderHUD(){
for(const v of [0,1,2,4,8]){const b=$('sp'+v);if(b)b.classList.toggle('on',UI.speed===v);}
$('muteBtn').style.opacity=UI.muted?.4:1;
if(!S)return;
$('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn;
$('hCash').textContent=fmt$(S.cash);$('hCash').style.color=S.cash<0?'var(--bad)':'';
const net=R.revMo-R.costMo;$('hRate').innerHTML=`<span class="${net>=0?'up':'down'}">${net>=0?'▲':'▼'} ${fmt$(Math.abs(net))}/mo</span>`;
$('hTraffic').textContent=`${fmtG(R.served)}`;
$('hTrafBar').style.width=(R.demand?R.served/R.demand*100:0)+'%';
$('hTrafBar').style.background=R.demand&&R.served/R.demand<0.9?'var(--bad)':'var(--ok)';
$('hReach').textContent=pct(R.reach);$('hReach').style.color=R.reach<0.99?'var(--bad)':'var(--eye)';
$('hTier').textContent=tierLabel();
$('hDate').textContent=dateStr(S.day);
{const bo=(S.loanOffers||[]).length,hb=$('hBank');hb.hidden=!bo;hb.textContent=bo;}
const n=S.inc.length;$('hNoc').classList.toggle('hot',n>0);$('hNocVal').textContent=n?`${n} incident${n>1?'s':''}`:'All quiet';
}
function renderLeft(){
const L=$('left');L.classList.toggle('closed',!UI.leftOpen);
if(!S){L.hidden=true;return;}L.hidden=false;
const ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length;
const tabs=[['goals',`Goals<span class="cnt">${ndone}/${GOALS.length}</span>`],['deals',`Deals${S.offers.length?`<span class="cnt">${S.offers.length}</span>`:''}`],['noc',`NOC${S.inc.length?`<span class="cnt red">${S.inc.length}</span>`:''}`],['nets','Networks']];
$('leftTabs').innerHTML=tabs.map(([k,l])=>`<button class="${UI.left===k?'on':''}" data-act="leftTab" data-args='{"t":"${k}"}'>${l}</button>`).join('')+(innerWidth<760?`<button data-act="toggleLeft" style="margin-left:auto" aria-label="Close">×</button>`:'');
let h='';
if(UI.left==='goals'){
const cur=GOALS.find(g=>S.done[g.id]===undefined);
h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `<div class="goal ${d?'done':''} ${c?'cur':''}"><div class="ck">${d?'✓':''}</div><div><div class="gt">${esc(g.t)}</div>${c||!d?`<div class="gd">${esc(g.d)}</div>`:''}${!d&&g.r?`<div class="gr">Reward ${fmt$(g.r)}</div>`:''}</div></div>`;}).join('');
}else if(UI.left==='deals'){
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:#FFF6CF"><div class="nm">Customer level ${lv}: ${LEVELS[lv-1].n}</div><div class="meta">${nx?`Next: ${nx.req} unlocks ${nx.unlock.toLowerCase()}`:'Every customer type is unlocked. Go get those terabits.'}</div></div>`;}
if(!S.offers.length)h+=`<p class="empty">No open offers right now. Businesses look for networks with POPs in their city. New ones pop up every few weeks.</p>`;
for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o);
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${o.exp-S.day}d left${(o.reqs||[]).length?` · ${o.reqs.length} special requirement${o.reqs.length>1?'s':''}`:''}</div>${reqList(o)}
<div class="btns">${has?btn('Accept','accept',{id:o.id},'green sm'):btn('Go there','focusCity',{city:o.city},'ghost sm')}${btn('Decline','decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">Needs a POP in ${bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')}</div>`}</div></div>`;}
}else if(UI.left==='noc'){
h+=`<div class="btns" style="margin-bottom:8px">${btn('Open NOC dashboard','dash',{},'pink')}</div>`;
h+=`<p class="lead">Your Network Operations Center. Every notification also lands here. Things fail all the time on the internet. Redundant links and multiple upstreams let traffic reroute by itself.</p>`;
h+=`<div class="kv"><span>DDoS scrubbing</span><b>${S.scrubAt?'On · '+CITY[S.scrubAt].name:'None (build one from a POP\'s Infra tab)'}</b></div>`;
const hot=S.links.filter(l=>!linkDown(l)&&capOf(l)>0&&(R.load[l.id]||0)/capOf(l)>=0.85).sort((a,b)=>(R.load[b.id]/capOf(b))-(R.load[a.id]/capOf(a)));
if(hot.length){h+=`<h3 style="font-size:15px;margin:4px 0">Congested links</h3>`+hot.map(l=>`<div class="row"><div class="grow"><div class="nm">${CITY[l.a].name} ⇄ ${CITY[l.b].name}</div><div class="meta">${capName(l)} · ${pct((R.load[l.id]||0)/capOf(l))} full</div></div>${btn('Inspect','selLink',{id:l.id},'pink sm')}</div>`).join('');}
const hotR=Object.keys(S.pops).filter(c=>(R.nodeLoad[c]||0)>=(R.nodeCap[c]||1e12)*0.9);
if(hotR.length)h+=`<h3 style="font-size:15px;margin:4px 0">Routers running hot</h3>`+hotR.map(c=>`<div class="row"><div class="grow"><div class="nm">${CITY[c].name}</div><div class="meta">${fmtG(R.nodeLoad[c])} of ${fmtG(R.nodeCap[c])}</div></div>${btn('Inspect','focusCity',{city:c},'pink sm')}</div>`).join('');
if(!S.inc.length&&!hot.length&&!hotR.length)h+=`<p class="empty">All systems green. Enjoy it while it lasts.</p>`;
for(const i of S.inc){h+=`<div class="inc"><div class="nm">${incTitle(i.type)}</div><div class="meta">${esc(i.msg)}</div><div class="meta">Auto-fix in ${i.until-S.day} day${i.until-S.day===1?'':'s'}${i.impact?` · ${fmtG(i.impact)} lost`:''}</div>${i.cost?`<div class="btns">${btn(`${i.fix||'Rush repair'} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash<i.cost)}</div>`:''}</div>`;}
if(S.log&&S.log.length){h+=`<h3 style="font-size:15px;margin:12px 0 4px">Recent events</h3>`+S.log.slice(0,15).map(e=>`<div class="row"><div class="grow"><div class="meta"><b class="tag ${e.k==='bad'?'restrictive':e.k==='good'?'open':'st'}">${dateStr(e.d)}</b> ${esc(e.t)}</div></div></div>`).join('');}
h+=`<div class="kv" style="margin-top:8px"><span>Incidents so far</span><b>${S.stats.incidents}</b></div><div class="kv"><span>Survived with no impact</span><b>${S.stats.survived}</b></div>`;
}else{
h+=`<p class="lead">Every network on the map. Traffic share is how much of your users' traffic goes to them.</p>`;
for(const n of NETS){const st=[];if(S.transit.some(t=>t.net===n.id))st.push('Transit');if(Object.keys(S.ixp).some(c=>ixSessions(c).has(n.id)))st.push('Peered');if(S.pni.some(p=>p.net===n.id))st.push('PNI');if(S.caches.some(c=>c.net===n.id))st.push('Cache');
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="meta">AS${n.asn}</span></div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${(NSH[n.id]*100).toFixed(1)}% of traffic${n.price?` · transit $${(n.price*S.priceMul).toFixed(2)}/Gbps`:''}</div><div class="meta">${esc(n.blurb)}</div>${st.length?`<div class="btns">${st.map(s=>`<span class="tag st on">${s}</span>`).join('')}</div>`:''}</div></div>`;}
}
if(h!==UI._lh){UI._lh=h;$('leftBody').innerHTML=h;}
}
function renderPanel(){
const P=$('panel');
if(!S||!UI.sel){P.hidden=true;return;}
P.hidden=false;
const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0;
const html=UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;$('panelBody').innerHTML=html;
const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st;
}
function cityPanel(c){
const C=CITY[c],p=S.pops[c],ix=ixName(c),down=p&&p.down>S.day;
let h=`<div class="ph"><div style="min-width:0"><div class="eyebrow">${REG[C.reg]} · ${esc(C.dc)}</div><h2>${C.name}</h2>
<div class="facts"><span class="fact">${fmtG(C.P)} of eyeballs</span>${regionMult(c)>1?`<span class="fact">Transit ${regionMult(c)}× pricier</span>`:''}${C.reg==='AS'&&!C.cn?'<span class="fact ixf">Underserved: users grow 60% faster</span>':''}${ix?`<span class="fact ixf">IX: <b>${cityIxes(c).map(k=>esc(ixName(k))).join(' + ')}</b></span>`:''}${p?`<span class="fact mine">Your POP</span>`:''}${down?`<span class="fact down">DOWN</span>`:''}</div></div>
<button class="x" data-act="closePanel" aria-label="Close">×</button></div>`;
if(!p){
h+=`<div class="scroll">${C.note?`<p class="note" style="margin-top:0">${esc(C.note)}</p>`:''}
${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`<section><h3>Open a POP here</h3><p class="lead">A POP (point of presence) is your router in a rack here. Then connect it: lay fiber from one of your POPs, or buy transit right here.</p>
${C.ru?`<p class="why">Includes the mandatory government box in your rack: ${fmt$(RU_BOX)} + ${fmt$(RU_BOX_MO)}/mo. It comes with its own listener.</p>`:''}${btn(`Build POP <small>${fmt$(popCost(c))} + ${fmt$(POP_MO)}/mo</small>`,'buildPop',{city:c},'pink big',S.cash<popCost(c))}
<p class="note">Or drag from one of your routers to this city to lay fiber and build the POP in one go.</p></section>`}`;
h+=offersHere(c);
const tr=NETS.filter(n=>n.price&&n.pops.includes(c));
const fh=FABS.filter(f=>f.cities.includes(c));
if(ix&&fh.length){if(remoteCities().includes(c))h+=ixSection(c).replaceAll('<h3>Internet Exchange','<h3>Remote peering at the IX');
else h+=`<section><h3>Remote peering</h3><p class="lead">Peer at ${cityIxes(c).map(k=>esc(ixName(k))).join(' or ')} without building a POP. Order a virtual circuit here from one of your POPs over ${fh.map(f=>esc(f.name)).join(' or ')}.</p>${REMOTE_WARN}${btn('Order circuit anyway','openVxc',{to:c},'ghost sm')}</section>`;}
h+=`<section><h3>Who's here</h3><div class="meta" style="font-size:12.5px;line-height:1.6">Transit sellers: ${tr.map(n=>`<b>${esc(n.name)}</b>`).join(', ')||'none'}<br>Fabrics: ${fh.map(f=>`<b>${esc(f.name)}</b>`).join(', ')||'none'}<br>${ix?cityIxes(c).map(k=>`IX members on ${esc(ixName(k))}: ${ixMembers(k).length}`).join('<br>'):'No IX here yet. You could found one later.'}</div></section></div>`;
return h;
}
const tabs=[['cust','Customers'],['up','Transit'],['peer','Peering'],['links','Infra']];
h+=`<nav class="tabs">${tabs.map(([k,l])=>`<button class="${UI.tab===k?'on':''}" data-act="tab" data-args='{"t":"${k}"}'>${l}</button>`).join('')}</nav><div class="scroll">`;
if(C.cn&&UI.tab==='cust')h+=chinaSection(c);
const sf=sfOf(R,c),dem=R.cityDem[c]||0;
if(down){const i=S.inc.filter(x=>x.ref===c&&POPDOWN.includes(x.type)).sort((a,b)=>b.until-a.until)[0];h+=`<section><h3 style="color:var(--bad)">This POP is down</h3><p class="lead">${i?esc(i.msg):''} Customers here get nothing until it's back.</p>${i&&i.cost?btn(`${i.fix} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red'):''}</section>`;}
if(UI.tab==='cust'){
{const nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||1;if(nl>=nc*0.95)h+=`<section><h3 style="color:var(--bad)">Router maxed out</h3><p class="lead">Your routers here are forwarding ${fmtG(nl)} of ${fmtG(nc)}. Traffic is being dropped. Upgrade or add a router in the Infra tab.</p>${btn('Open Infra','tab',{t:'links'},'pink sm')}</section>`;}
h+=`<section><h3>Home broadband</h3>`;
if(!p.bb){const s=Math.max(8,C.P*0.03);h+=`<p class="lead">Sell internet to homes here. Starts around ${fmtG(s)} and grows toward ${fmtG(C.P)} while service is good. Pays ${fmt$(EYE_RATE)} per Gbps served, every month.</p>${btn(`Launch broadband <small>${fmt$(bbCost(c))}</small>`,'launchBB',{city:c},'pink big',S.cash<bbCost(c))}`;}
else{const eye=R.cityEye[c]||0;
h+=`<div class="kv"><span>Eyeball demand</span><b>${fmtG(eye)} of ${fmtG(C.P)}</b></div><div class="bar me"><i style="width:${eye/C.P*100}%"></i></div>
<div class="kv"><span>Served in ${C.name}</span><b style="color:${sf<0.9?'var(--bad)':'var(--eye)'}">${pct(sf)}</b></div><div class="bar ${sf<0.9?'bad':''}"><i style="width:${sf*100}%"></i></div>
<div class="kv"><span>Revenue</span><b>${fmt$(eye*sf*EYE_RATE)}/mo</b></div>
<div class="kv"><span>Network-wide peering ratio</span><b>${pct(R.peerShare||0)}</b></div><p class="note">More traffic over peering, PNIs and caches means lower latency, and happier users grow faster.</p>
${sf<0.9?`<p class="why">Customers are unhappy and leaving. Add upstream capacity, peering, or a bigger link.</p>`:''}
<div class="btns">${p.boost>S.day?`<span class="tag st on">Ad campaign: ${p.boost-S.day}d left</span>`:btn('Run ad campaign <small>$8k · 2× growth 30d</small>','ad',{city:c},'',S.cash<8000)}</div>`;}
h+=`</section><section><h3>Business customers</h3>`;
const bz=S.biz.filter(b=>bCities(b).includes(c));
if(!bz.length)h+=`<p class="empty">No businesses yet. Offers pop up as $ bubbles on the map.</p>`;
for(const b of bz)h+=`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · carrying ${fmtG(R.l2[b.id]||0)}${b.sites?' per site':''}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · <b style="color:var(--bad)">fiber is down</b>':''}${BIZ_T[b.type].event&&eventLive(b)?` · <b>serving ${pct(sfOf(R,b.city))}</b>`:''}${b.type==='scrub'&&!S.scrubAt?' · <b style="color:var(--bad)">needs a scrubbing center</b>':''}${S.day-(b.since||0)<15?` · <b>provisioning, ${15-(S.day-(b.since||0))}d grace</b>`:''}</div>${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}<div class="bar ${b.mood<30?'bad':b.mood<65?'warn':''}"><i style="width:${b.mood}%"></i></div><div class="meta">Happiness ${Math.round(b.mood)}%</div></div>${btn(UI.confirm===b.id?'Really drop?':'Drop','dropBiz',{id:b.id},'ghost sm')}</div>`;
h+=`</section>`+offersHere(c);
}else if(UI.tab==='up'){
h+=portNote(c);
h+=`<section><h3>IP transit</h3><p class="lead">Pay a bigger network per Gbps and it carries your traffic to the whole internet. Billed on the 95th percentile of the last 30 days, with a 20% commit and a port fee. Spikes like DDoS raise your bill.</p>`;
const prov=NETS.filter(n=>n.price&&n.pops.includes(c)).sort((a,b)=>a.price-b.price);
if(!prov.length)h+=`<p class="empty">Nobody sells transit here. Haul your traffic over fiber to a city that has it.</p>`;
for(const n of prov){const t=S.transit.find(x=>x.city===c&&x.net===n.id);const pr=n.price*S.priceMul*(t&&t.premium&&c==='hkg'?n.premium:1)*regionMult(c);
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="tag ${n.type}">${TYPE_L[n.type]}</span></div><div class="meta">$${pr.toFixed(2)} per Gbps / month · billed on 95th percentile</div>`;
if(t){const u=R.useT[t.id]||0,cap=lagCap(PORT[t.tier].g,t.n),tdown=t.down>S.day;
h+=`<div class="kv"><span>${lagName(t.tier,t.n)}${tdown?' · <b style="color:var(--bad)">OUTAGE</b>':''}</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('t',t.id,t.pref)}${n.premium&&c==='hkg'?`<div class="btns">${btn(t.premium?'CN-Too premium on ✓':`Switch to CN-Too premium <small>${n.premium}× price · ~3% loss into China</small>`,'togglePrem',{id:t.id},t.premium?'green sm':'sm')}</div>`:''}<div class="meta">95th pct ${fmtG(R.p95[t.id]||0)} · commit ${fmtG(cap*.2)} · bill ${fmt$(Math.max(R.p95[t.id]||0,PORT[t.tier].g*(t.n||1)*.2)*pr+PORT[t.tier].tmo*(t.n||1))}/mo</div>
<div class="btns">${PORT.map((P2,i)=>i>t.tier?btn(`Upgrade ${(t.n||1)>1?'all to ':''}${P2.n} <small>${fmt$(P2.setup*(t.n||1))} + ${fmt$(P2.tmo*(t.n||1))}/mo</small>`,'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup*(t.n||1)||!portOk(c,i)):'').join('')}${(t.n||1)<LAG_MAX?btn(`+ LAG member <small>${fmt$(PORT[t.tier].setup)} + ${fmt$(PORT[t.tier].tmo)}/mo</small>`,'lagT',{id:t.id,d:1},'sm',S.cash<PORT[t.tier].setup||!portOk(c,t.tier)):''}${(t.n||1)>1?btn('− member','lagT',{id:t.id,d:-1},'ghost sm'):''}${btn(UI.confirm===t.id?'Really cancel?':'Cancel','cancelTransit',{id:t.id},'ghost sm')}</div>`;}
else h+=`<div class="btns">${PORT.map((P2,i)=>btn(`${P2.n} <small>${fmt$(P2.setup)} + ${fmt$(P2.tmo)}/mo</small>`,'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup||!portOk(c,i))).join('')}</div>`;
h+=`</div></div>`;}
h+=`</section>`;
}else if(UI.tab==='peer'){
h+=portNote(c);
h+=ixSection(c);
h+=`<section><h3>Private interconnects (PNI)</h3><p class="lead">A dedicated cross-connect to one network in ${esc(C.dc)}. Needs more traffic than IX peering, but has its own capacity.</p>`;
const here=NETS.filter(n=>n.pops.includes(c));
for(const n of here){const pn=S.pni.find(x=>x.city===c&&x.net===n.id),chk=peerOk(n.id,'pni',c);
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="tag ${n.pol}">${n.pol}</span></div>`;
if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(PORT[pn.tier].g,pn.n);h+=`<div class="kv"><span>${(pn.n||1)>1?`${pn.n}×${PORT[pn.tier].n} LAG`:PORT[pn.tier].n} PNI</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('p',pn.id,pn.pref)}<div class="btns">${PORT.map((P2,i)=>i>pn.tier?btn(`Upgrade ${(pn.n||1)>1?'all to ':''}${P2.n}`,'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)):'').join('')}${(pn.n||1)<LAG_MAX?btn(`+ LAG member <small>${fmt$(1500+PORT[pn.tier].setup/2)} + ${fmt$(PORT[pn.tier].pni)}/mo</small>`,'lagP',{id:pn.id,d:1},'sm',S.cash<1500+PORT[pn.tier].setup/2):''}${(pn.n||1)>1?btn('− member','lagP',{id:pn.id,d:-1},'ghost sm'):''}${btn(UI.confirm===pn.id?'Really remove?':'Remove','cancelPni',{id:pn.id},'ghost sm')}</div>`;}
else{h+=chk.ok?`<div class="btns">${PORT.map((P2,i)=>btn(`${P2.n} <small>${fmt$(1500+P2.setup/2)}</small>`,'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i))).join('')}</div>${chk.fee?`<div class="meta">Paid peering: ${fmt$(chk.fee)}/mo on top</div>`:''}`:`<div class="why">${esc(chk.why)}</div>`;}
h+=`</div></div>`;}
h+=`</section><section><h3>Embedded caches</h3><p class="lead">CDNs put free cache servers inside your POP. Most of their traffic is then served right here, with no transit and no IX port.</p>`;
for(const n of NETS.filter(n=>n.cache)){const have=S.caches.filter(x=>x.city===c&&x.net===n.id),dem=R.demTo[n.id]||0,ok=dem>=n.cache.min;
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.cache.name)}</div><div class="meta">from ${esc(n.name)} · ${have.length?`${have.length} box${have.length>1?'es':''} · serving ${fmtG(have.reduce((a,x)=>a+(R.useCache[x.id]||0),0))}`:`100G per box`}</div>${!ok?`<div class="why">Needs ${n.cache.min} Gbps of traffic to ${esc(n.name)} (now ${dem.toFixed(1)})</div>`:''}</div>
${have.length?btn('Remove','rmCache',{id:have[0].id},'ghost sm'):''}${have.length<4?btn(have.length?'+ box':'Request','cache',{city:c,net:n.id},'sm',!ok):''}</div>`;}
h+=`</section>`;
}else{
const ls=S.links.filter(l=>l.a===c||l.b===c);
const rt=p.routers||1,g=p.rgen||0,G=RG[g],nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c),N=RG[g+1];
h+=`<section><h3>Routers</h3><p class="lead">The model sets your fastest interface and how much this POP can forward. More routers add capacity and survive crashes.</p>
<div class="row"><span class="logo" style="--c:#FF4F9A">R${g+1}</span><div class="grow"><div class="nm">${rt} × ${esc(G.n)}</div><div class="meta">Up to ${G.pn} interfaces · ${fmtG(G.cap)} per router · ${esc(G.blurb)}</div></div></div>
<div class="kv"><span>Forwarding load</span><b>${fmtG(nl)} / ${fmtG(nc)}</b></div><div class="bar ${barCls(nl/nc)}"><i style="width:${Math.min(100,nl/nc*100)}%"></i></div>
${nl>=nc*0.95?`<p class="why">Maxed out. Traffic here is being dropped.</p>`:''}
<div class="btns">${N?btn(N.lvl>lvl()?`${esc(N.n)} <small>level ${N.lvl}</small>`:`Upgrade to ${esc(N.n)} <small>${fmt$(N.cost*rt)} + ${fmt$(N.mo*rt)}/mo</small>`,'upRouter',{city:c},'pink',N.lvl>lvl()||S.cash<N.cost*rt):''}${rt<4?btn(`Add router <small>${fmt$(routerCost(g))} + ${fmt$(ROUTER_MO+G.mo)}/mo</small>`,'addRouter',{city:c},'',S.cash<routerCost(g)):''}${rt>1?btn('Remove one','rmRouter',{city:c},'ghost sm'):''}</div>
${N?`<p class="note">${rt>1?'Rolling upgrade: one router at a time, no downtime.':'With one router, the upgrade needs a maintenance window: this POP goes dark for a day.'}</p>`:''}
<p class="note">${rt>=2?'A crash here only costs one router’s capacity for a few days.':'One router is a single point of failure.'}</p></section>
<section><h3>Power</h3><div class="kv"><span>Backup generator</span><b>${p.gen?'Installed':'None'}</b></div>${p.gen?'<p class="note">Power cuts are covered.</p>':`<div class="btns">${btn(`Install generator <small>${fmt$(GEN_COST)} + ${fmt$(GEN_MO)}/mo</small>`,'addGen',{city:c},'',S.cash<GEN_COST)}</div>`}</section>`;
h+=`<section><h3>DDoS scrubbing center</h3>${S.scrubAt===c?`<p class="lead">Online here. Attack traffic anywhere on your network is cleaned before it hurts, and you can sell DDoS protection to businesses.</p>${btn(UI.confirm==='scrub'?'Really shut it down?':'Shut down','scrub',{city:c},'ghost sm')}`:S.scrubAt?`<p class="lead">You already run one in ${CITY[S.scrubAt].name}.</p>`:`<p class="lead">Absorbs DDoS attacks for your whole network and unlocks DDoS protection contracts for businesses.</p>${btn(`Build scrubbing center <small>${fmt$(SCRUB_COST)} + ${fmt$(SCRUB_MO)}/mo</small>`,'scrub',{city:c},'',S.cash<SCRUB_COST)}`}</section>`;
const fabs=FABS.filter(f=>f.cities.includes(c));
if(fabs.length){h+=`<section><h3>Interconnection fabrics (NNI)</h3><p class="lead">Buy a port on a fabric, then order virtual circuits to your other POPs or to a remote IX. Fast and flexible, but you share their fabric.</p>`;
for(const f of fabs){const pt=nniPort(c,f.id),used=nniUsed(c,f.id);
h+=`<div class="row"><span class="logo" style="--c:${f.col}">${initials(f)}</span><div class="grow"><div class="nm">${esc(f.name)}</div><div class="meta">${esc(f.blurb)}</div>`;
if(pt){const cap=NNI[pt.tier].g;h+=`<div class="kv"><span>${NNI[pt.tier].n} port · ${fmt$(NNI[pt.tier].mo)}/mo</span><b>${fmtG(used)} of circuits</b></div><div class="bar ${barCls(used/cap)}"><i style="width:${used/cap*100}%"></i></div><div class="btns">${btn('New circuit','openVxc',{from:c,prov:f.id},'pink sm')}${pt.tier<1?btn(`Upgrade 100G <small>${fmt$(NNI[1].mo)}/mo</small>`,'buyNni',{city:c,prov:f.id,tier:1},'sm'):''}${btn('Remove port','rmNni',{city:c,prov:f.id},'ghost sm')}</div>`;}
else h+=`<div class="btns">${NNI.map((N,i)=>btn(`${N.n} port <small>${fmt$(N.mo)}/mo</small>`,'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash<N.mo)).join('')}</div>`;
h+=`</div></div>`;}
h+=`</section>`;}
h+=`<section><h3>Fiber from ${C.name}</h3><p class="lead">Drag from this router to any city on the map to lay a new link. Two paths to every POP means a backhoe can't take you offline.</p>`;
if(!ls.length)h+=`<p class="empty">No links yet.</p>`;
for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l);
h+=`<div class="row"><div class="grow"><div class="nm">→ ${CITY[o].name}${l.mult>1?' · diverse':''} ${cut?'<span class="tag restrictive">CUT</span>':''}</div><div class="meta">${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?'virtual circuit via '+esc(FAB[l.prov].name):l.kind==='df'?(l.own?'own dark fiber':'dark fiber IRU')+(l.ready>S.day?` · ready in ${l.ready-S.day}d`:''):l.sub?'subsea':'terrestrial'} · ${fmt$(l.mo)}/mo</div><div class="bar ${barCls(u)}"><i style="width:${u*100}%"></i></div></div>${btn('Open','selLink',{id:l.id},'ghost sm')}</div>`;}
h+=`</section>`;
}
return h+`</div>`;
}
function ixSection(c){const C=CITY[c],ks=cityIxes(c);if(ks.length)return ks.map(ixBlock).join('');let h='';
h+=`<section><h3>Internet Exchange</h3>`;
if(C.cn){h+=`<p class="lead">Running an exchange in mainland China takes a different license entirely. Peer with Chinese networks over PNIs, or meet them in Hong Kong.</p>`;}
else{h+=`<p class="lead">There's no IX in ${C.name} yet. Found one: networks join over time, pay you for ports, and peer with you for free.</p>${S.pops[c]?btn(`Found your own IX <small>${fmt$(MYIX_COST)} + ${fmt$(MYIX_MO)}/mo</small>`,'foundIx',{city:c},'pink',S.cash<MYIX_COST):'<p class="note">Build a POP here first.</p>'}`;}
h+=`</section>`;return h;
}
const portMo=v=>v?fmt$(v)+'/mo':'free';
function ixBlock(c){const cc=ixCity(c),ix=ixName(c),x=XIX[c];let h=`<section><h3>Internet Exchange${cityIxes(cc).length>1?' · '+esc(ix):''}</h3>${x?`<p class="note" style="margin-top:0">${esc(x.note)}</p>`:''}`;
if(S.ixp[c]===undefined){h+=`<p class="lead">${esc(ix)} is a shared switch. One port lets you peer with every member for free. Members: ${ixMembers(c).map(id=>esc(NET[id].name)).join(', ')||'nobody yet'}.</p>${S.pops[cc]?'':REMOTE_WARN}<div class="btns">${PORT.map((P2,i)=>btn(`${P2.n} port <small>${portMo(ixPortMo(c,i))}</small>`,'buyIx',{city:c,tier:i},'',S.cash<ixPortMo(c,i)||(!!S.pops[cc]&&!portOk(cc,i))||(!S.pops[cc]&&i>1))).join('')}</div>`;}
else{const mine=!!S.myIx[c],u=R.useIx[c]||0,cap=ixCap(c),set=ixSessions(c),xdown=S.ev.ixdown&&S.ev.ixdown[c]>S.day;
h+=`<div class="kv"><span>${mine?'Your own fabric · 400G':lagName(S.ixp[c],(S.ixn||{})[c])}${xdown?' · <b style="color:var(--bad)">FABRIC DOWN</b>':''}</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('ix',c,S.ixPref&&S.ixPref[c])}`;
if(isRemote(c))h+=`<p class="note">Remote port via a reseller: 1.5× price, 80% usable, and ${ixMembers(c).filter(noRemote).length} member${ixMembers(c).filter(noRemote).length===1?'':'s'} here refuse remote peers.</p>`;
if(mine)h+=`<div class="kv"><span>Members paying you</span><b>${S.myIx[c].members.length} · ${fmt$(S.myIx[c].members.length*MYIX_FEE)}/mo</b></div>`;
else h+=`<div class="btns">${PORT.map((P2,i)=>i>S.ixp[c]?btn(`Upgrade ${P2.n} <small>${portMo(ixPortMo(c,i)*((S.ixn||{})[c]||1))}</small>`,'buyIx',{city:c,tier:i},'sm',(!!S.pops[cc]&&!portOk(cc,i))||(!S.pops[cc]&&i>1)):'').join('')}${S.pops[cc]&&((S.ixn||{})[c]||1)<LAG_MAX?btn(`+ LAG member <small>${portMo(ixPortMo(c,S.ixp[c]))}</small>`,'lagIx',{city:c,d:1},'sm',S.cash<ixPortMo(c,S.ixp[c])):''}${((S.ixn||{})[c]||1)>1?btn('− member','lagIx',{city:c,d:-1},'ghost sm'):''}${btn(S.rs[c]?'Leave route server':'Join route server','rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${btn(UI.confirm==='ix'+c?'Really leave?':'Leave IX','cancelIx',{city:c},'ghost sm')}</div>`;
h+=`<div style="margin-top:8px">`;
for(const id of ixMembers(c)){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c);
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)}</div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${(NSH[id]*100).toFixed(0)}%</div>${!on&&!chk.ok?`<div class="why">${esc(chk.why)}</div>`:''}</div>
${on?(viaRs||mine?`<span class="tag st on">${mine?'Member':'via RS'}</span>`:btn('Peered ✓','unpeer',{city:c,net:id},'green sm',false,'Click to tear down')):btn('Request','peer',{city:c,net:id},'sm',!chk.ok)}</div>`;}
h+=`</div>`;}
h+=`</section>`;return h;
}
function vxcPanel(l){
const load=R.load[l.id]||0,cap=VXC[l.vt].g,u=load/cap,down=linkDown(l),f=FAB[l.prov];
let h=`<div class="ph"><div><div class="eyebrow">Virtual circuit · ${esc(f.name)} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="Close">×</button></div><div class="scroll">`;
if(down)h+=`<section><h3 style="color:var(--bad)">Fabric outage</h3><p class="lead">${esc(f.name)} is down. Nothing you can do but wait, or have another path.</p></section>`;
h+=`<section><h3>Capacity</h3><div class="kv"><span>${VXC[l.vt].n} circuit</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>Monthly</span><b>${fmt$(l.mo)}/mo</b></div>${!S.pops[l.b]?`<p class="note">Remote peering leg into ${cityIxes(l.b).map(k=>esc(ixName(k))).join(' and ')}.</p>`:''}
<div class="btns">${VXC.map((V,t)=>t>l.vt?btn(`${V.n} <small>${fmt$(vxcMo(l.km,l.sub,t))}/mo</small>`,'upVxc',{id:l.id,t},'sm'):'').join('')}</div></section>
${trafficSection(l)}${metricSection(l)}
<section>${btn(UI.confirm===l.id?'Really cancel?':'Cancel circuit','cancelVxc',{id:l.id},'ghost sm')}</section></div>`;
return h;
}
function prefCtl(kind,id,cur){cur=cur||'normal';return `<div class="btns"><span class="meta" style="align-self:center">Egress:</span>${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}</div>`;}
function trafficSection(l){
const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length;
let h=`<section><h3>What's on this link</h3>`;
if(!rec){return h+`<p class="empty">No traffic right now.</p></section>`;}
const tot=Object.values(rec.net).reduce((a,b)=>a+b,0)||1;
const nets=Object.entries(rec.net).sort((a,b)=>b[1]-a[1]);
const col=id=>id==='junk'?'#FF4D5E':id==='l2vpn'?'#7B61FF':NET[id].col,nm=id=>id==='junk'?'DDoS junk':id==='l2vpn'?'L2VPN customers':NET[id].name;
h+=`${n>1?`<p class="note" style="margin-top:0">Totals for all ${n} links between these cities.</p>`:''}<div class="stack">${nets.map(([id,v])=>`<i style="width:${v/tot*100}%;background:${col(id)}" title="${esc(nm(id))}"></i>`).join('')}</div>`;
h+=`<h4 class="sub4">Content from</h4>`+nets.slice(0,6).map(([id,v])=>`<div class="kv"><span><span class="dot" style="background:${col(id)}"></span>${esc(nm(id))}</span><b>${fmtG(v)} · ${pct(v/tot)}</b></div>`).join('');
const egs=Object.entries(rec.eg).sort((a,b)=>b[1]-a[1]);
h+=`<h4 class="sub4">Enters your network at</h4>`+egs.slice(0,6).map(([k,v])=>{const d=R.egDesc[k];return `<div class="row"><div class="grow"><div class="nm">${esc(d.lab)}</div><div class="meta">${CITY[d.city].name} · ${fmtG(v)} · ${pct(v/tot)}</div></div>${btn('Open','goEgress',{city:d.city,k:d.k},'ghost sm')}</div>`;}).join('');
const dst=Object.entries(rec.dst).sort((a,b)=>b[1]-a[1]);
h+=`<h4 class="sub4">Going to customers in</h4>`+dst.slice(0,6).map(([c,v])=>`<div class="kv"><span>${CITY[c].name}</span><b>${fmtG(v)} · ${pct(v/tot)}</b></div>`).join('');
const u=tot/pairLinks(l.a,l.b).filter(x=>!linkDown(x)).reduce((a,x)=>a+capOf(x),0);
if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`<p class="why">Biggest feeder: ${esc(d.lab)} in ${CITY[d.city].name}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.</p>`;}
return h+`</section>`;
}
function metricSection(l){const cur=l.metric||'normal';
return `<section><h3>Routing metric</h3><p class="lead">Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.</p><div class="btns">${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}</div></section>`;}
function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2;
let h=`<section><h3>Behind the Great Firewall</h3><p class="lead">Mainland China plays by its own rules. ${CN_BLOCKED.slice(0,4).map(esc).join(', ')} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about ${pct(loss)} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.</p>`;
if(st==='none')h+=`<p class="lead">Foreign networks need a local joint venture and an operating license to build infrastructure here.</p>${btn(`Apply for a license <small>${fmt$(CN_LIC)} + ${fmt$(CN_JV_MO)}/mo · ~45 days</small>`,'applyCn',{},'pink',S.cash<CN_LIC)}`;
else if(st==='pending')h+=`<p class="note">License paperwork in progress: ${Math.max(0,S.cnLic.ready-S.day)} days left.</p>`;
else h+=`<p class="note">Your joint venture holds an operating license.</p>`;
if(R.gfwCross>0.5)h+=`<div class="kv"><span>Your traffic crossing the border</span><b>${fmtG(R.gfwCross)}</b></div><div class="kv"><span>Lost on the way</span><b style="color:var(--bad)">${fmtG(R.gfwLost)}</b></div>`;
return h+`</section>`;}
function dfPanel(l){
const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys];
let h=`<div class="ph"><div><div class="eyebrow">Dark fiber · ${l.own?'your own build':'leased IRU'} · ${l.km.toLocaleString()} km</div><h2>${A} ⇄ ${B}</h2></div><button class="x" data-act="closePanel" aria-label="Close">×</button></div><div class="scroll">`;
if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1);
h+=`<section><h3>${l.own?'Under construction':'Being spliced'}</h3><div class="kv"><span>${l.own?'Permits, trenching, splicing':'IRU handover'}</span><b>${l.ready-S.day} days left</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own?btn(`Hire extra crews <small>${fmt$(Math.round(15000+l.km*6))} · −30 days</small>`,'crews',{id:l.id},'sm',S.cash<15000+l.km*6):''}<p class="note">You can pre-install optics now so it lights up the day it's ready.</p></section>`;}
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">Dark!</h3><p class="lead">${esc(inc.msg)}</p>${inc.cost?btn(`${esc(inc.fix||'Rush repair')} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>Capacity</h3><div class="kv"><span>${(l.ch||[]).length} of ${sysD.max} channels lit${soldSlots(l)?` · ${soldSlots(l)} sold as alien waves`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>Latency</span><b>${linkLat(l).toFixed(1)} ms one-way</b></div><div class="kv"><span>${l.own?'Right-of-way upkeep':'IRU lease'}</span><b>${fmt$(l.mo)}/mo</b></div><div class="kv"><span>${amps} amp huts</span><b>${fmt$(amps*AMP_MO)}/mo</b></div>${!bld&&!(l.ch||[]).length?`<p class="why">This fiber is dark. Add optics below to carry traffic.</p>`:''}</section>`;
h+=`<section><h3>Optics</h3><p class="lead">Each channel is a pair of optics, one per end. ZR+ optics plug straight into your routers. Transponders sit on a shelf.</p>`;
for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k);
h+=`<div class="row"><div class="grow"><div class="nm">${O.n} <span class="meta">${fmtG(O.g)} · reach ${O.reach.toLocaleString()} km</span></div><div class="meta">${esc(O.blurb)}${n?` · <b>${n} lit</b>`:''}</div>${why?`<div class="why">${esc(why)}</div>`:''}</div>${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(`+ <small>${fmt$(optCost(k))}</small>`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash<optCost(k))}</div>`;}
h+=`</section><section><h3>Line system</h3><div class="kv"><span>${esc(sysD.n)}</span><b>${amps} amplifiers</b></div><p class="note">${esc(sysD.blurb)}</p><div class="btns">${l.sys!=='roadm'?btn(lvl()>=3?`Upgrade to ROADMaster 9000 <small>${fmt$(DF_SYS.roadm.cost)}</small>`:'ROADMaster 9000 <small>level 3</small>','upSys',{id:l.id},'sm',lvl()<3||S.cash<DF_SYS.roadm.cost):''}${btn(l.spares?'Spares kit on ✓':`Keep a spares kit <small>${fmt$(Math.round(150+(l.ch||[]).length*80))}/mo</small>`,'spares',{id:l.id},l.spares?'green sm':'sm')}</div><p class="note">Spare optics and amplifier cards on the shelf turn multi-day hardware failures into one-day swaps.</p></section>`;
h+=`${trafficSection(l)}${metricSection(l)}<section>${btn(UI.confirm===l.id?'Really give it up?':(l.own?'Abandon the fiber':'Cancel the IRU'),'rmLink',{id:l.id},'ghost sm')}</section></div>`;
return h;
}
function offersHere(c){
const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return '';
return `<section><h3>Offers here</h3>${os.map(o=>`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${o.exp-S.day}d left</div>${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">They need the full internet. Your reach is ${pct(R.reach)}.</div>`:''}${o.type==='scrub'&&!S.scrubAt?`<div class="why">Needs your own scrubbing center (Infra tab).</div>`:''}${reqList(o)}${bHas(o)?'':`<div class="why">Needs a POP in ${bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')} too.</div>`}</div>${bHas(o)?btn('Accept','accept',{id:o.id},'green sm'):''}${btn('No','decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
}
function linkPanel(id){
const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';}
if(l.kind==='vxc')return vxcPanel(l);
if(l.kind==='df')return dfPanel(l);
const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,tr=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===tr)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===tr);
let h=`<div class="ph"><div><div class="eyebrow">${l.cable?esc(CAB[l.cable].name):l.sub?'Subsea cable':'Terrestrial fiber'} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="Close">×</button></div><div class="scroll">`;
if(cut)h+=`<section><h3 style="color:var(--bad)">Cut!</h3><p class="lead">${inc?esc(inc.msg):''} Back in ${l.cut-S.day} days.</p>${inc?btn(`Rush repair ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>Capacity</h3><div class="kv"><span>${LT[l.tier].n} wave</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>Latency</span><b>${linkLat(l).toFixed(1)} ms one-way</b></div>${l.cable?`<div class="kv"><span>Cable system</span><b>${esc(CAB[l.cable].name)}</b></div>`:''}
<div class="kv"><span>Wave lease</span><b>${fmt$(l.mo)}/mo</b></div>${u>=0.9?`<p class="why">Congested. Upgrade it or add a parallel path.</p>`:''}
<div class="btns">${LT.map((T,i)=>{const d=Math.round(waveMo(l.km,l.sub,i)*(l.mult||1)),ok=waveOk(l.a,l.b,i);return i>l.tier?btn(`${T.n} <small>${ok?fmt$(d)+'/mo':'needs '+esc(waveNeed(i))}</small>`,'upLink',{id:l.id,tier:i},'sm',S.cash<d||!ok):'';}).join('')}</div></section>
<section><h3>Redundancy</h3><p class="lead">${mates.length?`Shares a trench with ${mates.length} other link${mates.length>1?'s':''}. One cut takes them all down.`:sib.length?'Runs on its own route. A cut here leaves the other links up.':'This is the only link between these cities. Add a parallel one, or a path through another city.'}</p>
${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${capName(x)} parallel link ${x.cut>S.day?'<span class="tag restrictive">CUT</span>':''}</div><div class="meta">${(x.trench||x.id)===tr?'same trench':'diverse route'}</div></div>${btn('Open','selLink',{id:x.id},'ghost sm')}</div>`).join('')}
<div class="btns">${btn('Add parallel link','addParallel',{id:l.id},'pink sm')}</div></section>
${trafficSection(l)}${metricSection(l)}
<section>${btn(UI.confirm===l.id?'Really decommission?':'Decommission link','rmLink',{id:l.id},'ghost sm')}</section></div>`;
return h;
}
const EGC={c:['Caches','#16A866'],p:['PNIs','#7B61FF'],ix:['IX peering','#FFD23F'],t:['Transit','#FF8A3D'],l2:['L2 circuits','#2F8CFF']};
function svgChart(rows,stackKeys,lines,fmtY){
const W=600,H=180,L=50,B=20,T=8,Rr=8;if(rows.length<2)return `<p class="empty">Collecting data. Check back in a few days.</p>`;
let ymax=1;for(const r of rows){let s=0;for(const k of stackKeys)s+=r[k]||0;ymax=Math.max(ymax,s);for(const ln of lines)ymax=Math.max(ymax,r[ln.k]||0);}ymax*=1.1;
const x=i=>L+(W-L-Rr)*i/(rows.length-1),y=v=>T+(H-T-B)*(1-v/ymax);let g='';
for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`<line x1="${L}" x2="${W-Rr}" y1="${yy}" y2="${yy}" stroke="#D5DEEC" stroke-width="1"/><text x="${L-6}" y="${yy+3}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${fmtY(v)}</text>`;}
const base=rows.map(()=>0);
for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i<rows.length;i++)d+=`L${x(i)},${y(top[i])}`;for(let i=rows.length-1;i>=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=`<path d="${d}Z" fill="${EGC[k][1]}" fill-opacity=".85" stroke="#1E2640" stroke-width=".8"/>`;top.forEach((v,i)=>base[i]=v);}
for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=`<path d="${d}" fill="none" stroke="${ln.col}" stroke-width="2.5" ${ln.dash?'stroke-dasharray="5 4"':''} stroke-linejoin="round"/>`;const last=rows[rows.length-1][ln.k]||0;g+=`<circle cx="${x(rows.length-1)}" cy="${y(last)}" r="3.5" fill="${ln.col}" stroke="#1E2640" stroke-width="1.5"/>`;}
g+=`<text x="${L}" y="${H-5}" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[0].d)}</text><text x="${W-Rr}" y="${H-5}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[rows.length-1].d)}</text>`;
return `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img">${g}</svg>`;}
function renderDash(){
const H=S.hist||[],rows=H.slice(-90),last30=H.slice(-30);
const up=last30.length?last30.reduce((a,r)=>a+(r.dem?Math.min(1,r.srv/r.dem):1),0)/last30.length:1;
const net=R.revMo-R.costMo,tot=Object.values(R.egT).reduce((a,b)=>a+b,0)||1;
const tile=(l,v,sub)=>`<div class="tile"><div class="lbl">${l}</div><div class="val">${v}</div>${sub?`<div class="sub">${sub}</div>`:''}</div>`;
let h=`<div style="display:flex;align-items:center;gap:10px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)} · ${tierLabel()}</div><h2 style="font-size:28px">NOC dashboard</h2></div><button class="x" data-act="dashClose" aria-label="Close">×</button></div>
<div class="dgrid">${tile('Traffic now',fmtG(R.served),`of ${fmtG(R.demand)} wanted`)}${tile('Peak',fmtG(S.stats.peak))}${tile('Delivered, 30 days',(up*100).toFixed(1)+'%',up>=0.999?'five nines-ish':up>=0.99?'two nines and change':'customers are upset')}${tile('Peering ratio',pct(R.peerShare||0),'caches, PNIs and IX')}${tile('Monthly P&L',`<span style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</span>`,`${fmt$(R.revMo)} in · ${fmt$(R.costMo)} out`)}${tile('Incidents',S.stats.incidents,`${S.stats.survived} shrugged off`)}</div>
<div class="dcols"><div class="panel2"><h3>Traffic by way out</h3>${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)))}<div class="legend">${Object.keys(EGC).map(k=>`<span><i style="background:${EGC[k][1]}"></i>${EGC[k][0]} ${pct((R.egT[k]||0)/tot)}</span>`).join('')}<span><i style="background:#fff;border-style:dashed"></i>Demand</span></div></div>
<div class="panel2"><h3>Money per month</h3>${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v))}<div class="legend"><span><i style="background:#16A866"></i>Revenue</span><span><i style="background:#FF4D5E"></i>Costs</span></div>
<h3 style="margin-top:8px">Where the money goes</h3>${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`<div class="kv"><span>${{pops:'POPs and routers',links:'Waves and fiber',transit:'Transit',ix:'IX ports',pni:'PNIs',caches:'Cache power',nni:'Fabric ports',optical:'Amp huts and spares',loans:'Loan repayments',revshare:'Investor revenue share',extras:'Licenses and scrubbing'}[k]||k}</span><b>${fmt$(v)}/mo</b></div>`).join('')}</div></div>`;
const nets=NETS.map(n=>{const e=R.netEg[n.id]||{c:0,p:0,ix:0,t:0};const t=e.c+e.p+e.ix+e.t;return {n,e,t};}).filter(x=>x.t>0.01||R.demTo[x.n.id]>0.01).sort((a,b)=>b.t-a.t);
const tT=(R.egT.t||0)||1;
h+=`<div class="panel2" style="margin-top:12px"><h3>Traffic by network (ASN)</h3><p class="note" style="margin-top:0">Where your users' traffic comes from, and how it gets to you. Red in the mix is paid transit; everything else is free or cheap.</p><div class="tscroll"><table class="tbl"><thead><tr><th>Network</th><th>AS</th><th>Type</th><th class="r">Traffic</th><th>How it arrives</th><th class="r">Transit cost</th><th class="r">Lost</th></tr></thead><tbody>
${nets.map(({n,e,t})=>{const want=R.demTo[n.id]||0;return `<tr><td><span style="display:inline-flex;align-items:center;gap:6px">${logo(n)}<b>${esc(n.name)}</b></span></td><td>${n.asn}</td><td><span class="tag ${n.type}">${TYPE_L[n.type]}</span></td><td class="r">${fmtG(t)}</td><td><div class="mix">${['c','p','ix','t'].map(k=>`<i style="width:${t?e[k]/t*100:0}%;background:${k==='t'?'#FF4D5E':EGC[k][1]}"></i>`).join('')}</div></td><td class="r">${e.t>0.01?fmt$((R.cost.transit||0)*e.t/tT)+'/mo':'—'}</td><td class="r" style="color:${want-t>want*0.05?'var(--bad)':'inherit'}">${want>0.01?pct(Math.max(0,1-t/want)):'—'}</td></tr>`;}).join('')}</tbody></table></div></div>`;
const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8);
const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6);
h+=`<div class="dcols" style="margin-top:12px"><div class="panel2"><h3>Busiest links</h3>${ls.length?ls.map(({l,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[l.a].name} ⇄ ${CITY[l.b].name} <span class="meta">${capName(l)} · ${linkLat(l).toFixed(1)} ms</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b>${btn('Open','dashLink',{id:l.id},'ghost sm')}</div>`).join(''):'<p class="empty">No links yet.</p>'}</div>
<div class="panel2"><h3>Router load</h3>${rs.map(({c,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[c].name} <span class="meta">${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b></div>`).join('')}
<h3 style="margin-top:10px">Your AS</h3><div class="kv"><span>AS number</span><b>AS${S.asn}</b></div><div class="kv"><span>Prefixes</span><b>${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>BGP sessions</span><b>${R.sessions}</b></div><div class="kv"><span>Upstreams</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>Reach</span><b>${pct(R.reach)}</b></div><div class="kv"><span>Customers</span><b>${S.biz.length} businesses</b></div></div></div>`;
if(h!==UI._dh){UI._dh=h;$('dashCard').innerHTML=h;}
}
function renderBank(){
if(!S||$('bankBox').hidden)return;const rt=rating(),net=R.revMo-R.costMo;
const terms=(o)=>{const B=BANKS[o.bank];return B.equity?`<span class="tag st on">No repayments</span><span class="tag st">${pct(o.share)} of revenue, forever</span><span class="tag st">Buy-out ${fmt$(o.amount*3)}</span>`:`<span class="tag st on">${(o.apr*100).toFixed(1)}% APR</span><span class="tag st">${o.term} months</span><span class="tag st">${fmt$(o.pay)}/mo</span>${B.crypto?'<span class="tag selective">Paid in TubeCoin</span>':''}`;};
const covList=(l)=>l.covs.length?l.covs.map(c=>{const ok=COVS[c].ok(l);return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(COVS[c].l)}</div>`;}).join(''):'<div class="meta">No conditions. That is the scary part.</div>';
let h=`<div style="display:flex;align-items:center;gap:12px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)}</div><h2 style="font-size:28px">Bank</h2></div><button class="x" data-act="bankClose" aria-label="Close">×</button></div>
<div class="dgrid"><div class="tile"><div class="lbl">Cash</div><div class="val" style="color:${S.cash<0?'var(--bad)':'inherit'}">${fmt$(S.cash)}</div><div class="sub">${S.cash<0?'Bankrupt at −$100k':'in the vault'}</div></div>
<div class="tile"><div class="lbl">Monthly P&L</div><div class="val" style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</div><div class="sub">after loan payments</div></div>
<div class="tile"><div class="lbl">Credit rating</div><div class="val">${rt}</div><div class="sub">${rIdx(rt)>=5?'Bankers return your calls':rIdx(rt)>=3?'Bankers return your emails':'Bankers pretend to be out'}</div></div>
<div class="tile"><div class="lbl">Debt</div><div class="val">${fmt$(S.loans.reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.bal),0))}</div><div class="sub">${S.loans.length} loan${S.loans.length===1?'':'s'}</div></div></div>`;
h+=`<h3 style="font-size:18px;margin-top:6px">Offers</h3>`;
if(!S.loanOffers.length)h+=`<p class="empty">No offers right now. Banks get in touch now and then, and much faster when you are in trouble. A better credit rating brings better banks.</p>`;
for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${esc(B.name)} offers <b>${fmt$(o.amount)}</b></div><div class="meta">${esc(B.blurb)} · offer ends in ${o.exp-S.day}d</div><div class="terms">${terms(o)}</div>${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(x=>x.sub).length}})}<div class="btns" style="margin-top:6px">${btn('Take the money','takeLoan',{id:o.id},'pink')}${btn('No thanks','declineLoan',{id:o.id},'ghost sm')}</div></div></div>`;}
h+=`<h3 style="font-size:18px;margin-top:14px">Your loans</h3>`;
if(!S.loans.length)h+=`<p class="empty">Debt-free. Your accountant is suspicious.</p>`;
for(const l of S.loans){const B=BANKS[l.bank];const cost=B.equity?Math.round(l.amount*3):Math.round(l.bal*1.02);
h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${esc(B.name)} · ${fmt$(l.amount)}</div>
${B.equity?`<div class="meta">Taking ${pct(l.share)} of your revenue every month.</div>`:`<div class="kv"><span>Still owed</span><b>${fmt$(l.bal)}</b></div><div class="bar me"><i style="width:${Math.min(100,(1-l.bal/l.amount)*100)}%"></i></div><div class="meta">${fmt$(l.pay)}/mo · ${l.left} months left · ${(l.apr*100).toFixed(1)}% APR</div>`}
${covList(l)}${l.breach>=1?`<div class="why">Condition broken for ${l.breach} day${l.breach===1?'':'s'}. ${l.breach<10?`Penalty in ${10-l.breach} days.`:'Penalties are running.'}</div>`:''}
<div class="btns" style="margin-top:6px">${btn(UI.confirm===l.id?`Really pay ${fmt$(cost)}?`:B.equity?`Buy them out <small>${fmt$(cost)}</small>`:`Repay early <small>${fmt$(cost)} incl. 2% fee</small>`,'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash<cost)}</div></div></div>`;}
if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;}
}
function renderHint(){
const hn=$('hint');if(!S||UI.hintOff||(innerWidth<760&&(UI.sel||UI.leftOpen)&&!(UI.drag&&UI.drag.mode==='link'))){hn.hidden=true;return;}
let t='';
if(UI.drag&&UI.drag.mode==='link')t=UI.snap?'Release to plan a link':'Drag onto another city';
else if(!S.links.length&&S.done.tr)t='Tip: drag from your pink router to another city to lay fiber';
else if(!S.done.bb)t='Tap your city, then Launch broadband';
hn.textContent=t;hn.hidden=!t;
}
/* ---------- toasts & modals ---------- */
function toast(html,kind='',actions=[]){
if(S){S.log=S.log||[];const tmp=document.createElement('div');tmp.innerHTML=html.replace(/<br>/g,' ');S.log.unshift({d:S.day,t:tmp.textContent,k:kind});if(S.log.length>30)S.log.length=30;}
const el=document.createElement('div');el.className='toast '+kind;
el.innerHTML=`<div class="tx">${html}</div>${actions.map(a=>btn(a.l,a.act,a.args,'sm')).join('')}`;
const box=$('toasts');box.prepend(el);const max=innerWidth<760?2:3;while(box.children.length>max)box.lastChild.remove();
setTimeout(()=>{el.style.transition='opacity .4s';el.style.opacity=0;setTimeout(()=>el.remove(),400);},actions.length?8000:4500);
}
function openModal(html){$('modalCard').innerHTML=html;$('modal').hidden=false;}
function closeModal(){$('modal').hidden=true;UI.pending=null;}
function showTitle(){
const sv=loadSave();
const starts=[['fra','Crossroads of Europe. DE-KICKS IX, cheap transit.'],['nyc','Huge eyeball market. Pricey neighbours.'],['sin','Asia hub. Great peering, far from home.'],['sao','Big hungry market, few providers.']];
openModal(`<div class="title-art"><svg width="74" height="74" viewBox="0 0 74 74" aria-hidden="true"><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#1E2640" stroke-width="16" stroke-linecap="round"/><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#FFD23F" stroke-width="9" stroke-linecap="round"/><circle cx="58" cy="16" r="11" fill="#FF4F9A" stroke="#1E2640" stroke-width="4"/><circle cx="21" cy="44" r="3" fill="#fff"/><circle cx="30" cy="27" r="3" fill="#fff"/></svg>
<h1>Series<br>of <span>Tubes</span></h1></div>
<p class="tagline">Build an internet. Lay fiber between cities, buy transit, peer at exchanges, sign up businesses, and keep the eyeballs happy while backhoes, sharks and route leaks do their best to stop you.</p>
${sv?`<div class="btns" style="margin-bottom:6px">${btn(`Continue ${esc(sv.name)} · ${dateStr(sv.day)}`,'cont',{},'pink big')}</div>`:''}
<label class="f" for="nmIn">Name your network</label><input class="t" id="nmIn" maxlength="24" value="Packet Pals" autocomplete="off">
<label class="f">Pick your home city</label><div class="starts">${starts.map(([c,d])=>`<button class="start ${UI.startCity===c?'on':''}" data-city="${c}" data-act="pickStart" data-args='{"city":"${c}"}'><b>${CITY[c].name}</b><span>${d}</span></button>`).join('')}</div>
<div class="btns" style="margin-top:16px;justify-content:space-between;align-items:center">${btn(sv?'Start a new network':'Start building','start',{},'big')}${btn('How to play','help',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">Source on GitHub</a> · Cookieless stats, no tracking</p>`);
if(sv){S=migrate(sv);compute();}
}
// "What's new": shown once to returning players after an update, or on demand.
function whatsNew(returning,force){
if(IS_DEV||!RELEASE_NOTES.length)return false;let seen=null;
try{seen=localStorage.getItem('sot-seen-version');localStorage.setItem('sot-seen-version',APP_VERSION);}catch(e){}
if(!force&&(!returning||seen===APP_VERSION))return false;
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Release notes</div><h2 style="font-size:28px">New in Series of Tubes ${esc(APP_VERSION)}</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="Close">×</button></div>
<ul class="notes">${RELEASE_NOTES.map(n=>`<li>${esc(n)}</li>`).join('')}</ul>
${returning&&S?`<p class="note">Your network ${esc(S.name)} was saved and is waiting for you.</p>`:''}
<div class="btns" style="margin-top:12px">${btn(UI.started?'Back to my network':'Got it',UI.started?'closeModal':'helpClose',{},'pink big')}<a class="b ghost" href="https://github.com/fjaeckel/seriesoftubes/blob/main/CHANGELOG.md" target="_blank" rel="noopener">Full changelog</a></div>`);
return true;}
function newerVer(a,b){const x=String(a).split('.').map(Number),y=String(b).split('.').map(Number);for(let i=0;i<3;i++){if((x[i]||0)>(y[i]||0))return true;if((x[i]||0)<(y[i]||0))return false;}return false;}
// While the game is open, look for a newer release now and then and offer a reload.
function checkUpdate(){
if(IS_DEV||location.protocol==='file:'||!window.fetch)return;const now=Date.now();if(now-(UI.updChecked||0)<60000)return;UI.updChecked=now;
fetch('/version.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(j=>{
if(!j||!j.version||!newerVer(j.version,APP_VERSION))return;if(UI.updLater&&now-UI.updLater<6*3600*1000)return;
const top=(j.notes||[])[0]||'';$('update').innerHTML=`<div class="tx"><b>Series of Tubes ${esc(j.version)} is out!</b>${top?`<br>${esc(top.length>120?top.slice(0,117)+'…':top)}`:''}<br><span class="meta">Your game is saved automatically.</span></div>${btn('Reload now','updateNow',{},'pink sm')}${btn('Later','updateLater',{},'ghost sm')}`;$('update').hidden=false;
}).catch(()=>{});
}
function showHelp(){
openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:28px">How the internet works here</h2><button class="x" data-act="helpClose" aria-label="Close">×</button></div>
<p class="tagline" style="margin:6px 0 4px"><b>Controls:</b> drag the map to pan, scroll or pinch to zoom, tap a city to open it. <b>Drag from your pink router to another city</b> to lay fiber. <span class="kbd">Space</span> pauses, <span class="kbd">1</span> <span class="kbd">2</span> <span class="kbd">3</span> <span class="kbd">4</span> set speed. At 1× a day lasts 2.5 seconds.</p>
<dl class="gl">
<dt>Eyeballs</dt><dd>Home broadband users. They mostly download from CDNs and pay you per Gbps you deliver. Serve them well and they multiply.</dd>
<dt>POP</dt><dd>Point of presence: your router in a data center. Everything starts at a POP.</dd>
<dt>IP transit</dt><dd>You pay a bigger network per Gbps and it delivers your traffic anywhere. Easy, full reach, never free.</dd>
<dt>Tier 1 / Tier 2</dt><dd>Tier 1s reach the whole internet without paying anyone, because they all peer with each other. Tier 2s peer a lot but still buy some transit.</dd>
<dt>CDN</dt><dd>Content networks like NetChill and Goggle. Most of your traffic comes from them. Peer with them and that traffic is free.</dd>
<dt>IX (Internet Exchange)</dt><dd>A shared switch in a city. One port, many free peering sessions. The route server peers you with every open member at once.</dd>
<dt>PNI</dt><dd>Private network interconnect: a cable straight to one network in the same building. For big traffic.</dd>
<dt>Embedded cache</dt><dd>A CDN's server in your rack. Serves most of that CDN's traffic locally, for the price of power.</dd>
<dt>Remote peering</dt><dd>Reach an IX over a fabric circuit without a POP there. It works, and the route server still gets you every open network, but it is discouraged: the reseller charges 1.5× for the port and oversubscribes it to 80%, latency rides the fabric, one fabric outage drops every session, and many selective networks refuse remote members outright.</dd><dt>Peering policy</dt><dd>Open peers with anyone. Selective wants to see traffic first. Restrictive (Tier 1s) only peers with giants, over PNIs. Paid means exactly that. Big selective networks also have moods: in some cities they refuse new peers for a few months, or only take PNIs, and now and then they tear down a session you already had. Try another city or a PNI, and ask again later.</dd>
<dt>Waves</dt><dd>Your fiber links are leased waves at a flat monthly rate. Longer and bigger costs more (10G → 6.4T), and subsea is 1.8× the price.</dd><dt>95th percentile</dt><dd>Transit bills sample your usage every day and charge the 95th percentile of the last 30 days, so short spikes are forgiven but long ones are not.</dd><dt>Routers</dt><dd>Each POP's router model caps its fastest port (100G, 400G, 800G, 1.6T) and how much it can forward. Bigger waves and ports need better routers at both ends. Better models unlock with your customer level. With one router, upgrades mean a day of downtime.</dd><dt>Dark fiber</dt><dd>Lease an IRU or build your own (slow, with delays), then buy a line system with amplifiers and light channels with 400ZR+, 800ZR+ or 1.6T transponders. Much cheaper than waves at scale, but the gear can fail. A spares kit speeds up repairs.</dd><dt>Subsea cables</dt><dd>Subsea waves can only follow real-ish cable systems, drawn faintly on the map (tap a city to highlight its cables). Teal ones are new and cheap, purple ones pricey, dashed ones old and cut-prone. All your waves on one cable die together when it is cut. Between continents on land, you can often choose overland (2.5×, many borders) or a cable.</dd><dt>Latency</dt><dd>Every link has latency. High-frequency traders pay a fortune for a circuit within their latency budget; route them “Lowest latency”. Bulk backup customers do not care, so route them “Scenic” over your quiet links to keep busy ones free.</dd><dt>NOC dashboard</dt><dd>The chart button at the top opens traffic graphs by exit (caches, PNIs, IX, transit), money over time, per-ASN traffic with how it reaches you and what its transit costs, plus your busiest links and routers.</dd><dt>Asia</dt><dd>A weird, underserved market. Transit costs 2.5× what it does in Europe (Africa 2×, Oceania 1.8×), local incumbents mostly peer only for pay, and IXs are fragmented. But demand is enormous and users sign up 60% faster than anywhere else. Peering and caches pay off most here.</dd><dt>Russia</dt><dd>Moscow needs a mandatory government box in every POP, Western CDNs are mostly gone, Goggle video is throttled to half speed, and the sovereign internet drills now and then cut Moscow off for a day.</dd><dt>Events, chains and wholesale</dt><dd>Event networks (a final, a festival, a keynote) need a burst of capacity in one city for a few days and pay once at the end, prorated by how much of the crowd you served; below 70% you pay a penalty. SD-WAN chains connect 3–6 of your POPs hub-and-spoke, so one broken spoke upsets the whole contract. Once you run your own dark fiber, carriers want to rent spare channels as alien waves, and on fiber you built yourself, a spare pair.</dd><dt>Bank</dt><dd>Tap your cash to open the bank. Lenders make offers now and then, and much more often when you are in the red. Each loan has a monthly payment and some odd conditions; break one and you pay a penalty. Your credit rating decides which banks talk to you. The loan shark is always there. Do not be late.</dd><dt>LAGs</dt><dd>Out of port speed? Bundle up to 8 identical ports to the same transit provider, IX or PNI into a LAG. Each member costs a full port; flow hashing is never perfectly even, so a bundle carries about 95% of the sum.</dd><dt>Traffic engineering</dt><dd>Tap a link to see which networks, which entry points and which customer cities fill it. Raise a link's metric to steer traffic around it, or set an egress (transit, IX, PNI) to Prefer or Backup only.</dd><dt>China</dt><dd>Mainland China needs a license and a local joint venture. Many foreign services are blocked there, and traffic crossing the border loses packets unless you pay for premium routes.</dd><dt>Weird requirements</dt><dd>Some customers come with conditions: no Cogentle anywhere, no subsea cables because of sharks, two routers, a generator, NetChill on-net, low-loss China reach and more. Each pays a bonus. Unmet ones make them grumpy until you fix it or they leave.</dd><dt>Customer levels</dt><dd>As your peak traffic and footprint grow, bigger customers show up: streaming startups and universities, then AI GPU data centers and cloud on-ramps, then AI training interconnects and hyperscaler DCI deals measured in terabits. Pink $$ bubbles mark the big ones.</dd><dt>L2VPN & DDoS protection</dt><dd>Businesses may want a private circuit between two of your POPs (it rides your backbone), or DDoS protection (needs your own scrubbing center).</dd><dt>NNI fabrics</dt><dd>Megapork, PocketFabric and Consolation Connect sell a port plus virtual circuits between cities. Great for small links and remote peering at an IX where you have no POP.</dd>
<dt>Failures</dt><dd>Things break all the time: fiber cuts, router crashes, power cuts, IX loops, fabric outages, route leaks, DDoS, fat fingers, cooling failures, and geopolitics: sanctions, tariffs, BGP hijacks, landing permit disputes, exam-day shutdowns and Red Sea cable cuts. Traffic reroutes automatically over other paths and upstreams. Parallel links on diverse routes, a second router and a backup generator all help. Or pay to rush repairs.</dd>
</dl><div class="btns" style="margin-top:14px">${btn(UI.started?'Back to the map':'Got it','helpClose',{},'big')}${RELEASE_NOTES.length?btn(`What’s new in ${esc(APP_VERSION)}`,'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn('Start a new network','resetAsk',{},'ghost sm'):''}</div>`);
}
function showWin(){openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">You're a <span style="color:var(--me)">Tier 1</span>!</h1><p class="tagline">${esc(S.name)} (AS${S.asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you ${S.day} days and ${S.stats.incidents} incidents.</p>${btn('Keep building','keepPlaying',{},'pink big')}`);sfx('coin');}
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">Bankrupt</h1><p class="tagline">The bank repossessed your routers and sold them on eBuy. ${esc(S.name)} lasted ${S.day} days and peaked at ${fmtG(S.stats.peak)}.</p>${btn('Try again','newgame',{},'pink big')}`);try{localStorage.removeItem('sot-save-v1');}catch(e){}}
function openLinkModal(a,b){
if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">Not without a license</h2><button class="x" data-act="closeModal" aria-label="Close">×</button></div><p class="lead" style="margin-top:8px">Building into mainland China needs a joint venture and an operating license. Open ${CITY[cnCity(a)?a:b].name} to apply.</p>`);return;}
let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:popCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc');
if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),same=sib.length>0&&UI.route==='same',mult=(sib.length&&!same?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if(border)route+=`<p class="lead" style="margin-top:8px">Cross-border circuits into mainland China are sold only by licensed carriers, at 3× the price. Regular ones lose about 20% of traffic at the border.</p>${a==='hkg'||b==='hkg'?`<div class="seg">${btn('Regular crossing','cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn('Premium crossing <small>+60% · ~3% loss</small>','cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}</div>`:`<p class="note">Premium crossings are only sold in Hong Kong.</p>`}`;
if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`<p class="lead" style="margin-top:8px">You already have ${sib.length} link${sib.length>1?'s':''} here (${sib.map(l=>capName(l)).join(', ')}). Parallel links add capacity. How should this one be routed?</p>
<div class="seg">${btn('Diverse route <small>+40% · survives cuts alone</small>','route',{r:'diverse'},UI.route!=='same'?'pink':'ghost')}${btn('Same trench <small>cheaper · one backhoe cuts all</small>','route',{r:'same'},UI.route==='same'?'pink':'ghost')}</div>`;}
const mode=UI.lmode==='df'?'df':'wave',tabs=`<div class="seg" style="margin-top:8px">${btn('Lease a wave','dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn('Dark fiber','dfMode',{m:'df'},mode==='df'?'pink':'ghost')}</div>`;
const head=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${sub?'Subsea':'Terrestrial'} · ${km.toLocaleString()} km</div><h2 style="font-size:26px">${CITY[a].name} → ${CITY[b].name}</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>${tabs}`;
if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));return;}
if(sub&&!cablesFor(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))];openModal(head+`<p class="lead" style="margin-top:10px">No subsea cable lands in both ${CITY[a].name} and ${CITY[b].name}. Cables from ${CITY[a].name} reach ${fr.join(', ')||'nowhere'}. Hop through one of those.</p>`);return;}
if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`<p class="lead" style="margin-top:10px">The landing permit dispute in ${CITY[S.ev.landban.city].name} blocks new subsea links for ${S.ev.landban.until-S.day} more days.</p>`);return;}
const wr=waveRoute(a,b,mult,border);
openModal(`${head}
<p class="lead" style="margin-top:8px">Waves are leased at a flat monthly rate. Bigger and longer costs more, and subsea is 1.8×. First month is due now.</p>
${pop?`<p class="lead" style="margin-top:8px">Includes a new POP in ${CITY[b].name} (${fmt$(popCost(b))}${ruCity(b)?', government box included':''}).</p>`:''}${route}${viaSeg(a,b)}
<div class="tiers">${LT.map((T,i)=>{const lc=Math.round(waveMo(wr.km,wr.sub,i)*wr.wm),c=lc+pop,ok=waveOk(a,b,i);return `<button class="tierbtn" data-act="buildLink" data-args='{"tier":${i}}'${S.cash<c||!ok?' disabled':''}><span class="sz">${T.n}</span><span class="grow meta">${!ok?`needs ${esc(waveNeed(i))} at both ends`:pop?`due now ${fmt$(c)}`:'flat rate'}</span><span class="pr num">${fmt$(lc)}/mo</span></button>`;}).join('')}</div>`);
}
function dfModalBody(a,b,km,pop){
if(isSub(a,b))return `<p class="lead" style="margin-top:10px">Nobody sells dark fiber on a subsea cable here. Subsea capacity comes as leased waves.</p>`;
if(!dfAllowed(a,b))return `<p class="lead" style="margin-top:10px">Dark fiber across the Chinese border is not for sale. Buy a cross-border wave instead.</p>`;
if(lvl()<2)return `<p class="lead" style="margin-top:10px">Dark fiber unlocks at customer level 2. You need the scale to justify buying your own optical gear.</p>`;
const src=UI.dfSrc==='build'&&lvl()>=3?'build':'lease',sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite',amps=ampCount(km);
const up=(src==='build'?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO;
const w=Math.round(waveMo(km,false,3));
return `<p class="lead" style="margin-top:8px">A fiber pair of your own. The glass is cheap, the gear is not: you buy a line system with an amplifier every ${AMP_EVERY} km, then optics for each channel. Your gear can fail, and you fix it.</p>
<h4 class="sub4">The glass</h4><div class="seg">${btn(`Lease an IRU <small>${fmt$(dfLeaseMo(km))}/mo · ready in 30 days</small>`,'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${btn(lvl()>=3?`Build your own <small>${fmt$(dfBuildCost(km))} · ~${dfBuildDays(km)} days</small>`:'Build your own <small>level 3</small>','dfSrc',{v:'build'},src==='build'?'pink':'ghost',lvl()<3)}</div>
${src==='build'?`<p class="note">Your own trench: almost no rent, but permits and digging take forever, and delays happen.</p>`:''}
<h4 class="sub4">Line system</h4><div class="seg">${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} <small>${DF_SYS[k].lvl>lvl()?'level '+DF_SYS[k].lvl:fmt$(DF_SYS[k].cost)}</small>`,'dfSys',{v:k},sys===k?'pink':'ghost',DF_SYS[k].lvl>lvl())).join('')}</div>
<p class="note">${esc(DF_SYS[sys].blurb)} Plus ${amps} in-line amplifier${amps===1?'':'s'} (${fmt$(AMP_COST)} each, ${fmt$(AMP_MO)}/mo for hut rent and power).</p>
<div class="kv" style="margin-top:10px"><span>Due now</span><b>${fmt$(up)}</b></div><div class="kv"><span>Monthly</span><b>${fmt$(mo)}/mo</b></div>
<p class="note">For comparison, a leased 1.6T wave on this route is ${fmt$(w)}/mo. Optics come next, from the link panel.</p>
<div class="btns" style="margin-top:10px">${btn(`${src==='build'?'Start construction':'Sign the IRU'} <small>${fmt$(up)}</small>`,'orderDf',{},'pink big',S.cash<up)}</div>`;
}
function openVxcModal({from,to,prov}){
let rows='';const row=(f,a,b)=>{const km=kmBetween(a,b),sub=isSub(a,b),pb=S.pops[b]?nniPort(b,f.id):null,remote=!S.pops[b];
const label=remote?`Remote peering at ${cityIxes(b).map(k=>esc(ixName(k))).join(' or ')} · discouraged`:pb?'Your POP':'Your POP · needs a fabric port there';
const freeA=nniPort(a,f.id)?NNI[nniPort(a,f.id).tier].g-nniUsed(a,f.id):0,freeB=remote?1e9:pb?NNI[pb.tier].g-nniUsed(b,f.id):0;
return `<div class="row"><span class="logo" style="--c:${f.col}">${initials(f)}</span><div class="grow"><div class="nm">${CITY[a].name} → ${CITY[b].name}</div><div class="meta">${label} · ${km.toLocaleString()} km${sub?' subsea':''}</div>
<div class="btns">${VXC.map((V,t)=>btn(`${V.n} <small>${fmt$(vxcMo(km,sub,t))}/mo</small>`,'buyVxc',{a,b,prov:f.id,t},'sm',(!remote&&!pb)||V.g>freeA||V.g>freeB||S.cash<vxcMo(km,sub,t))).join('')}</div></div></div>`;};
for(const f of FABS){if(prov&&f.id!==prov)continue;
if(from){if(!nniPort(from,f.id))continue;for(const b of f.cities){if(b===from)continue;if(!S.pops[b]&&!CITY[b].ix)continue;rows+=row(f,from,b);}}
else if(to&&f.cities.includes(to)){for(const a of Object.keys(S.pops))if(a!==to&&nniPort(a,f.id))rows+=row(f,a,to);}}
if(!rows){const fs=FABS.filter(f=>!to||f.cities.includes(to));rows=`<p class="empty">You need a fabric port at one of your POPs first. Open a POP's Infra tab and buy a port on ${fs.map(f=>`<b>${esc(f.name)}</b> (${f.cities.filter(c=>S.pops[c]).map(c=>CITY[c].name).join(', ')||'no POP of yours on it yet'})`).join(', ')}.</p>`;}
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Virtual circuit over an NNI fabric</div><h2 style="font-size:26px">${from?`From ${CITY[from].name}`:`To ${CITY[to].name}`}</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>
<p class="lead" style="margin-top:8px">No install fee, live in minutes, billed monthly. Cheaper than a wave for small capacity, but it rides someone else's fabric, and that fabric can fail.</p>${rows}`);
}
/* ================= CANVAS ================= */
const cv=$('map'),ctx=cv.getContext('2d');
const cam={x:1050,y:330,z:0.8};
let CW=0,CH=0,DPR=1;
function resize(){DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;}
addEventListener('resize',()=>{resize();WL.key=null;renderLeft();});resize();
function rng(seed){return()=>{seed|=0;seed=seed+0x6D2B79F5|0;let t=Math.imul(seed^seed>>>15,1|seed);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}
function inPoly(x,y,pts){let ins=false;for(let i=0,j=pts.length-1;i<pts.length;j=i++){const [xi,yi]=pts[i],[xj,yj]=pts[j];if(((yi>y)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;}
function smoothPath(pts){const p=new Path2D();const n=pts.length;const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(pts[n-1],pts[0]);p.moveTo(m[0],m[1]);for(let i=0;i<n;i++){const nx=pts[(i+1)%n];m=mid(pts[i],nx);p.quadraticCurveTo(pts[i][0],pts[i][1],m[0],m[1]);}p.closePath();return p;}
const LANDP=LANDS.map(l=>smoothPath(l.pts)).concat(DECOR.map(smoothPath));
const ALLPOLY=LANDS.map(l=>l.pts).concat(DECOR);
const onLand=(x,y)=>ALLPOLY.some(p=>inPoly(x,y,p));
const R1=rng(7),WAVES=[],HILLS=[];
while(WAVES.length<220){const x=R1()*W,y=R1()*H;if(!onLand(x,y)&&!onLand(x+12,y)&&!onLand(x-12,y))WAVES.push([x,y,R1()]);}
while(HILLS.length<130){const x=R1()*W,y=R1()*H;if(LANDS.some(l=>inPoly(x,y,l.pts))&&!CITIES.some(c=>Math.hypot(c.x-x,c.y-y)<40))HILLS.push([x,y,6+R1()*10,R1()]);}
const CLOUDS=Array.from({length:7},(_,i)=>({x:R1()*W,y:60+R1()*(H-120),s:.7+R1()*.6,v:3+R1()*4}));
const FLOATS=[];
function floater(x,y,text,col){FLOATS.push({x,y,text,col,t:performance.now()});}
const toS=(wx,wy,k=0)=>[(wx+k*W-cam.x)*cam.z+CW/2,(wy-cam.y)*cam.z+CH/2];
const iconScale=()=>clamp(Math.sqrt(cam.z),0.7,1.35);
function rr(x,y,w,h,r){ctx.beginPath();ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();}
function visibleKs(){const ks=[];for(const k of [-1,0,1]){const a=toS(0,0,k)[0],b=toS(W,0,k)[0];if(b>-200&&a<CW+200)ks.push(k);}return ks;}
const GEO=new Map();
function linkGeom(l){const i=pairLinks(l.a,l.b).indexOf(l);const key=l.id+'|'+i+'|'+(l.cable||'');const h=GEO.get(key);if(h)return h;
let pts=null;if(l.cable){const cp=cablePair(l.cable,l.a,l.b);if(cp){pts=cp.pts.map(p=>p.slice());const same=pairLinks(l.a,l.b).filter(x=>x.cable===l.cable).indexOf(l);if(same>0)for(let j=1;j<pts.length-1;j++){pts[j][1]+=same*5;}}}
if(!pts){const g=bezGeom(l);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));}
const cum=[0];let L=0;for(let j=1;j<pts.length;j++){L+=Math.hypot(pts[j][0]-pts[j-1][0],pts[j][1]-pts[j-1][1]);cum.push(L);}for(let j=0;j<cum.length;j++)cum[j]/=L||1;
const g={pts,cum,len:L};GEO.set(key,g);return g;}
function polyAt(sp,cum,t){let i=1;while(i<cum.length-1&&cum[i]<t)i++;const t0=cum[i-1],t1=cum[i],f=t1>t0?(t-t0)/(t1-t0):0;return [sp[i-1][0]+(sp[i][0]-sp[i-1][0])*f,sp[i-1][1]+(sp[i][1]-sp[i-1][1])*f];}
function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const t=clamp(((x-a[0])*dx+(y-a[1])*dy)/L,0,1);return Math.hypot(x-a[0]-t*dx,y-a[1]-t*dy);}
function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!worldLayer(z);
if(!selC&&z<1.7&&cached)return;
ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';
for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;const col=cableCol(C);
for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}if(mx<-20||mn>CW+20)continue;
if(hot||!cached){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);ctx.stroke();ctx.setLineDash([]);}
if(hot||z>=1.7){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);}
ctx.globalAlpha=1;}}}
function bezGeom(l){const A=CITY[l.a],B=CITY[l.b];const i=pairLinks(l.a,l.b).indexOf(l);const key=l.id+'|'+i;const hit=GEO.get(key);if(hit)return hit;
const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;}
const base=Math.max(10,Math.min(len*0.13,110)),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*16);
const mx=(A.x+bx)/2,my=(A.y+by)/2;
const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]);
const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(d<m)m=d;}}return m;};
const sg=Math.sign(off0)||1,mag=Math.abs(off0);
const cand=[1,1.5,2.1,2.9,3.8].map(k=>sg*mag*k).concat([1,1.5,2.1,2.9,3.8].map(k=>-sg*Math.max(mag,base)*k));
let best=null,bc=-1;
for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=24){best=[cx,cy];break;}if(c>bc){bc=c;best=[cx,cy];}}
const g={ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};GEO.set(key,g);return g;}
const qpt=(g,t)=>[(1-t)*(1-t)*g.ax+2*(1-t)*t*g.cx+t*t*g.bx,(1-t)*(1-t)*g.ay+2*(1-t)*t*g.cy+t*t*g.by];
const utilCol=u=>u<=0.001?'#AFC0D6':u<0.65?'#22C47A':u<0.9?'#FFAA1F':'#FF4D5E';
function draw(now){
if(!ctx)return;
ctx.setTransform(DPR,0,0,DPR,0,0);
// sea
const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,'#62CBEA');g.addColorStop(1,'#43AED6');ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH);
const ks=visibleKs(),z=cam.z;
const wl=worldLayer(z);
for(const k of ks){
ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));
// waves: one path, one stroke
ctx.strokeStyle='rgba(255,255,255,.45)';ctx.lineWidth=2/z;ctx.lineCap='round';ctx.beginPath();
const ph0=now/900;for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;ctx.moveTo(x-9+o,y);ctx.quadraticCurveTo(x-4.5+o,y-4,x+o,y);ctx.quadraticCurveTo(x+4.5+o,y+4,x+9+o,y);}ctx.stroke();
if(wl){ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(wl.cv,Math.round(DPR*((k*W-cam.x)*z+CW/2)),Math.round(DPR*((-cam.y)*z+CH/2)));ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));}else paintWorld(ctx,z,true);
// clouds
ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();
for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100,y=c.y;ctx.moveTo(x+16*c.s,y);ctx.arc(x,y,16*c.s,0,7);ctx.moveTo(x+38*c.s,y-8*c.s);ctx.arc(x+18*c.s,y-8*c.s,20*c.s,0,7);ctx.moveTo(x+55*c.s,y);ctx.arc(x+40*c.s,y,15*c.s,0,7);}ctx.fill();
}
ctx.setTransform(DPR,0,0,DPR,0,0);
if(!S)return;
const sc=iconScale(),day=S.day;
// cable systems
drawCables(ks);
// links
for(const l of S.links){
const gm=linkGeom(l),cap=capOf(l),load=R.load[l.id]||0,u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&linkDown(l)&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc';
const sel=UI.sel&&UI.sel.type==='link'&&UI.sel.id===l.id;
const w=(vx?2.2:(2.5+tierW(l)*1.8))*sc;
for(const k of ks){
const sp=gm.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}
if(mx<-40||mn>CW+40)continue;
const path=()=>{ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);};
ctx.lineCap='round';ctx.lineJoin='round';
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:[]);path();ctx.stroke();
ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
if(df&&!bld&&!dark){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);path();ctx.stroke();ctx.setLineDash([]);}
const at=t=>polyAt(sp,gm.cum,t);
if(!cut&&load>0.01){const n=clamp(Math.round(2+u*10),2,12),len=gm.len*z,spd=90;
ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;
const rr2=Math.max(2.2,w*.42),base=now/1000*spd/Math.max(len,40);ctx.beginPath();for(let i=0;i<n;i++){let t=(base+i/n)%1;if(i%2)t=1-t;const [px,py]=at(t);ctx.moveTo(px+rr2,py);ctx.arc(px,py,rr2,0,7);}ctx.fill();ctx.stroke();}
const [mx2,my]=at(.5);const mxx=mx2;
if(bld){drawCone(mxx,my,now);}
else if(cut&&!vx){drawBackhoe(mxx,my,now,l.sub);}
else if(z>0.9||sel){const t=capName(l);ctx.font='800 11px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+10;ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
}
}
// drag preview
if(UI.drag&&UI.drag.mode==='link'){
const A=CITY[UI.drag.from];let tx=UI.drag.cx,ty=UI.drag.cy;
if(UI.snap){const sv=UI.snap;tx=sv.sx;ty=sv.sy;}
let [ax,ay]=toS(A.x,A.y,0);if(UI.snap){const B=CITY[UI.snap.id];const bxw=A.x+wrapDx(A.x,B.x);[tx,ty]=toS(bxw,B.y,0);}else{/* nearest copy of origin to cursor */for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k);if(Math.abs(px-tx)<Math.abs(ax-tx)){ax=px;ay=py;}}}
if(UI.snap){const B=CITY[UI.snap.id];const wx=A.x+wrapDx(A.x,B.x);for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k),[qx]=toS(wx,B.y,k);if(Math.abs(qx-CW/2)<Math.abs(tx-CW/2)){ax=px;ay=py;tx=qx;}}}
ctx.strokeStyle='#1E2640';ctx.lineWidth=7;ctx.lineCap='round';ctx.setLineDash([2,12]);ctx.beginPath();ctx.moveTo(ax,ay);ctx.lineTo(tx,ty);ctx.stroke();
ctx.strokeStyle='#FF4F9A';ctx.lineWidth=4;ctx.lineDashOffset=-now/30;ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;
if(UI.snap&&UI.snap.id!==UI.drag.from){const b=UI.snap.id,km=kmBetween(UI.drag.from,b),sub=isSub(UI.drag.from,b);
const t=`${km.toLocaleString()} km${sub?' · subsea':''} · ${sub&&!cablesFor(UI.drag.from,b).length?'no cable lands here':'from '+fmt$(waveMo(km,sub,0))+'/mo'}`;
ctx.font='800 13px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+18;const lx=(ax+tx)/2,ly=(ay+ty)/2-22;
ctx.fillStyle='#1E2640';rr(lx-tw/2,ly-12,tw,24,12);ctx.fill();ctx.fillStyle='#fff';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,lx,ly+1);}
}
// cities
UI.feed=null;if(UI.sel&&UI.sel.type==='link'){const sl=S.links.find(x=>x.id===UI.sel.id);const rec=sl&&R.ef[edgeKey(sl)];if(rec){UI.feed=new Set(Object.keys(rec.eg).map(k=>R.egDesc[k].city));UI.dest=new Set(Object.keys(rec.dst));}}
// Place labels: your POPs and the selected city first, then others; a label that would overlap moves above its city or hides.
const vis=[];for(const C of CITIES)for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}
const prio=v=>(UI.sel&&UI.sel.type==='city'&&UI.sel.id===v.C.id?0:S.pops[v.C.id]?1:2);vis.sort((a,b)=>prio(a)-prio(b)||b.C.P-a.C.P);
const rects=[],hit=(r)=>rects.some(q=>r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h);
for(const v of vis){const h=(12+Math.sqrt(v.C.P)*0.75)*sc;rects.push({x:v.sx-18*sc,y:v.sy-h-4*sc,w:40*sc,h:h+14*sc});}
for(const v of vis){const p=S.pops[v.C.id];ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const tw=(LBLW[v.C.id+(p?1:0)]||(LBLW[v.C.id+(p?1:0)]=ctx.measureText(v.C.name).width+14));
const h=12+Math.sqrt(v.C.P)*0.75;const below=v.sy+16*sc+8,above=v.sy-h*sc-17*sc;let ly=null;
for(const y of [below,above]){const r={x:v.sx-tw/2-2,y:y-10,w:tw+4,h:21};if(!hit(r)){ly=y;rects.push(r);break;}}
if(ly===null&&prio(v)<2){ly=below;rects.push({x:v.sx-tw/2,y:below-10,w:tw,h:21});}
v.ly=ly;}
for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly);
// floaters
for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;}
for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}}
}
function drawCone(x,y,now){const b=Math.sin(now/300)*1.5;ctx.save();ctx.translate(x,y-12+b);ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();ctx.restore();}
// Static land + cable map, rendered once per zoom bucket into an offscreen canvas.
function paintWorld(c,z,withCables){
for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();}
c.strokeStyle='#F8E6A8';c.lineWidth=10/z;c.lineJoin='round';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();}
c.fillStyle='#9BDA6C';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.fill(p);c.restore();}
c.fillStyle='#86CB5B';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x+r*1.4,y);c.ellipse(x,y,r*1.4,r*.8,0,0,Math.PI*2);}c.fill();
c.fillStyle='rgba(255,255,255,.18)';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x-r*.3+r*.6,y-r*.25);c.ellipse(x-r*.3,y-r*.25,r*.6,r*.3,0,0,Math.PI*2);}c.fill();
c.strokeStyle='#1E2640';c.lineWidth=2.5/z;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();}
if(withCables)for(const off of [0,W,-W]){c.save();c.translate(off,0);for(const cp of CABLE_PAIRS){const C=CAB[cp.cid];c.globalAlpha=0.4;c.strokeStyle=cableCol(C);c.lineWidth=1.6/z;c.lineJoin='round';c.setLineDash(C.age==='old'?[6/z,5/z]:[]);c.beginPath();c.moveTo(cp.pts[0][0],cp.pts[0][1]);for(let i=1;i<cp.pts.length;i++)c.lineTo(cp.pts[i][0],cp.pts[i][1]);c.stroke();}c.restore();}
c.globalAlpha=1;c.setLineDash([]);
}
const WL={key:null,cv:null,zAt:0,lastZ:0};const MAXPX=4096;
// Cache at the exact on-screen scale, so drawing it is a plain copy. While the zoom is changing we draw vectors instead.
function worldLayer(z){
const now=performance.now();if(z!==WL.lastZ){WL.lastZ=z;WL.zAt=now;}
const sc=z*DPR,key=sc.toFixed(4);if(WL.key===key)return WL;
if(W*sc>MAXPX||now-WL.zAt<250)return null;
const cv2=WL.cv||document.createElement('canvas');cv2.width=Math.ceil(W*sc)+2;cv2.height=Math.ceil(H*sc)+2;
const c=cv2.getContext('2d');if(!c)return null;c.setTransform(sc,0,0,sc,0,0);paintWorld(c,z,true);WL.cv=cv2;WL.key=key;return WL;
}
function cableCol(C){return C.price<=0.85?'#14A88C':C.price<=1.1?'#2F7BEA':'#A05AE0';}
function drawBackhoe(x,y,now,sub){
const b=Math.sin(now/180)*2;ctx.save();ctx.translate(x,y-14+b);
ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2;
if(sub){ // shark fin
ctx.fillStyle='#6B7C99';ctx.beginPath();ctx.moveTo(-12,8);ctx.quadraticCurveTo(-2,-14,10,-12);ctx.quadraticCurveTo(4,-2,12,8);ctx.closePath();ctx.fill();ctx.stroke();
}else{
ctx.fillStyle='#FFD23F';rr(-12,-4,18,12,3);ctx.fill();ctx.stroke();rr(-8,-12,10,9,2);ctx.fillStyle='#BDE8FF';ctx.fill();ctx.stroke();
ctx.beginPath();ctx.moveTo(6,0);ctx.lineTo(14,-10);ctx.lineTo(19,2);ctx.stroke();ctx.fillStyle='#1E2640';ctx.beginPath();ctx.arc(-7,10,3,0,7);ctx.arc(2,10,3,0,7);ctx.fill();
}
ctx.restore();
}
const LBLW={};
function drawCity(C,sx,sy,sc,now,lyOverride){
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
const k=sc*(hov?1.15:1);
ctx.save();ctx.translate(sx,sy);
if(UI.feed&&UI.feed.has(C.id)){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);}
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);}
if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){const a=.35+.25*Math.sin(now/200);ctx.fillStyle=`rgba(255,77,94,${a})`;ctx.beginPath();ctx.arc(0,-6*k,26*k,0,7);ctx.fill();}
ctx.scale(k,k);
ctx.fillStyle='rgba(30,38,64,.2)';ctx.beginPath();ctx.ellipse(0,9,20,5,0,0,7);ctx.fill();
const h=12+Math.sqrt(C.P)*0.75;
const bl=[[-15,h*.65,'#FFFFFF'],[-5,h,'#FFE7A1'],[5,h*.5,'#BDE8FF']];
ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2;
for(const [x,hh,col] of bl){ctx.fillStyle=col;rr(x,8-hh,10,hh,2);ctx.fill();ctx.stroke();}
ctx.fillStyle='rgba(30,38,64,.35)';ctx.beginPath();for(const [x,hh] of bl)for(let yy=8-hh+4;yy<5;yy+=5){ctx.rect(x+2.5,yy,2,2);ctx.rect(x+5.5,yy,2,2);}ctx.fill();
if(p){
ctx.translate(0,2);
ctx.lineWidth=2.4;ctx.beginPath();ctx.moveTo(-10,-6);ctx.lineTo(-13,-17);ctx.moveTo(10,-6);ctx.lineTo(13,-17);ctx.stroke();
ctx.fillStyle=down?'#FF4D5E':'#FFD23F';ctx.beginPath();ctx.arc(-13,-18,2.6,0,7);ctx.arc(13,-18,2.6,0,7);ctx.fill();ctx.stroke();
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-13,-13,34,16,6);ctx.fill();ctx.stroke();}
if(p.gen){ctx.fillStyle='#FFD23F';rr(-27,-1,9,11,2);ctx.fill();ctx.stroke();}
ctx.fillStyle=down?'#8A91A8':'#FF4F9A';rr(-17,-7,34,16,6);ctx.fill();ctx.stroke();
if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const t=(now/700+i/3)%1;ctx.fillStyle=`rgba(90,98,130,${0.55*(1-t)})`;ctx.beginPath();ctx.arc(6+i*3,-12-t*18,3+t*4,0,7);ctx.fill();}}
if((p.rgen||0)>0){ctx.fillStyle='#FFD23F';ctx.beginPath();ctx.arc(17,-7,6,0,7);ctx.fill();ctx.lineWidth=1.8;ctx.stroke();ctx.fillStyle='#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(String((p.rgen||0)+1),17,-6.5);ctx.lineWidth=2.2;}
const sf=sfOf(R,C.id);
for(let i=0;i<4;i++){const on=down?false:(((now/(160+i*37))|0)+i)%3!==0;ctx.fillStyle=down?'#3B4260':on?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';ctx.beginPath();ctx.arc(-10+i*6.6,1,2.1,0,7);ctx.fill();}
if(down){ctx.fillStyle='#fff';ctx.font='900 14px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.fillText('zzz',20,-14);}
ctx.translate(0,-2);
}
const ixn=ixName(C.id);
if(ixn){const mine=!!S.myIx[C.id],joined=cityIxes(C.id).some(k=>S.ixp[k]!==undefined);ctx.fillStyle=mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(19+8.5*Math.cos(a),-h+2+8.5*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=2;ctx.stroke();
ctx.fillStyle=mine?'#fff':'#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',19,-h+2.5);}
const off=S.offers.some(o=>bCities(o).includes(C.id));
if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=S.offers.some(o=>bCities(o).includes(C.id)&&(BIZ_T[o.type].lv>=3||BIZ_T[o.type].event));ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);}
const inc=S.inc.some(i=>(IXDOWN.includes(i.type)?ixCity(i.ref):i.ref)===C.id&&i.type!=='leak');
if(inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
ctx.restore();
// label
if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){
ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=ctx.measureText(t).width+14,ly=lyOverride==null?sy+16*sc+8:lyOverride;
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(sx-tw/2,ly-9,tw,19,9);ctx.fill();ctx.stroke();
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);
}
}
/* ---------- hit tests & input ---------- */
function hitCity(x,y,r=28){let best=null,bd=r*iconScale();for(const C of CITIES)for(const k of [-1,0,1]){const [sx,sy]=toS(C.x,C.y,k);const d=Math.hypot(sx-x,sy+4-y);if(d<bd){bd=d;best={id:C.id,sx,sy};}}return best;}
function hitLink(x,y){if(!S)return null;let best=null,bd=12;for(const l of S.links){const g=linkGeom(l);for(const k of [-1,0,1]){let prev=null;for(const p of g.pts){const q=toS(p[0],p[1],k);if(prev){const d=segDist(x,y,prev,q);if(d<bd){bd=d;best=l.id;}}prev=q;}}}return best;}
function wrapCam(){cam.x=((cam.x%W)+W)%W;cam.y=clamp(cam.y,0,H);}
const ptrs=new Map();
cv.addEventListener('pointerdown',e=>{audioInit();cv.setPointerCapture(e.pointerId);ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(ptrs.size===2){const [a,b]=[...ptrs.values()];UI.drag={mode:'pinch',d0:Math.hypot(a.x-b.x,a.y-b.y)||1,z0:cam.z};return;}
const hit=S&&hitCity(e.clientX,e.clientY);
if(hit&&S.pops[hit.id])UI.drag={mode:'maybeLink',from:hit.id,sx:e.clientX,sy:e.clientY,camx:cam.x,camy:cam.y,moved:false};
else UI.drag={mode:'pan',sx:e.clientX,sy:e.clientY,camx:cam.x,camy:cam.y,moved:false};
});
cv.addEventListener('pointermove',e=>{
if(ptrs.has(e.pointerId))ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
const d=UI.drag;
if(!d){const h=S&&hitCity(e.clientX,e.clientY);UI.hover=h?h.id:null;cv.style.cursor=h?(S.pops[h.id]?'crosshair':'pointer'):(hitLink(e.clientX,e.clientY)?'pointer':'grab');return;}
if(d.mode==='pinch'&&ptrs.size===2){const [a,b]=[...ptrs.values()];const mx=(a.x+b.x)/2,my=(a.y+b.y)/2;zoomAt(mx,my,clamp(d.z0*Math.hypot(a.x-b.x,a.y-b.y)/d.d0,0.35,3)/cam.z);return;}
const dx=e.clientX-d.sx,dy=e.clientY-d.sy;if(Math.hypot(dx,dy)>6)d.moved=true;
if(d.mode==='maybeLink'&&d.moved){d.mode='link';cv.classList.add('linking');}
if(d.mode==='link'){d.cx=e.clientX;d.cy=e.clientY;const h=hitCity(e.clientX,e.clientY,40);UI.snap=h&&h.id!==d.from?h:null;renderHint();}
else if(d.mode==='pan'&&d.moved){cam.x=d.camx-dx/cam.z;cam.y=d.camy-dy/cam.z;wrapCam();cv.style.cursor='grabbing';}
});
function endPtr(e){
ptrs.delete(e.pointerId);const d=UI.drag;if(!d)return;
if(d.mode==='pinch'){if(ptrs.size===0)UI.drag=null;return;}
if(d.mode==='link'){if(UI.snap&&UI.snap.id!==d.from){openLinkModal(d.from,UI.snap.id);sfx('click');}}
else if(!d.moved&&S){const h=hitCity(e.clientX,e.clientY);
if(h){selectCity(h.id);sfx('click');}
else{const l=hitLink(e.clientX,e.clientY);if(l){UI.sel={type:'link',id:l};UI.confirm=null;renderPanel();sfx('click');}else{UI.sel=null;renderPanel();}}}
UI.drag=null;UI.snap=null;cv.classList.remove('linking');cv.style.cursor='grab';renderHint();
}
cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',endPtr);
function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,0.35,3);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();}
cv.addEventListener('wheel',e=>{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false});
addEventListener('keydown',e=>{if(e.target.tagName==='INPUT')return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});
/* ---------- click delegation ---------- */
let pressing=false;
document.addEventListener('pointerdown',e=>{if(e.target.closest('#panel,#left'))pressing=true;});
addEventListener('pointerup',()=>setTimeout(()=>pressing=false,0));
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','pickStart','cont','help','helpClose','newgame','mute','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
/* ================= LOOP ================= */
let last=performance.now(),acc=0,hudT=0;
function frame(now){
const dt=Math.min(250,now-last);last=now;
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4){acc-=DAY_MS;dayTick();n++;}
if(n){renderHUD();if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}}
draw(now);
if(!window.__TUBES_TEST__)requestAnimationFrame(frame);
}
function boot(data){
try{UI.muted=localStorage.getItem('sot-mute')==='1';}catch(e){}
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
else{const sv=loadSave();
if(sv){S=migrate(sv);UI.started=true;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
compute();renderAll();if(!whatsNew(true))toast(`<b>Welcome back, ${esc(S.name)}.</b><br>Your network is right where you left it: ${dateStr(S.day)}.`,'good');}
else{showTitle();whatsNew(false);}}
renderHUD();renderLeft();
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
}
window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {});
</script>
</body>
</html>