diff --git a/public/css/app.css b/public/css/app.css
new file mode 100644
index 0000000..4c4c122
--- /dev/null
+++ b/public/css/app.css
@@ -0,0 +1,288 @@
+/* Elorasmus: mobile-first. Light/dark via tokens; data-theme on overrides the system. */
+
+:root {
+ --bg: #f6f4ef; --surface: #ffffff; --surface-2: #eeebe3; --text: #1b1f24; --muted: #5f6873; --line: #e1ddd3;
+ --accent: #2d5bd7; --accent-text: #ffffff;
+ --a: #0f7f75; --a-soft: #d8efeb; --b: #b4570f; --b-soft: #f9e4d1;
+ --good: #1d7a43; --warn: #9a6400; --bad: #c0352e;
+ --radius: 14px; --shadow: 0 1px 2px rgb(0 0 0 / .06), 0 6px 20px rgb(0 0 0 / .06);
+ --max: 760px; --gutter: 16px;
+ color-scheme: light;
+}
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) {
+ --bg: #111418; --surface: #1a1e24; --surface-2: #252b33; --text: #e8eaed; --muted: #9aa4ae; --line: #2d343d;
+ --accent: #7ea2ff; --accent-text: #0c1222;
+ --a: #3fc4b4; --a-soft: #153532; --b: #f2a45f; --b-soft: #3b2715;
+ --good: #5fcf8c; --warn: #f0b94e; --bad: #ff7d74;
+ --shadow: 0 1px 2px rgb(0 0 0 / .4), 0 6px 20px rgb(0 0 0 / .3);
+ color-scheme: dark;
+ }
+}
+:root[data-theme="dark"] {
+ --bg: #111418; --surface: #1a1e24; --surface-2: #252b33; --text: #e8eaed; --muted: #9aa4ae; --line: #2d343d;
+ --accent: #7ea2ff; --accent-text: #0c1222;
+ --a: #3fc4b4; --a-soft: #153532; --b: #f2a45f; --b-soft: #3b2715;
+ --good: #5fcf8c; --warn: #f0b94e; --bad: #ff7d74;
+ --shadow: 0 1px 2px rgb(0 0 0 / .4), 0 6px 20px rgb(0 0 0 / .3);
+ color-scheme: dark;
+}
+
+* { box-sizing: border-box; }
+html { -webkit-text-size-adjust: 100%; }
+body {
+ margin: 0; background: var(--bg); color: var(--text);
+ font: 16px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ overflow-x: hidden;
+}
+a { color: var(--accent); }
+button { font: inherit; color: inherit; }
+h1, h2, h3 { line-height: 1.2; margin: 0 0 .4em; }
+h1 { font-size: 1.35rem; } h2 { font-size: 1.05rem; } h3 { font-size: .95rem; }
+p { margin: .4em 0; }
+ul, ol { margin: .3em 0; padding-left: 1.2em; }
+.muted { color: var(--muted); }
+.small { font-size: .82rem; }
+.loading { padding: 40px var(--gutter); text-align: center; color: var(--muted); }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+/* ---------- top bar ---------- */
+.topbar {
+ position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 8px;
+ padding: 6px var(--gutter); padding-top: calc(6px + env(safe-area-inset-top));
+ background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: blur(10px);
+ border-bottom: 1px solid var(--line);
+}
+.brand { display: flex; align-items: center; gap: 8px; font-weight: 700; color: var(--text); text-decoration: none; }
+.picks { color: var(--muted); font-size: .8rem; display: none; }
+.tabs { margin-left: auto; display: flex; gap: 2px; }
+.tabs a {
+ display: flex; flex-direction: column; align-items: center; gap: 1px; min-width: 52px; padding: 4px 6px;
+ border-radius: 10px; color: var(--muted); text-decoration: none; font-size: .68rem;
+}
+.tabs a svg { width: 22px; height: 22px; }
+.tabs a.active { color: var(--accent); background: var(--surface); box-shadow: var(--shadow); }
+body.logged-out .tabs { display: none; }
+
+.view { max-width: var(--max); margin: 0 auto; padding: 12px var(--gutter) 24px; }
+
+/* ---------- shared bits ---------- */
+.btn {
+ display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 44px; padding: 0 16px;
+ border: 0; border-radius: 12px; background: var(--accent); color: var(--accent-text); font-weight: 600;
+ text-decoration: none; cursor: pointer;
+}
+.btn.ghost { background: var(--surface); color: var(--text); border: 1px solid var(--line); }
+.link { background: none; border: 0; padding: 6px 0; color: var(--accent); cursor: pointer; text-decoration: underline; }
+.chip {
+ display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: .74rem; background: var(--surface-2);
+ color: var(--muted); white-space: nowrap;
+}
+.chip.warn { background: color-mix(in srgb, var(--warn) 18%, transparent); color: var(--warn); }
+.notice { padding: 10px 12px; border-radius: 12px; background: var(--surface-2); }
+.empty { text-align: center; padding: 40px 0; }
+
+.bar { display: inline-block; width: 46px; height: 6px; border-radius: 3px; background: var(--surface-2); vertical-align: middle; overflow: hidden; }
+.bar > i { display: block; height: 100%; background: var(--accent); border-radius: 3px; }
+.num { margin-left: 6px; font-variant-numeric: tabular-nums; }
+.w0 { width: 0; } .w1 { width: 10%; } .w2 { width: 20%; } .w3 { width: 30%; } .w4 { width: 40%; } .w5 { width: 50%; }
+.w6 { width: 60%; } .w7 { width: 70%; } .w8 { width: 80%; } .w9 { width: 90%; } .w10 { width: 100%; }
+
+.tone-ok, .tone-best, .tone-good { color: var(--good); }
+.tone-fail, .tone-none, .tone-poor { color: var(--bad); }
+.tone-unknown, .tone-weak { color: var(--warn); }
+b.tone-ok { color: var(--good); }
+
+/* ---------- duel ---------- */
+.duel { padding-bottom: 150px; }
+.prompt { margin: 0 0 8px; color: var(--muted); font-size: .85rem; text-align: center; }
+.duel-heads { display: grid; grid-template-columns: 1fr auto 1fr; gap: 6px; align-items: stretch; }
+.vs { align-self: center; font-weight: 700; color: var(--muted); font-size: .8rem; }
+.school-head {
+ position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 2px; text-align: left;
+ padding: 10px 10px 10px; border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow);
+ border: 2px solid transparent; cursor: pointer; min-width: 0;
+}
+.school-head.side-a { border-color: var(--a); }
+.school-head.side-b { border-color: var(--b); }
+.side-tag {
+ display: inline-grid; place-items: center; width: 20px; height: 20px; border-radius: 6px; font-size: .72rem; font-weight: 800;
+ color: #fff;
+}
+.side-a .side-tag { background: var(--a); }
+.side-b .side-tag { background: var(--b); }
+.school-head .side-tag { position: absolute; top: 8px; right: 8px; }
+.school-head .flag { font-size: 1.5rem; line-height: 1; }
+.sname { font-weight: 700; font-size: .98rem; line-height: 1.2; overflow-wrap: anywhere; padding-right: 18px; }
+.splace { color: var(--muted); font-size: .78rem; line-height: 1.25; }
+.srating { margin-top: 4px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.srating small { display: block; font-weight: 400; color: var(--muted); font-size: .72rem; }
+.provisional { opacity: .75; }
+
+.cmp { margin-top: 10px; background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 4px 10px 8px; }
+.cmp-section {
+ grid-column: 1 / -1; margin-top: 10px; padding: 2px 0; font-size: .7rem; letter-spacing: .06em; text-transform: uppercase;
+ color: var(--muted); font-weight: 700;
+}
+.cmp-row {
+ display: grid; grid-template-columns: minmax(84px, .9fr) 1fr 1fr; gap: 6px; align-items: center;
+ padding: 3px 0; border-top: 1px solid var(--line); font-size: .86rem;
+}
+.cmp-section + .cmp-row { border-top: 0; }
+.cmp-label { color: var(--muted); font-size: .8rem; line-height: 1.2; }
+.cmp-val { padding: 4px 6px; border-radius: 8px; min-width: 0; overflow-wrap: anywhere; line-height: 1.25; }
+.cmp-val .bar { width: 38px; }
+.cmp-val .bar > i { background: var(--muted); opacity: .55; }
+.cmp-val.win .bar > i { opacity: 1; }
+.win-a { background: var(--a-soft); }
+.win-b { background: var(--b-soft); }
+.win-a .bar > i { background: var(--a); }
+.win-b .bar > i { background: var(--b); }
+.win { font-weight: 600; }
+
+.duel-flags { display: grid; gap: 10px; margin-top: 12px; }
+.flags { background: var(--surface); border-radius: var(--radius); padding: 10px 12px; box-shadow: var(--shadow); border-left: 4px solid; }
+.flags.side-a { border-left-color: var(--a); }
+.flags.side-b { border-left-color: var(--b); }
+.flags h3 { display: flex; align-items: center; gap: 6px; }
+.flags .summary { font-size: .88rem; }
+.flags ul { list-style: none; padding: 0; font-size: .86rem; }
+.flags li, .hl-list li, .wo-list li { padding-left: 1.3em; position: relative; margin: .25em 0; }
+.flags li::before, .hl-list li::before, .wo-list li::before { position: absolute; left: 0; font-weight: 700; }
+.flags li.hl::before, .hl-list li::before { content: "+"; color: var(--good); }
+.flags li.wo::before, .wo-list li::before { content: "!"; color: var(--bad); left: .25em; }
+.hl-list, .wo-list { list-style: none; padding: 0; }
+.duel-drop { display: flex; justify-content: space-between; margin-top: 10px; font-size: .82rem; }
+
+/* ---------- bottom action bar ---------- */
+.actionbar {
+ position: fixed; left: 0; right: 0; bottom: 0; z-index: 15; background: var(--surface); border-top: 1px solid var(--line);
+ box-shadow: 0 -6px 20px rgb(0 0 0 / .08); padding: 6px var(--gutter) calc(10px + env(safe-area-inset-bottom));
+}
+.actionbar > div { max-width: var(--max); margin: 0 auto; }
+.actionbar-sub { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px !important; }
+.ghost { background: none; border: 0; padding: 6px 4px; color: var(--accent); cursor: pointer; font-weight: 600; font-size: .9rem; }
+.ghost:disabled { color: var(--muted); opacity: .5; cursor: default; }
+.actionbar-main { display: grid; grid-template-columns: 1fr 56px 1fr; gap: 8px; }
+.pick {
+ min-height: 54px; border: 0; border-radius: 14px; font-weight: 700; font-size: .95rem; cursor: pointer; padding: 0 10px;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #fff;
+}
+.pick span { display: inline-grid; place-items: center; width: 22px; height: 22px; border-radius: 6px; background: rgb(255 255 255 / .22); font-size: .8rem; }
+.pick-a { background: var(--a); text-align: left; }
+.pick-b { background: var(--b); text-align: right; }
+.pick-draw { background: var(--surface-2); color: var(--text); font-size: 1.3rem; }
+.pick:active { transform: scale(.98); }
+:root[data-theme="dark"] .pick-a, :root[data-theme="dark"] .pick-b { color: #0d1117; }
+@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .pick-a, :root:not([data-theme="light"]) .pick-b { color: #0d1117; } }
+.triage + .actionbar .actionbar-main, .actionbar-main:has(.pick-keep) { grid-template-columns: 1fr 1fr; }
+.pick-drop { background: var(--surface-2); color: var(--bad) !important; }
+.pick-keep { background: var(--accent); color: var(--accent-text) !important; }
+
+/* ---------- ranking ---------- */
+.rank-tools { display: grid; gap: 8px; margin-bottom: 8px; }
+.rank-tools input[type=search], select, input[type=number], textarea, .login input {
+ width: 100%; min-height: 42px; padding: 8px 10px; border-radius: 10px; border: 1px solid var(--line);
+ background: var(--surface); color: var(--text); font: inherit;
+}
+.rank-filters { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 6px; }
+.rank-filters select { font-size: .85rem; padding: 6px; }
+.check { display: flex; gap: 8px; align-items: flex-start; font-size: .9rem; margin: 6px 0; }
+.check input { margin-top: 3px; width: 18px; height: 18px; flex: none; }
+.rank-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 6px; }
+.rank-list li { display: grid; }
+.rank-row {
+ display: grid; grid-template-columns: 26px 26px 1fr auto; gap: 8px; align-items: center; width: 100%; text-align: left;
+ padding: 10px; border: 0; border-radius: 12px; background: var(--surface); box-shadow: var(--shadow); cursor: pointer;
+}
+.rank-row.dropped { opacity: .55; }
+.pos { font-weight: 700; color: var(--muted); text-align: right; font-variant-numeric: tabular-nums; }
+.rank-row .flag { font-size: 1.3rem; }
+.rmain { display: grid; min-width: 0; }
+.rname { font-weight: 650; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rmeta { font-size: .78rem; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rchips { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 3px; }
+.rscore { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
+.rscore small { display: block; font-weight: 400; color: var(--muted); font-size: .72rem; }
+.restore { justify-self: end; font-size: .85rem; }
+
+/* ---------- detail ---------- */
+.back { display: inline-flex; align-items: center; gap: 2px; background: none; border: 0; color: var(--accent); padding: 4px 0; cursor: pointer; font-weight: 600; }
+.back svg { width: 20px; height: 20px; }
+.dhead { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 14px; margin: 6px 0 12px; }
+.dflag { font-size: 2rem; line-height: 1; margin-bottom: 4px; }
+.dstats { font-variant-numeric: tabular-nums; }
+.dactions { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; margin-top: 8px; }
+.dsummary { font-size: 1rem; }
+.hlwo { display: grid; gap: 4px; margin: 8px 0 12px; font-size: .92rem; }
+.dsec { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 12px 14px; margin-bottom: 12px; }
+.dsec h2 { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
+.dsec h3 { margin-top: .8em; }
+.dsec p, .dsec li { font-size: .92rem; }
+.conf { font-size: .7rem; font-weight: 600; padding: 1px 8px; border-radius: 999px; background: var(--surface-2); color: var(--muted); }
+.conf-low { color: var(--warn); }
+.scored { margin: 8px 0 12px; }
+.scored-head { display: flex; justify-content: space-between; align-items: center; font-weight: 650; }
+.scored-head .bar { width: 90px; }
+.kv { display: grid; grid-template-columns: 1fr; gap: 2px 12px; margin: 0; }
+.kv dt { font-weight: 650; font-size: .85rem; margin-top: 8px; }
+.kv dd { margin: 0; font-size: .92rem; }
+.agreements { list-style: none; padding: 0; display: grid; gap: 8px; }
+.agreements li { padding: 8px 10px; border-radius: 10px; background: var(--surface-2); }
+.lang { font-weight: 600; }
+.sources { font-size: .85rem; overflow-wrap: anywhere; }
+.history { list-style: none; padding: 0; font-size: .9rem; }
+.history .up { color: var(--good); font-weight: 700; display: inline-block; width: 3em; }
+.history .down { color: var(--bad); font-weight: 700; display: inline-block; width: 3em; }
+.advisory { font-weight: 700; }
+.adv-none { color: var(--good); } .adv-caution { color: var(--warn); } .adv-partial-avoid, .adv-avoid { color: var(--bad); }
+textarea { min-height: 96px; resize: vertical; }
+
+/* ---------- triage ---------- */
+.triage { padding-bottom: 110px; }
+.progress { position: relative; height: 28px; border-radius: 10px; background: var(--surface-2); overflow: hidden; margin-bottom: 6px; }
+.progress > i { position: absolute; inset: 0 auto 0 0; background: color-mix(in srgb, var(--accent) 30%, transparent); }
+.progress > span { position: relative; z-index: 1; display: block; text-align: center; line-height: 28px; font-size: .82rem; font-weight: 600; }
+.tcard { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 14px; margin-top: 8px; }
+.tcard header { display: flex; gap: 10px; align-items: center; }
+.tcard .flag { font-size: 2rem; }
+.concerns { background: color-mix(in srgb, var(--bad) 12%, transparent); border-radius: 10px; padding: 8px 8px 8px 26px; color: var(--bad); font-size: .9rem; }
+.tgrid { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; font-size: .9rem; margin: 10px 0; }
+.tgrid dt { color: var(--muted); } .tgrid dd { margin: 0; }
+
+/* ---------- settings & login ---------- */
+.settings h2 { margin-top: 1.4em; }
+.field { display: grid; gap: 6px; margin: 10px 0; border: 0; padding: 0; font-weight: 600; font-size: .92rem; }
+.field legend { padding: 0; margin-bottom: 6px; }
+.seg { display: flex; gap: 6px; flex-wrap: wrap; font-weight: 400; }
+.seg label { display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); }
+.langs { list-style: none; padding: 0; display: grid; gap: 6px; font-weight: 400; }
+.langs li { display: grid; grid-template-columns: 1fr 90px auto; gap: 8px; align-items: center; }
+.addlang { display: grid; grid-template-columns: 1fr auto; gap: 8px; }
+.row { display: flex; flex-wrap: wrap; gap: 8px; }
+.file { position: relative; overflow: hidden; }
+.file input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
+.about li { margin: .3em 0; }
+.login { max-width: 340px; margin: 40px auto; display: grid; gap: 10px; background: var(--surface); padding: 20px; border-radius: var(--radius); box-shadow: var(--shadow); }
+.error { color: var(--bad); min-height: 1.2em; }
+
+/* ---------- toast ---------- */
+.toast {
+ position: fixed; left: 50%; bottom: calc(132px + env(safe-area-inset-bottom)); transform: translate(-50%, 20px); z-index: 30;
+ display: flex; gap: 12px; align-items: center; max-width: calc(100vw - 32px); padding: 10px 14px; border-radius: 12px;
+ background: #1f252d; color: #f1f3f5; font-size: .88rem; box-shadow: 0 8px 24px rgb(0 0 0 / .25);
+ opacity: 0; pointer-events: none; transition: opacity .2s, transform .2s;
+}
+.toast.show { opacity: 1; transform: translate(-50%, 0); pointer-events: auto; }
+.toast button { background: none; border: 0; color: #8fb4ff; font-weight: 700; cursor: pointer; padding: 4px; }
+
+/* ---------- wider screens ---------- */
+@media (min-width: 640px) {
+ .picks { display: inline; }
+ .duel-flags { grid-template-columns: 1fr 1fr; }
+ .kv { grid-template-columns: 200px 1fr; }
+ .kv dt { margin-top: 0; }
+ .sname { font-size: 1.08rem; }
+ .cmp-row { grid-template-columns: 170px 1fr 1fr; }
+}
+@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
diff --git a/public/icons/apple-touch-icon.png b/public/icons/apple-touch-icon.png
new file mode 100644
index 0000000..e083985
Binary files /dev/null and b/public/icons/apple-touch-icon.png differ
diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png
new file mode 100644
index 0000000..83cd816
Binary files /dev/null and b/public/icons/icon-192.png differ
diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png
new file mode 100644
index 0000000..00993ab
Binary files /dev/null and b/public/icons/icon-512.png differ
diff --git a/public/icons/icon.svg b/public/icons/icon.svg
new file mode 100644
index 0000000..4fbdc07
--- /dev/null
+++ b/public/icons/icon.svg
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/public/index.html b/public/index.html
new file mode 100644
index 0000000..4e07203
--- /dev/null
+++ b/public/index.html
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+%APP_TITLE%
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Loading…
+
+Elorasmus needs JavaScript.
+
+
diff --git a/public/js/main.js b/public/js/main.js
new file mode 100644
index 0000000..9177f9b
--- /dev/null
+++ b/public/js/main.js
@@ -0,0 +1,391 @@
+// App controller: loads data, keeps the event log in sync with the server, routes between views.
+//
+// Every user action becomes an event ({id, t, type, ...}). Events go to a local outbox first
+// (localStorage), are applied immediately, and are flushed to the server in the background,
+// so a pick made on a flaky phone connection is never lost. Ratings are always recomputed by
+// replaying server events (in server order) followed by not-yet-acknowledged local ones.
+
+import { replay, ranking, pairKey } from './elo.js';
+import { nextPair } from './pairing.js';
+import { DEFAULT_SETTINGS, shortName } from './metrics.js';
+import { html, toast, newId, local, ICONS } from './ui.js';
+import * as duelView from './views/duel.js';
+import * as rankView from './views/rank.js';
+import * as schoolView from './views/school.js';
+import * as triageView from './views/triage.js';
+import * as settingsView from './views/settings.js';
+
+class ApiError extends Error {
+ constructor(status, message) {
+ super(message);
+ this.status = status;
+ }
+}
+
+async function api(path, { method = 'GET', body } = {}) {
+ let res;
+ try {
+ res = await fetch(path, {
+ method,
+ credentials: 'same-origin',
+ headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch {
+ throw new ApiError(0, 'offline');
+ }
+ const data = await res.json().catch(() => null);
+ if (!res.ok) throw new ApiError(res.status, data?.error ?? res.statusText);
+ return data;
+}
+
+const ROUTES = {
+ '': duelView, rank: rankView, triage: triageView, settings: settingsView, school: schoolView,
+};
+
+const app = {
+ config: null,
+ data: null,
+ byCode: new Map(),
+ bySlug: new Map(),
+ serverEvents: [],
+ seq: 0,
+ outbox: local.get('outbox', []),
+ notes: {},
+ settings: { ...DEFAULT_SETTINGS },
+ state: null,
+ ctx: null,
+ recent: local.get('recent', []),
+ pair: local.get('pair', null),
+ positions: new Map(),
+ flushing: false,
+ retryDelay: 2000,
+ lastRoute: null,
+
+ /* ---------- derived state ---------- */
+
+ recompute() {
+ const known = new Set(this.serverEvents.map((e) => e.id));
+ this.outbox = this.outbox.filter((e) => !known.has(e.id));
+ const events = [...this.serverEvents, ...this.outbox];
+ const elo = { initial: this.config.elo.initial, kMax: this.config.elo.kMax, kMin: this.config.elo.kMin };
+ this.state = replay(events, this.data.schools.map((s) => s.code), elo);
+ this.positions = new Map(ranking(this.state.stats).map((s, i) => [s.code, i + 1]));
+ this.ctx = { settings: this.settings, data: this.data };
+ },
+
+ rankOf(code) {
+ return this.positions.get(code) ?? null;
+ },
+
+ currentPair() {
+ const ok = (c) => this.state.stats.get(c) && !this.state.stats.get(c).dropped;
+ if (!(this.pair && this.pair.length === 2 && this.pair[0] !== this.pair[1] && this.pair.every(ok))) {
+ this.pair = nextPair(this.state.stats, {
+ mode: this.settings.pairing, recent: this.recent, pairCounts: this.state.pairCounts,
+ });
+ local.set('pair', this.pair);
+ }
+ return this.pair;
+ },
+
+ /* ---------- actions ---------- */
+
+ record(fields) {
+ const ev = { id: newId(), t: new Date().toISOString(), ...fields };
+ this.outbox.push(ev);
+ local.set('outbox', this.outbox);
+ this.recompute();
+ this.flush();
+ return ev;
+ },
+
+ rememberPair(a, b) {
+ this.recent = [...this.recent, pairKey(a, b)].slice(-40);
+ local.set('recent', this.recent);
+ },
+
+ pick(a, b, r) {
+ const before = { a: this.state.stats.get(a).rating, b: this.state.stats.get(b).rating };
+ this.record({ type: 'match', a, b, r });
+ this.rememberPair(a, b);
+ this.pair = null;
+ const da = Math.round(this.state.stats.get(a).rating - before.a);
+ const db = Math.round(this.state.stats.get(b).rating - before.b);
+ const fmt = (code, d) => `${shortName(this.byCode.get(code))} ${d >= 0 ? '+' : ''}${d}`;
+ toast(r === 'draw' ? `Tie · ${fmt(a, da)} · ${fmt(b, db)}` : `${fmt(a, da)} · ${fmt(b, db)}`, { label: 'Undo', run: () => this.undo() });
+ this.render();
+ },
+
+ skip() {
+ if (this.pair) this.rememberPair(...this.pair);
+ this.pair = null;
+ this.render();
+ },
+
+ undo() {
+ const target = this.state.lastUndoable;
+ if (!target) return toast('Nothing to undo');
+ this.record({ type: 'undo', target: target.id });
+ if (target.type === 'match') {
+ this.pair = [target.a, target.b];
+ local.set('pair', this.pair);
+ }
+ const what = target.type === 'match' ? 'pick' : target.type;
+ toast(`Undid the last ${what}`);
+ this.render();
+ },
+
+ drop(code) {
+ this.record({ type: 'drop', code });
+ if (this.pair?.includes(code)) this.pair = null;
+ toast(`Dropped ${shortName(this.byCode.get(code))}`, { label: 'Undo', run: () => this.undo() });
+ this.render();
+ },
+
+ restore(code) {
+ this.record({ type: 'restore', code });
+ toast(`${shortName(this.byCode.get(code))} is back in the race`);
+ this.render();
+ },
+
+ review(code) {
+ this.record({ type: 'review', code });
+ this.render();
+ },
+
+ duelWith(code) {
+ const me = this.state.stats.get(code);
+ const others = [...this.state.stats.values()]
+ .filter((s) => !s.dropped && s.code !== code)
+ .sort((x, y) => Math.abs(x.rating - me.rating) - Math.abs(y.rating - me.rating))
+ .slice(0, 5);
+ if (!others.length) return toast('No opponent available');
+ const opp = others[Math.floor(Math.random() * others.length)].code;
+ this.pair = Math.random() < 0.5 ? [code, opp] : [opp, code];
+ local.set('pair', this.pair);
+ this.navigate('#/');
+ },
+
+ async saveNote(code, text) {
+ const res = await api(`api/notes/${encodeURIComponent(code)}`, { method: 'PUT', body: { text } });
+ if (res.note) this.notes[code] = res.note;
+ else delete this.notes[code];
+ },
+
+ async updateSettings(patch) {
+ const previous = this.settings;
+ this.settings = { ...this.settings, ...patch };
+ if ('pairing' in patch) this.pair = null;
+ this.recompute();
+ this.render();
+ try {
+ await api('api/settings', { method: 'PUT', body: patch });
+ } catch (err) {
+ this.settings = previous;
+ this.recompute();
+ this.render();
+ toast(err.status === 0 ? 'Offline: setting not saved' : `Setting not saved: ${err.message}`);
+ }
+ },
+
+ async importBackup(file) {
+ let data;
+ try {
+ data = JSON.parse(await file.text());
+ } catch {
+ return toast('That file is not valid JSON');
+ }
+ const n = Array.isArray(data?.events) ? data.events.length : 0;
+ if (!confirm(`Replace ALL current picks, notes and settings with this backup (${n} events)?\nThe server keeps a copy of the current state in DATA_DIR/backups.`)) return;
+ try {
+ await api('api/import', { method: 'POST', body: data });
+ this.outbox = [];
+ local.set('outbox', []);
+ await this.sync({ full: true });
+ toast('Backup imported');
+ } catch (err) {
+ toast(`Import failed: ${err.message}`);
+ }
+ },
+
+ async logout() {
+ await api('api/logout', { method: 'POST', body: {} }).catch(() => {});
+ location.reload();
+ },
+
+ /* ---------- server sync ---------- */
+
+ /** Pull server state. Returns how many new events came from elsewhere (not our outbox). */
+ async sync({ full = false } = {}) {
+ const res = await api(`api/state${full ? '' : `?since=${this.seq}`}`);
+ const mine = new Set(this.outbox.map((e) => e.id));
+ let incoming;
+ if (full || res.seq < this.seq) {
+ // First load, or the server state was replaced (import): take it wholesale.
+ this.serverEvents = full ? res.events : (await api('api/state')).events;
+ incoming = this.serverEvents;
+ } else {
+ incoming = res.events.filter((e) => e.seq > this.seq);
+ this.serverEvents.push(...incoming);
+ }
+ this.seq = res.seq;
+ this.notes = res.notes;
+ this.settings = { ...DEFAULT_SETTINGS, stayMonths: this.config.defaults.stayMonths, ...res.settings };
+ this.recompute();
+ local.set('outbox', this.outbox);
+ return incoming.filter((e) => !mine.has(e.id)).length;
+ },
+
+ async flush() {
+ if (this.flushing || !this.outbox.length) return;
+ this.flushing = true;
+ const batch = this.outbox.slice();
+ let sent = false;
+ try {
+ await api('api/events', { method: 'POST', body: { events: batch } });
+ sent = true;
+ } catch (err) {
+ if (err.status === 401) {
+ this.flushing = false;
+ return this.showLogin();
+ }
+ // 400 = the server refused something in the batch; find and discard just that event.
+ if (err.status === 400) sent = await this.discardRejected(batch);
+ if (!sent) {
+ setTimeout(() => this.flush(), this.retryDelay);
+ this.retryDelay = Math.min(this.retryDelay * 2, 60000);
+ }
+ }
+ this.flushing = false;
+ if (!sent) return;
+ this.retryDelay = 2000;
+ const foreign = await this.sync().catch(() => 0);
+ if (foreign) this.render(); // another device changed something meanwhile
+ if (this.outbox.length) this.flush();
+ },
+
+ /** Resend events one by one; drop those refused (e.g. undo of something already undone elsewhere). */
+ async discardRejected(batch) {
+ const rejected = [];
+ for (const ev of batch) {
+ try {
+ await api('api/events', { method: 'POST', body: { events: [ev] } });
+ } catch (err) {
+ if (err.status !== 400) return false; // connection trouble: retry everything later
+ rejected.push(ev);
+ }
+ }
+ this.outbox = this.outbox.filter((e) => !rejected.includes(e));
+ local.set('outbox', this.outbox);
+ if (rejected.length) toast(`${rejected.length} change(s) refused by the server and discarded`);
+ return true;
+ },
+
+ /* ---------- routing & rendering ---------- */
+
+ navigate(hash) {
+ location.hash = hash;
+ },
+
+ back() {
+ if (history.length > 1) history.back();
+ else this.navigate('#/rank');
+ },
+
+ applyTheme() {
+ const theme = local.get('theme', 'system');
+ if (theme === 'system') delete document.documentElement.dataset.theme;
+ else document.documentElement.dataset.theme = theme;
+ },
+
+ route() {
+ const [, name = '', param] = location.hash.match(/^#\/?([a-z]*)\/?(.*)$/) ?? [];
+ return { name: ROUTES[name] ? name : '', param: decodeURIComponent(param ?? '') };
+ },
+
+ render() {
+ const { name, param } = this.route();
+ const view = document.getElementById('view');
+ const key = `${name}/${param}`;
+ // Don't yank the notes box away from someone typing in it during a background sync.
+ if (key === this.lastRoute && view.contains(document.activeElement) && document.activeElement.matches('textarea, input[type=search]')) return;
+ view.onclick = view.onchange = view.oninput = null;
+ ROUTES[name].render(view, this, param);
+ for (const a of document.querySelectorAll('.tabs a')) a.classList.toggle('active', a.dataset.route === (name === 'school' ? 'rank' : name));
+ document.getElementById('picks').textContent = `${this.state.matches.length} picks`;
+ if (key !== this.lastRoute) {
+ window.scrollTo(0, 0);
+ this.lastRoute = key;
+ }
+ },
+
+ showLogin(message = '') {
+ const view = document.getElementById('view');
+ document.body.classList.add('logged-out');
+ view.innerHTML = String(html`
+ `);
+ view.querySelector('form').onsubmit = async (e) => {
+ e.preventDefault();
+ try {
+ await api('api/login', { method: 'POST', body: { password: e.target.password.value } });
+ location.reload();
+ } catch (err) {
+ this.showLogin(err.status === 401 ? 'Wrong password' : err.message);
+ }
+ };
+ },
+
+ async start() {
+ this.applyTheme();
+ document.querySelector('.tabs').innerHTML = String(html`
+ ${ICONS.duel}Compare
+ ${ICONS.rank}Ranking
+ ${ICONS.triage}Triage
+ ${ICONS.settings}Settings `);
+ try {
+ this.config = await api('api/config');
+ document.title = this.config.title;
+ if (this.config.authRequired && !this.config.authenticated) return this.showLogin();
+ this.data = await api('data/schools.json');
+ if (this.config.eurCzk) this.data.fx = { ...this.data.fx, EURCZK: this.config.eurCzk };
+ } catch (err) {
+ if (err.status === 401) return this.showLogin();
+ document.getElementById('view').innerHTML = String(html`Can't load the app ${err.message}
`);
+ return;
+ }
+ for (const s of this.data.schools) {
+ this.byCode.set(s.code, s);
+ this.bySlug.set(s.slug, s);
+ }
+ try {
+ await this.sync({ full: true });
+ } catch (err) {
+ if (err.status === 401) return this.showLogin();
+ // Offline: run on the local outbox only; sync when back.
+ this.recompute();
+ toast('Offline: your picks are kept on this device and sent later');
+ }
+ this.render();
+ this.flush();
+ addEventListener('hashchange', () => this.render());
+ addEventListener('online', () => this.flush());
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') this.sync().then((n) => n && this.render()).catch(() => {});
+ });
+ setInterval(() => {
+ if (document.visibilityState === 'visible') this.sync().then((n) => n && this.render()).catch(() => {});
+ }, 60000);
+ document.addEventListener('keydown', (e) => {
+ if (this.route().name === '' && duelView.onKey(e, this)) e.preventDefault();
+ });
+ },
+};
+
+app.start();
diff --git a/public/js/ui.js b/public/js/ui.js
new file mode 100644
index 0000000..2e2f4de
--- /dev/null
+++ b/public/js/ui.js
@@ -0,0 +1,99 @@
+// Tiny UI helpers. `html` is a tagged template that escapes every interpolated value unless it
+// was produced by `html` itself (or wrapped in `raw`). Research text comes from the web, so
+// escaping by default is the line of defence against markup injection.
+
+const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
+
+class Safe {
+ constructor(s) { this.s = s; }
+ toString() { return this.s; }
+}
+
+export const raw = (s) => new Safe(String(s));
+export const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ESC[c]);
+
+function piece(v) {
+ if (v == null || v === false) return '';
+ if (v instanceof Safe) return v.s;
+ if (Array.isArray(v)) return v.map(piece).join('');
+ return esc(v);
+}
+
+export function html(strings, ...values) {
+ let out = strings[0];
+ for (let i = 0; i < values.length; i++) out += piece(values[i]) + strings[i + 1];
+ return new Safe(out);
+}
+
+/** Only http(s) links survive; anything else (javascript:, data:) becomes "#". */
+export function safeUrl(u) {
+ try {
+ const url = new URL(u);
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : '#';
+ } catch {
+ return '#';
+ }
+}
+
+export const extLink = (url, label) =>
+ html`${label} `;
+
+/** Score bar 0-10 (no inline styles: CSP forbids them, so widths are classes). */
+export function bar(v, tone = '') {
+ if (v == null) return html`– `;
+ const w = Math.max(0, Math.min(10, Math.round(v)));
+ return html`${Math.round(v * 10) / 10} `;
+}
+
+let toastTimer;
+/** Show a short message; `action` = { label, run } adds a button (e.g. Undo). */
+export function toast(message, action) {
+ const el = document.getElementById('toast');
+ el.replaceChildren();
+ const span = document.createElement('span');
+ span.textContent = message;
+ el.append(span);
+ if (action) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.textContent = action.label;
+ btn.addEventListener('click', () => { el.classList.remove('show'); action.run(); }, { once: true });
+ el.append(btn);
+ }
+ el.classList.add('show');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => el.classList.remove('show'), action ? 5000 : 2600);
+}
+
+/** Random id that works without a secure context (crypto.randomUUID needs HTTPS). */
+export function newId() {
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+/** localStorage that never throws (private mode, blocked storage). */
+export const local = {
+ get(key, fallback) {
+ try {
+ const v = localStorage.getItem(`elorasmus.${key}`);
+ return v == null ? fallback : JSON.parse(v);
+ } catch {
+ return fallback;
+ }
+ },
+ set(key, value) {
+ try {
+ localStorage.setItem(`elorasmus.${key}`, JSON.stringify(value));
+ } catch { /* storage unavailable: state just won't survive a reload */ }
+ },
+};
+
+export const ICONS = {
+ duel: raw(' '),
+ rank: raw(' '),
+ triage: raw(' '),
+ settings: raw(' '),
+ back: raw(' '),
+ undo: raw(' '),
+ skip: raw(' '),
+};
diff --git a/public/js/views/duel.js b/public/js/views/duel.js
new file mode 100644
index 0000000..a35b36f
--- /dev/null
+++ b/public/js/views/duel.js
@@ -0,0 +1,125 @@
+// The main screen: two schools side by side, a comparison table, and pick buttons in thumb reach.
+
+import { html, bar } from '../ui.js';
+import { COMPARE_ROWS, rowWinner, shortName, place } from '../metrics.js';
+import { PROVISIONAL_GAMES } from '../elo.js';
+
+function head(app, s, side) {
+ const st = app.state.stats.get(s.code);
+ const rank = app.rankOf(s.code);
+ const provisional = st.games < PROVISIONAL_GAMES;
+ return html`
+
+ ${side.toUpperCase()}
+ ${s.flag}
+ ${shortName(s)}
+ ${place(s)}
+
+ ${provisional ? '~' : ''}${Math.round(st.rating)}
+ ${rank && st.games ? `#${rank} · ` : ''}${st.games} ${st.games === 1 ? 'game' : 'games'}
+
+ ${s.research ? '' : html`research pending `}
+ `;
+}
+
+function table(app, a, b) {
+ let section = '';
+ const rows = [];
+ for (const row of COMPARE_ROWS) {
+ if (row.section !== section) {
+ section = row.section;
+ rows.push(html`${section}
`);
+ }
+ const va = row.get(a, app.ctx);
+ const vb = row.get(b, app.ctx);
+ if (!va && !vb) continue;
+ const win = rowWinner(row, va, vb);
+ const cell = (v, side) => {
+ if (!v) return html`–
`;
+ const content = v.bar != null ? bar(v.bar) : html`${v.text} `;
+ return html`${content}
`;
+ };
+ rows.push(html`
+
+
${row.label}
${cell(va, 'a')}${cell(vb, 'b')}
+
`);
+ }
+ return html`${rows}
`;
+}
+
+function flagsBlock(s, side) {
+ const r = s.research;
+ if (!r) return '';
+ const items = [
+ ...r.highlights.slice(0, 3).map((t) => html`${t} `),
+ ...r.watchouts.slice(0, 3).map((t) => html`${t} `),
+ ];
+ return html`
+
+
${side.toUpperCase()} ${shortName(s)}
+
${r.summary}
+
+
`;
+}
+
+export function render(root, app) {
+ const pair = app.currentPair();
+ if (!pair) {
+ root.innerHTML = String(html`
+
+ Not enough schools left
+ You need at least two schools that aren't dropped. Restore some in the ranking.
+ Open the ranking
+ `);
+ return;
+ }
+ const [a, b] = pair.map((c) => app.byCode.get(c));
+ const undoable = app.state.lastUndoable;
+ root.innerHTML = String(html`
+
+ Which would you rather go to?
+ ${head(app, a, 'a')}vs ${head(app, b, 'b')}
+ ${table(app, a, b)}
+ ${flagsBlock(a, 'a')}${flagsBlock(b, 'b')}
+
+ Drop A from the race
+ Drop B from the race
+
+
+
+
+ Undo
+ ${app.state.matches.length} picks
+ Skip
+
+
+ A ${shortName(a)}
+ =
+ ${shortName(b)} B
+
+
`);
+
+ root.onclick = (e) => {
+ const t = e.target.closest('[data-action]');
+ if (!t || t.disabled) return;
+ const action = t.dataset.action;
+ if (action === 'pick') app.pick(a.code, b.code, t.dataset.r);
+ else if (action === 'skip') app.skip();
+ else if (action === 'undo') app.undo();
+ else if (action === 'drop') app.drop(t.dataset.code);
+ else if (action === 'open') app.navigate(`#/school/${t.dataset.slug}`);
+ };
+}
+
+/** Desktop shortcuts: ←/→ pick, ↓ or = draw, space skip, z/backspace undo. */
+export function onKey(e, app) {
+ if (e.target.closest('input, textarea, select')) return false;
+ const pair = app.currentPair();
+ if (!pair) return false;
+ const map = { ArrowLeft: 'a', ArrowRight: 'b', ArrowDown: 'draw', '=': 'draw' };
+ if (map[e.key]) { app.pick(pair[0], pair[1], map[e.key]); return true; }
+ if (e.key === ' ') { app.skip(); return true; }
+ if (e.key === 'z' || e.key === 'Backspace') { app.undo(); return true; }
+ return false;
+}
diff --git a/public/js/views/rank.js b/public/js/views/rank.js
new file mode 100644
index 0000000..ccd6bf3
--- /dev/null
+++ b/public/js/views/rank.js
@@ -0,0 +1,116 @@
+// Leaderboard: everything ordered by your Elo, with filters and alternative sort orders.
+
+import { html, local } from '../ui.js';
+import { shortName, place, netCost, moneyRange, languageFit } from '../metrics.js';
+import { ranking, PROVISIONAL_GAMES } from '../elo.js';
+
+const SORTS = {
+ rating: { label: 'My Elo', key: (s, st) => -st.rating },
+ academic: { label: 'AI/robotics research', key: (s) => -(s.research?.aiRobotics?.academic?.score ?? -1) },
+ access: { label: 'Course access', key: (s) => -(s.research?.aiRobotics?.access?.score ?? -1) },
+ net: { label: 'Cheapest', key: (s, st, app) => { const n = netCost(s, app.settings, app.data); return n ? (n.lo + n.hi) / 2 : 1e9; } },
+ nature: { label: 'Nature (avg)', key: (s) => {
+ const n = s.research?.nature;
+ return n ? -(n.climbing.score + n.hiking.score + n.ocean.score) / 3 : 1;
+ } },
+ name: { label: 'Name', key: (s) => shortName(s).toLowerCase() },
+};
+
+export function render(root, app) {
+ const prefs = local.get('rank', { q: '', region: '', scope: '', sort: 'rating', dropped: false });
+ const all = ranking(app.state.stats, { includeDropped: true });
+ const position = new Map(ranking(app.state.stats).map((s, i) => [s.code, i + 1]));
+ const q = prefs.q.trim().toLowerCase();
+ const regions = [...new Set(app.data.schools.map((s) => s.region))].sort();
+
+ const rows = all
+ .map((st) => ({ st, s: app.byCode.get(st.code) }))
+ .filter(({ s, st }) => (prefs.dropped ? st.dropped : !st.dropped))
+ .filter(({ s }) => !prefs.region || s.region === prefs.region)
+ .filter(({ s }) => !prefs.scope || s.agreements.some((a) => a.scope === prefs.scope))
+ .filter(({ s }) => !q || `${shortName(s)} ${s.research?.name ?? ''} ${s.catalogName} ${s.research?.city ?? ''} ${s.countryShort} ${s.code}`
+ .toLowerCase().includes(q));
+ const sort = SORTS[prefs.sort] ?? SORTS.rating;
+ rows.sort((x, y) => {
+ const kx = sort.key(x.s, x.st, app);
+ const ky = sort.key(y.s, y.st, app);
+ return kx < ky ? -1 : kx > ky ? 1 : y.st.rating - x.st.rating;
+ });
+ const droppedCount = all.filter((s) => s.dropped).length;
+
+ root.innerHTML = String(html`
+
+
+ ${rows.length} schools · ${app.state.matches.length} picks so far
+
+ ${rows.map(({ s, st }) => {
+ const n = netCost(s, app.settings, app.data);
+ const lang = languageFit(s, app.settings.languages);
+ const ai = s.research?.aiRobotics?.academic?.score;
+ return html`
+
+
+ ${st.dropped ? '–' : position.get(s.code)}
+ ${s.flag}
+
+ ${shortName(s)}
+ ${place(s)}${lang.status === 'fail' ? html` · ${lang.text} ` : ''}
+
+ ${ai != null ? html`AI ${ai} ` : html`pending `}
+ ${n ? html`${moneyRange([n.lo, n.hi], app.settings, app.data, { compact: true })} ` : ''}
+ ${s.agreements.some((a) => a.scope === 'FEL') ? html`FEL ` : html`CTU `}
+
+
+
+ ${Math.round(st.rating)}${st.wins}–${st.losses}${st.draws ? `–${st.draws}` : ''}
+
+
+ ${st.dropped ? html`Restore ` : ''}
+ `;
+ })}
+
+ `);
+
+ const save = (patch) => { local.set('rank', { ...prefs, ...patch }); render(root, app); };
+ root.onclick = (e) => {
+ const t = e.target.closest('[data-action]');
+ if (!t) return;
+ if (t.dataset.action === 'open') app.navigate(`#/school/${t.dataset.slug}`);
+ if (t.dataset.action === 'restore') app.restore(t.dataset.code);
+ };
+ root.onchange = (e) => {
+ const el = e.target;
+ if (el.name === 'dropped') save({ dropped: el.checked });
+ else if (['region', 'scope', 'sort'].includes(el.name)) save({ [el.name]: el.value });
+ };
+ let typing;
+ root.oninput = (e) => {
+ if (e.target.name !== 'q') return;
+ clearTimeout(typing);
+ const value = e.target.value;
+ typing = setTimeout(() => {
+ save({ q: value });
+ const input = root.querySelector('input[name="q"]');
+ input.focus();
+ input.setSelectionRange(value.length, value.length);
+ }, 250);
+ };
+}
+
diff --git a/public/js/views/school.js b/public/js/views/school.js
new file mode 100644
index 0000000..c953d57
--- /dev/null
+++ b/public/js/views/school.js
@@ -0,0 +1,210 @@
+// Everything known about one school: catalog agreements, all research sections with sources,
+// money breakdown for your stay, your notes, and your pick history for it.
+
+import { html, bar, extLink, ICONS } from '../ui.js';
+import {
+ shortName, fullName, place, languageFit, subjectFit, monthlyGrant, netCost, money, moneyRange, LANG_NAMES,
+} from '../metrics.js';
+
+const CONF_LABEL = { high: 'high confidence', medium: 'medium confidence', low: 'low confidence' };
+const conf = (c) => (c ? html`${CONF_LABEL[c]} ` : '');
+const para = (t) => (t ? html`${t}
` : '');
+const list = (items, cls = '') => (items?.length ? html`${items.map((i) => html`${i} `)} ` : '');
+
+function scored(label, node, tone = '') {
+ if (!node) return '';
+ return html`${label} ${bar(node.score, tone)}
${para(node.text)}
`;
+}
+
+function section(title, body, confidence) {
+ return html`${title} ${conf(confidence)} ${body} `;
+}
+
+function agreementsBlock(s, app) {
+ return html`
+
+ ${s.agreements.map((a) => html`
+
+ ${a.scope === 'FEL' ? 'FEL agreement' : 'CTU-wide'}
+ ${a.places == null ? '?' : a.places >= 99 ? 'open' : a.places} place${a.places === 1 ? '' : 's'} ·
+ levels ${a.levels.join(' ')}
+ ${a.isced.length ? a.iscedLabels.map((l, i) => `${a.isced[i]} ${l}`).join(' · ') : 'Any subject area'}
+ ${a.languages.length
+ ? a.languages.map((l) => html`${LANG_NAMES[l.lang] ?? l.lang} ${l.level} `)
+ : html`No language listed `}
+ ${a.factsheet ? html`${extLink(a.factsheet, 'CTU factsheet (CTU login)')}
` : ''}
+ `)}
+
+ Subject fit: ${subjectFit(s).text} ·
+ Language: ${languageFit(s, app.settings.languages).text}
`;
+}
+
+function moneyBlock(s, app) {
+ const r = s.research;
+ const g = monthlyGrant(s, app.settings, app.data);
+ const n = netCost(s, app.settings, app.data);
+ const m = app.settings.stayMonths;
+ const country = app.data.countries?.[s.country];
+ const range = (x) => moneyRange(x, app.settings, app.data);
+ const liv = r?.living;
+ return html`
+
+ Money from CTU ${money(g.eur, app.settings, app.data)} /month · ${s.funding?.label}
+ ${s.funding?.note}
+ ${r?.fees?.hostFunding?.monthlyEUR ? html`Host scholarship ${money(r.fees.hostFunding.monthlyEUR, app.settings, app.data)}/month (not guaranteed)
+ ${r.fees.hostFunding.text}
` : ''}
+ ${liv ? html`
+ Living /month ${range(liv.totalEUR)}
+ rent ${range(liv.rentEUR)} · food ${range(liv.foodEUR)} · transport ${range(liv.transportEUR)} · other ${range(liv.otherEUR)}
+ Housing ${liv.housing} ` : ''}
+ ${r?.fees ? html`Mandatory fees ${r.fees.mandatoryEUR != null ? money(r.fees.mandatoryEUR, app.settings, app.data) : '?'} per semester
+ ${r.fees.text}
` : ''}
+ ${r?.travel ? html`Getting there ${r.travel.duration} · ${range(r.travel.roundTripEUR)} round trip
+ ${r.travel.text}
` : ''}
+ ${country?.visa ? html`Visa ${country.visa.required ? `${country.visa.type || 'Required'} · ${country.visa.costEUR != null ? money(country.visa.costEUR, app.settings, app.data) : 'cost unknown'}` : 'Not needed'}
+ ${country.visa.text}
` : ''}
+ ${n ? html`Out of pocket (${m} months) ${range([n.lo, n.hi])}
+ living ${range(n.parts.living)} + travel ${range(n.parts.travel)} + visa ${money(n.parts.visa, app.settings, app.data)}
+ + fees ${money(n.parts.fees, app.settings, app.data)} − money received ${money(n.parts.grant, app.settings, app.data)}
` : ''}
+
+ ${liv ? para(liv.text) : ''}`;
+}
+
+function safetyBlock(s, app) {
+ const r = s.research;
+ const c = app.data.countries?.[s.country];
+ return html`
+ ${r ? scored('City safety', { score: r.safety.score, text: r.safety.text }) : ''}
+ ${r ? html`Hazards: ${r.safety.hazards}
` : ''}
+ ${c ? html`
+ ${scored('Country stability', { score: c.stabilityScore, text: c.text })}
+ World Bank political stability: ${c.wgiPoliticalStability?.percentile ?? '?'}th percentile (${c.wgiPoliticalStability?.year}) ·
+ Global Peace Index #${c.gpi?.rank ?? '?'} (${c.gpi?.year})
+ Czech MFA: ${c.mfaAdvisory?.level} ${c.mfaAdvisory?.text}
+ Health insurance: ${c.health?.text}
` : ''}`;
+}
+
+export function render(root, app, slug) {
+ const s = app.bySlug.get(slug);
+ if (!s) {
+ root.innerHTML = String(html``);
+ return;
+ }
+ const r = s.research;
+ const st = app.state.stats.get(s.code);
+ const rank = app.rankOf(s.code);
+ const note = app.notes[s.code]?.text ?? '';
+ const history = [...st.history].reverse().slice(0, 30);
+
+ root.innerHTML = String(html`
+
+ ${ICONS.back} Back
+
+ ${s.flag}
+ ${fullName(s)}
+ ${shortName(s) !== fullName(s) ? `${shortName(s)} · ` : ''}${place(s)} · ${s.code}
+
+ ${Math.round(st.rating)} Elo ${rank && st.games ? `· #${rank}` : ''} · ${st.games} games (${st.wins}W ${st.losses}L ${st.draws}D)
+ ${st.dropped ? html`dropped ` : ''}
+
+
+ ${st.dropped
+ ? html`Restore to the race `
+ : html`Compare it now
+ Drop `}
+ ${s.web ? extLink(s.web, 'Website') : ''} ${s.qs ? extLink(s.qs, 'QS') : ''}
+ ${extLink(`https://www.openstreetmap.org/?mlat=${s.lat}&mlon=${s.lon}#map=12/${s.lat}/${s.lon}`, 'Map')}
+
+
+
+ ${r ? html`
+ ${r.summary}
+ ${list(r.highlights, 'hl-list')}${list(r.watchouts, 'wo-list')}
` : html`
+ Research for this school is still pending. You can still compare it using the catalog data.
`}
+
+ ${section('Agreements', agreementsBlock(s, app))}
+
+ ${r ? html`
+ ${section('AI & robotics', html`
+ ${scored('Research', r.aiRobotics.academic)}
+ ${scored('Hands-on', r.aiRobotics.practical)}
+ ${scored('Course access for you', r.aiRobotics.access)}
+ ${Object.entries(r.aiRobotics.rankings).filter(([, v]) => v).map(([k, v]) => html`${({ qsWorld: 'QS', qsCS: 'QS CS', csrankings: 'CSRankings', other: '' })[k]} ${v} `)}
+ ${r.aiRobotics.labs.length ? html`Labs & groups ${list(r.aiRobotics.labs)}` : ''}
+ ${r.aiRobotics.courses.length ? html`Relevant English courses ${list(r.aiRobotics.courses)}` : ''}
+ ${r.aiRobotics.teams.length ? html`Student teams ${list(r.aiRobotics.teams)}` : ''}`, r.confidence.aiRobotics)}
+
+ ${section('Money', moneyBlock(s, app), r.confidence.living)}
+
+ ${section('Language', html`
+
+ Teaching ${r.language.teaching}
+ Proof needed ${r.language.proof}
+ Local language in daily life ${bar(r.language.localNeed)} (10 = essential)
+ ${para(r.language.text)}`, r.confidence.language)}
+
+ ${section('Social life & solitude', html`
+ ${scored('Social', r.social)}
+ ${r.social.esn ? html`ESN/buddy: ${r.social.esn}` : ''}${r.social.internationals ? html` · Internationals: ${r.social.internationals}` : ''}
+ ${scored('Calm & solitude', r.solitude)}`, r.confidence.social)}
+
+ ${section('Nature', html`
+ ${scored('Climbing', r.nature.climbing)}
+ ${scored('Hiking', r.nature.hiking)}
+ ${scored('Ocean', r.nature.ocean)}
+ ${scored('Skiing', r.nature.skiing)}
+ Climate (Sep–Feb): ${r.nature.climate}
`, r.confidence.nature)}
+ ` : ''}
+
+ ${section('Safety & stability', safetyBlock(s, app), r?.confidence?.safety)}
+
+ ${r ? html`
+ ${section('Calendar & application', html`
+
+ Term ${r.calendar.term}
+ Fit with CTU winter ${r.calendar.fit} · full year: ${r.calendar.fullYear}
+ Host deadline ${r.application.nominationDeadline ?? 'unknown'}
+ ${para(r.calendar.text)}${para(r.application.text)}`, r.confidence.calendar)}
+
+ ${section('Sources', html`
+ ${r.sources.map((src) => html`${extLink(src.url, src.label)} `)}
+ Researched ${r.researchedAt} · overall ${CONF_LABEL[r.confidence.overall]}. Check money and language rules officially before applying.
`)}
+ ` : ''}
+
+ ${section('My notes', html`
+
+ ${note ? 'Saved' : 'Saved automatically'}
`)}
+
+ ${history.length ? section('My picks', html`
+ ${history.map((m) => {
+ const meA = m.a === s.code;
+ const other = app.byCode.get(meA ? m.b : m.a);
+ const delta = meA ? m.da : m.db;
+ const outcome = m.r === 'draw' ? 'tied with' : (m.r === 'a') === meA ? 'beat' : 'lost to';
+ return html`${delta >= 0 ? '+' : ''}${Math.round(delta)} ${outcome} ${shortName(other)} `;
+ })} `) : ''}
+ `);
+
+ root.onclick = (e) => {
+ const t = e.target.closest('[data-action]');
+ if (!t) return;
+ const action = t.dataset.action;
+ if (action === 'back') app.back();
+ else if (action === 'drop') app.drop(s.code);
+ else if (action === 'restore') app.restore(s.code);
+ else if (action === 'duel') app.duelWith(s.code);
+ };
+ const textarea = root.querySelector('textarea[name="note"]');
+ const status = root.querySelector('[data-note-status]');
+ let timer;
+ const save = () => {
+ clearTimeout(timer);
+ if (textarea.value === (app.notes[s.code]?.text ?? '')) return;
+ status.textContent = 'Saving…';
+ app.saveNote(s.code, textarea.value)
+ .then(() => { status.textContent = 'Saved'; })
+ .catch(() => { status.textContent = 'Not saved: offline? It will retry when you leave the field.'; });
+ };
+ textarea.addEventListener('input', () => { status.textContent = 'Editing…'; clearTimeout(timer); timer = setTimeout(save, 1200); });
+ textarea.addEventListener('blur', save);
+}
diff --git a/public/js/views/settings.js b/public/js/views/settings.js
new file mode 100644
index 0000000..6f4aa36
--- /dev/null
+++ b/public/js/views/settings.js
@@ -0,0 +1,110 @@
+// Preferences (synced to the server), per-device display options, data export/import, about.
+
+import { html, extLink, local } from '../ui.js';
+import { LANG_NAMES } from '../metrics.js';
+
+const LEVELS = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'];
+
+export function render(root, app) {
+ const s = app.settings;
+ const theme = local.get('theme', 'system');
+ const researched = app.data.schools.filter((x) => x.research).length;
+ const f = app.data.funding;
+ root.innerHTML = String(html`
+
+ Your situation
+ Stay length (months)
+
+
+ Currency
+
+ ${['EUR', 'CZK'].map((c) => html` ${c} `)}
+
+
+
+ I qualify for the Erasmus+ fewer-opportunities top-up (+${f.erasmus.fewerOpportunitiesTopUpEUR ?? 250} €/month)
+
+ Count host scholarships (e.g. JASSO) in the money totals. They're competitive, so it's off by default.
+
+ Your languages
+ ${s.languages.map((l, i) => html`
+ ${LANG_NAMES[l.lang] ?? l.lang}
+ ${LEVELS.map((lv) => html`${lv} `)}
+ Remove `)}
+
+
+
+ ${Object.entries(LANG_NAMES).filter(([k]) => !s.languages.some((l) => l.lang === k))
+ .map(([k, v]) => html`${v} `)}
+
+ Add
+
+
+
+ Next pair
+
+ Smart
+ Random
+
+ Smart shows rarely compared schools first, then close contests: fewer picks for the same ranking quality.
+
+
+ This device
+ Theme
+
+ ${['system', 'light', 'dark'].map((t) => html` ${t} `)}
+
+
+
+ Your data
+ Picks, notes and settings live on your server (DATA_DIR). Export a backup now and then.
+
+
Export backup
+
Import backup
+ ${app.config.authRequired ? html`
Log out ` : ''}
+
+
+ About the data
+
+ Catalog: CTU Mobility, FEL, Master, ${app.data.catalog.academicYear}, saved ${app.data.catalog.savedAt?.slice(4, 15) ?? '?'}.
+ Research: ${researched} of ${app.data.schools.length} schools so far. Data built ${app.data.generatedAt.slice(0, 10)}.
+ Erasmus+ rates: ${f.erasmus.status}.
+ Selection round: ${f.selection.deadline}
+ Exchange rate: 1 € = ${app.data.fx.EURCZK} Kč (${app.data.fx.date}).
+ Everything here was gathered from public web sources and can be wrong or outdated.
+ Check money, language rules and deadlines with the FEL international office before you apply.
+ Selection info sources: ${f.selection.sources.slice(0, 3).map((x) => html`${extLink(x.url, x.label)}; `)}
+
+ Elorasmus ${app.config.version}
+ `);
+
+ const update = (patch) => app.updateSettings(patch);
+ root.onchange = async (e) => {
+ const el = e.target;
+ if (el.name === 'stayMonths') {
+ const v = Number(el.value);
+ if (v >= 1 && v <= 12) update({ stayMonths: v });
+ } else if (el.name === 'currency' || el.name === 'pairing') update({ [el.name]: el.value });
+ else if (el.name === 'fewerOpportunities' || el.name === 'countHostFunding') update({ [el.name]: el.checked });
+ else if (el.name === 'level') {
+ const langs = s.languages.map((l, i) => (i === Number(el.dataset.i) ? { ...l, level: el.value } : l));
+ update({ languages: langs });
+ } else if (el.name === 'theme') {
+ local.set('theme', el.value);
+ app.applyTheme();
+ } else if (el.name === 'import' && el.files?.[0]) {
+ app.importBackup(el.files[0]);
+ el.value = '';
+ }
+ };
+ root.onclick = (e) => {
+ const t = e.target.closest('[data-action]');
+ if (!t) return;
+ if (t.dataset.action === 'rmlang') update({ languages: s.languages.filter((_, i) => i !== Number(t.dataset.i)) });
+ if (t.dataset.action === 'addlang') {
+ const lang = root.querySelector('select[name="newlang"]').value;
+ if (lang) update({ languages: [...s.languages, { lang, level: 'B1' }] });
+ }
+ if (t.dataset.action === 'logout') app.logout();
+ };
+}
diff --git a/public/js/views/triage.js b/public/js/views/triage.js
new file mode 100644
index 0000000..750c70b
--- /dev/null
+++ b/public/js/views/triage.js
@@ -0,0 +1,85 @@
+// Quick first pass: one school at a time, Keep or Drop. Schools with hard problems (language you
+// don't speak, unrelated subject, unsafe country) come first, with the reasons shown.
+
+import { html, bar } from '../ui.js';
+import { shortName, place, languageFit, subjectFit, netCost, moneyRange, monthlyGrant, money } from '../metrics.js';
+
+/** Reasons a school is probably not worth comparing. Empty = nothing obviously wrong. */
+export function concerns(s, app) {
+ const out = [];
+ const lang = languageFit(s, app.settings.languages);
+ if (lang.status === 'fail') out.push(`Language: ${lang.text.replace('✗ ', '')}`);
+ const subj = subjectFit(s);
+ if (subj.rank <= 1) out.push(`Subject area: ${subj.text}`);
+ const c = app.data.countries?.[s.country];
+ if (c && c.stabilityScore <= 3) out.push(`Country stability ${c.stabilityScore}/10 (MFA: ${c.mfaAdvisory?.level})`);
+ const r = s.research;
+ if (r && r.safety.score <= 3) out.push(`City safety ${r.safety.score}/10`);
+ if (r && r.aiRobotics.access.score <= 2) out.push(`Few relevant courses for you (access ${r.aiRobotics.access.score}/10)`);
+ return out;
+}
+
+export function render(root, app) {
+ const all = app.data.schools.map((s) => ({ s, st: app.state.stats.get(s.code) }));
+ const queue = all
+ .filter(({ st }) => !st.reviewed && !st.dropped)
+ .map((x) => ({ ...x, why: concerns(x.s, app) }))
+ .sort((x, y) => y.why.length - x.why.length);
+ const done = all.length - queue.length;
+
+ if (!queue.length) {
+ root.innerHTML = String(html`
+
+ Triage done
+ You've been through all ${all.length} schools. Now the comparisons do the rest.
+ Start comparing
+ `);
+ return;
+ }
+
+ const { s, why } = queue[0];
+ const r = s.research;
+ const n = netCost(s, app.settings, app.data);
+ const g = monthlyGrant(s, app.settings, app.data);
+ root.innerHTML = String(html`
+
+
+ ${done} / ${all.length} reviewed
+
+ Optional first pass. Drop the obvious no-gos so your picks go to real candidates. Problem schools come first.
+
+
+ ${s.flag}
+ ${shortName(s)} ${place(s)}
+
+ ${why.length ? html`${why.map((w) => html`${w} `)} ` : ''}
+ ${r ? html`
+ ${r.summary}
+
+ AI research ${bar(r.aiRobotics.academic.score)}
+ Course access ${bar(r.aiRobotics.access.score)}
+ Social / calm ${r.social.score} / ${r.solitude.score}
+ Climb / hike / ocean ${r.nature.climbing.score} / ${r.nature.hiking.score} / ${r.nature.ocean.score}
+ CTU money ${money(g.eur, app.settings, app.data)}/mo
+ Out of pocket ${n ? moneyRange([n.lo, n.hi], app.settings, app.data, { compact: true }) : '–'}
+
+ ${r.watchouts.length ? html`${r.watchouts.slice(0, 3).map((w) => html`${w} `)} ` : ''}`
+ : html`Research pending: judge from the catalog for now, or keep it and decide later.
`}
+ All details
+
+
+ `);
+
+ root.onclick = (e) => {
+ const t = e.target.closest('[data-action]');
+ if (!t) return;
+ if (t.dataset.action === 'drop') app.drop(s.code);
+ if (t.dataset.action === 'keep') app.review(s.code);
+ if (t.dataset.action === 'open') app.navigate(`#/school/${t.dataset.slug}`);
+ };
+}
diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest
new file mode 100644
index 0000000..ef1dd1c
--- /dev/null
+++ b/public/manifest.webmanifest
@@ -0,0 +1,15 @@
+{
+ "name": "Elorasmus",
+ "short_name": "Elorasmus",
+ "description": "Pick one of two exchange schools, again and again, and let Elo build your ranking.",
+ "start_url": "./",
+ "scope": "./",
+ "display": "standalone",
+ "background_color": "#f6f4ef",
+ "theme_color": "#f6f4ef",
+ "icons": [
+ { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
+ { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
+ { "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml" }
+ ]
+}
diff --git a/scripts/make_icons.py b/scripts/make_icons.py
new file mode 100644
index 0000000..1e41341
--- /dev/null
+++ b/scripts/make_icons.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Rasterise the app icon (same geometry as public/icons/icon.svg) to PNGs, stdlib only.
+
+Usage: python3 -I scripts/make_icons.py
+Writes public/icons/icon-192.png, icon-512.png (rounded, transparent corners) and
+apple-touch-icon.png (180 px, full-bleed: iOS applies its own mask).
+"""
+import os
+import struct
+import zlib
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+BG, TEAL, ORANGE, LIGHT = (0x14, 0x20, 0x2B), (0x16, 0xA3, 0x94), (0xE8, 0x89, 0x3A), (0xF6, 0xF4, 0xEF)
+C1, C2, R = (24.3, 32.0), (39.7, 32.0), 15.4 # in a 64x64 design grid
+
+
+def colour_at(x, y, rounded):
+ if rounded: # rounded rect, radius 14
+ cx, cy = min(max(x, 14), 50), min(max(y, 14), 50)
+ if (x - cx) ** 2 + (y - cy) ** 2 > 14 ** 2:
+ return None
+ in1 = (x - C1[0]) ** 2 + (y - C1[1]) ** 2 <= R * R
+ in2 = (x - C2[0]) ** 2 + (y - C2[1]) ** 2 <= R * R
+ return LIGHT if in1 and in2 else ORANGE if in2 else TEAL if in1 else BG
+
+
+def render(size, rounded, ss=4):
+ rows = []
+ for py in range(size):
+ row = bytearray([0]) # PNG filter type 0
+ for px in range(size):
+ acc, alpha = [0, 0, 0], 0
+ for sy in range(ss):
+ for sx in range(ss):
+ c = colour_at((px + (sx + .5) / ss) * 64 / size, (py + (sy + .5) / ss) * 64 / size, rounded)
+ if c:
+ alpha += 1
+ for i in range(3):
+ acc[i] += c[i]
+ n = ss * ss
+ row += bytes([round(acc[i] / alpha) if alpha else 0 for i in range(3)] + [round(255 * alpha / n)])
+ rows.append(bytes(row))
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ ihdr = struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0) # 8-bit RGBA
+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + chunk(b"IEND", b"")
+
+
+for name, size, rounded in (("icon-192.png", 192, True), ("icon-512.png", 512, True), ("apple-touch-icon.png", 180, False)):
+ path = os.path.join(ROOT, "public", "icons", name)
+ with open(path, "wb") as f:
+ f.write(render(size, rounded))
+ print(path, os.path.getsize(path), "bytes")