/* ============================================================ FLEX Essay Trainer — app.js SPA на ванильном JS поверх дизайн-системы KT AI. Хранение: /api/essays (server → data.json) + localStorage ( черновик, сессия, достижения, тёмная тема — переживает перезагрузку). ============================================================ */ "use strict"; (function () { const APP_KEY = "flex_essay_trainer_v1"; /* ---------- STATE ---------- */ const state = { view: "home", essays: [], // все сохранённые (с сервера) session: null, // активная/паузная сессия currentResult: null, // только что оценённое эссе historyQuery: "", theme: "light", aiAvailable: false, toast: null }; const $root = document.getElementById("root"); const $navCount = document.getElementById("nav-essays-count"); const $navStreak = document.getElementById("nav-streak"); /* ---------- PERSISTENCE (localStorage) ---------- */ function saveLocal() { try { localStorage.setItem(APP_KEY, JSON.stringify({ theme: state.theme, session: state.session, achievements: state.achievements })); } catch (_) {} } function loadLocal() { try { const s = JSON.parse(localStorage.getItem(APP_KEY) || "{}"); state.theme = s.theme || "light"; state.session = s.session || null; state.achievements = s.achievements || {}; return s; } catch (_) { return {}; } } /* ---------- API ---------- */ async function api(path, opts) { const res = await fetch(path, opts); let data = {}; try { data = await res.json(); } catch (_) {} if (!res.ok) throw new Error((data && data.error) || ("Ошибка " + res.status)); return data; } const apiGet = (p) => api(p, { method: "GET" }); const apiPost = (p, body) => api(p, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); async function loadEssays() { try { state.essays = (await apiGet("api/essays")).map(byDate).reverse(); } catch (_) { state.essays = []; } updateBadge(); } function byDate(a) { return a; } async function saveSession(s) { state.session = s; await apiPost("api/essays", { action: "session", ...s }); saveLocal(); } async function persistEssay(rec) { await apiPost("api/essays", { action: "save", ...rec }); state.session = null; saveLocal(); } async function initAI() { try { const h = await apiGet("api/health"); state.aiAvailable = !!h.ai; window.AI_ASSESS_AVAILABLE = h.ai; } catch (_) { state.aiAvailable = false; window.AI_ASSESS_AVAILABLE = false; } } /* ---------- LEVELS ---------- */ const LEVELS = [ { min: 0, max: 4.9, name: "Beginner", tone: "gray" }, { min: 5.0, max: 6.4, name: "Developing", tone: "blue" }, { min: 6.5, max: 7.9, name: "Strong", tone: "green" }, { min: 8.0, max: 10, name: "Excellent", tone: "purple" } ]; function levelFor(score) { return LEVELS.find((l) => score >= l.min && score <= l.max) || LEVELS[0]; } /* ---------- STATS ---------- */ function completed() { return state.essays.filter((e) => e.status === "completed"); } function avg(arr) { return arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0; } function stats() { const c = completed(); const scores = c.map((e) => (e.evaluation && e.evaluation.overall) || 0); const bestScore = c.length ? Math.max.apply(null, scores) : 0; const st = streaks(); const avgLen = avg(c.map((e) => e.charCount || 0)); const avgTime = avg(c.map((e) => e.timeUsed || 0)); return { count: c.length, avgScore: avg(scores), best: bestScore, current: st.current, bestStreak: st.best, avgLen: avgLen, avgTime: avgTime }; } function streaks() { const c = completed(); const days = [...new Set(c.map((e) => new Date(e.submittedAt).toDateString()))].sort(); let cur = 0; // current streak — идущая цепочка дней, заканчивающаяся сегодня/вчера const today = new Date().toDateString(); const yesterday = new Date(Date.now() - 864e5).toDateString(); const daySet = new Set(days); let d = new Date(); if (!daySet.has(d.toDateString()) && daySet.has(new Date(Date.now() - 864e5).toDateString())) d = new Date(Date.now() - 864e5); while (daySet.has(d.toDateString())) { cur++; d = new Date(d.getTime() - 864e5); } // best streak из всех let bestS = 0; for (let i = 0; i < days.length; i++) { let run = 1; for (let j = i + 1; j < days.length; j++) { if ((new Date(days[j]).getTime() - new Date(days[j - 1]).getTime()) / 864e5 === 1) run++; else break; } bestS = Math.max(bestS, run); } return { current: cur, best: bestS }; } /* ---------- ACHIEVEMENTS ---------- */ const ACHIEVEMENTS = [ { id: "first", name: "First Essay", desc: "Your first submitted essay", icon: "pencil" }, { id: "five", name: "5 Essays", desc: "Complete 5 essays", icon: "clipboard" }, { id: "ten", name: "10 Essays", desc: "Complete 10 essays", icon: "file" }, { id: "fifteen", name: "15-Minute Master", desc: "Use exactly 15 min on an essay", icon: "clock" }, { id: "aver8", name: "8+ Average", desc: "Average overall score 8.0 or higher", icon: "chart" }, { id: "consistent", name: "Consistent Writer", desc: "Keep a 3-day streak", icon: "calendar" }, { id: "voice", name: "Personal Voice", desc: "Score 8+ on Personal Voice", icon: "user" }, { id: "grammar", name: "Grammar Master", desc: "Score 8+ on Grammar & Vocabulary", icon: "check-circle" } ]; function checkAchievements(essay) { const c = completed(); // только что сохранённое эссе ещё может отсутствовать в state.essays const hasNew = !!(essay && essay.status === "completed") && !c.some((e) => e.id === essay.id); const n = c.length + (hasNew ? 1 : 0); const scores = c.map((e) => (e.evaluation && e.evaluation.overall) || 0); if (hasNew && essay.evaluation) scores.push(essay.evaluation.overall || 0); const earned = {}; const add = (id) => { earned[id] = true; }; if (n >= 1) add("first"); if (n >= 5) add("five"); if (n >= 10) add("ten"); if (essay && Math.ceil((essay.timeUsed || 0) / 60) >= 15) add("fifteen"); if (scores.length && avg(scores) >= 8) add("aver8"); if (streaks().current >= 3) add("consistent"); const ev = essay && essay.evaluation; if (ev && ((ev.scores.voice) || 0) >= 8) add("voice"); if (ev && ((ev.scores.grammar) || 0) >= 8) add("grammar"); const newOnes = Object.keys(earned).filter((k) => !state.achievements[k]); Object.assign(state.achievements, earned); saveLocal(); return newOnes; } /* ---------- TIME / CHAR HELPERS ---------- */ function fmtTime(sec) { sec = Math.max(0, sec); const m = Math.floor(sec / 60).toString().padStart(2, "0"); const s = Math.floor(sec % 60).toString().padStart(2, "0"); return m + ":" + s; } function fmtClock(sec) { const m = Math.floor(sec / 60); const s = (sec % 60).toString().padStart(2, "0"); return (m ? m + " min " : "") + s + " sec"; } function charStatus(n) { if (n < 250) return { label: "Too short", tone: "warn", ok: false }; if (n < 1000) return { label: "Good length", tone: "ok", ok: true }; return { label: "Excellent length", tone: "blue", ok: true }; } /* ---------- ROUTER / RENDER ---------- */ function nav(view, param) { if (view === state.view && JSON.stringify(state._vparam) === JSON.stringify(param)) { render(); return; } state.view = view; state._vparam = param; const el = document.getElementById("view"); if (el) { el.style.transition = "opacity .14s ease"; el.style.opacity = "0"; setTimeout(() => { render(); el.style.opacity = "1"; }, 100); } else render(); } const VIEW_TITLES = { home: ["#home", "Home"], practice: ["#pencil", "Choose a topic"], writing: ["#clock", "Writing"], result: ["#sparkles", "Evaluation"], progress: ["#dashboard", "My Progress"], history: ["#history", "Essay History"] }; function updateBadge() { const s = stats(); if ($navCount) $navCount.textContent = completed().length; if ($navStreak) $navStreak.textContent = (s.current || 0) + " day" + (s.current === 1 ? "" : "s"); const t = document.getElementById("topbarTitle"); if (t) { const [ic, label] = VIEW_TITLES[state.view] || VIEW_TITLES.home; t.innerHTML = `${label}`; } const ab = document.getElementById("aiBadge"); if (ab) { if (state.aiAvailable) { ab.dataset.tone = "green"; ab.innerHTML = ` AI ready`; } else { ab.dataset.tone = "orange"; ab.innerHTML = ` Demo evaluation`; } } } function render() { const map = { home: renderHome, practice: renderPractice, writing: renderWriting, result: renderResult, progress: renderProgress, history: renderHistory }; const fn = map[state.view] || renderHome; const el = document.getElementById("view"); el.innerHTML = fn(); // навигация активация document.querySelectorAll(".kt-ai-nav-item").forEach((n) => { n.dataset.active = (n.dataset.route === state.view || (state.view === "history" && n.dataset.route === "history")) ? "true" : "false"; }); updateBadge(); bindView(); } /* ================= HOME ================= */ function renderHome() { const s = stats(); const tiles = [ { v: s.count, l: "Essays completed", i: "clipboard" }, { v: s.avgScore.toFixed(1), l: "Average score", i: "chart" }, { v: s.best.toFixed(1), l: "Best score", i: "trophy" }, { v: s.current, l: "Current streak", i: "calendar" } ]; const lvl = s.count ? levelFor(s.avgScore) : null; return `
FLEX Essay Trainer

Practice. Write. Improve.
Get ready for FLEX.

Practice FLEX-style essay writing with realistic 15-minute challenges and personalized AI feedback.

${tiles.map((t) => `
${t.v} ${t.l}
`).join("")}
${s.count ? `
${lvl.name}
BeginnerDevelopingStrongExcellent
${s.avgScore.toFixed(1)}/10
your average
` : `
No essays yet

Write your first 15-minute essay to start tracking progress.

`}

How it works

${[ { i: "pencil", t: "Pick a topic", p: "Six essay types, original prompts, FLEX-style difficulty." }, { i: "clock", t: "15:00 challenge", p: "Strict timer, 250–1500 chars, auto-submit at zero." }, { i: "lightbulb", t: "AI feedback", p: "7 scored categories, concrete tips, one thing to improve." } ].map((c) => `

${c.t}

${c.p}

`).join("")}
This is a practice tool, not an official FLEX program. Scores are AI-based and for training only.
`; } function scoreWidth(score, lvl) { // ширина по шкале уровня const pos = (score - lvl.min) / (lvl.max - lvl.min); const base = [0, 25, 50, 75][["gray", "blue", "green", "purple"].indexOf(lvl.tone)]; return Math.round(base + pos * 25); } /* ================= PRACTICE (выбор типа) ================= */ const ESSAY_TYPES = [ { id: "personal", ic: "user", label: "Personal Experience", sub: "An important experience, lesson, decision or change." }, { id: "leadership", ic: "users", label: "Leadership & Teamwork", sub: "Leadership, cooperation, responsibility, working with others." }, { id: "challenge", ic: "warning", label: "Challenge & Problem Solving", sub: "A difficulty, failure or conflict and how you responded." }, { id: "community", ic: "building", label: "Community & Impact", sub: "Helping others, school or community, making a difference." }, { id: "future", ic: "lightbulb", label: "Future Goals & Motivation", sub: "Ambitions, personal growth and future plans." }, { id: "random", ic: "sparkles", label: "Random Topic", sub: "Automatically pick a random essay type." } ]; function renderPractice() { const s = stats(); return `
Choose your challenge
Original FLEX-style prompts. 15 minutes, 250–1500 characters.
${ESSAY_TYPES.map((t) => ` `).join("")}
`; } /* ================= WRITING (редактор + таймер) ================= */ let timerHandle = null; let lastTick = 0; function now() { return Date.now(); } function startSession(type, prompt, resumed) { const s = state.session && resumed ? state.session : { id: "e" + now(), type, typeLabel: (ESSAY_TYPES.find((t) => t.id === type) || { label: type }).label, prompt, startedAt: now(), remaining: 900, // 15:00 paused: false, essay: "", status: "in_progress" }; state.session = s; if (!resumed) saveSession(s); nav("writing"); startTimer(s, resumed ? s.remaining : 900); } function startTimer(s, remaining) { stopTimer(); s.remaining = remaining; s.paused = false; const tick = () => { const rem = s.remaining; const el = document.getElementById("timerVal"); if (el) { el.textContent = fmtTime(rem); el.dataset.warn = rem <= 30 ? "30" : rem <= 120 ? "2" : rem <= 300 ? "5" : rem <= 600 ? "10" : ""; } // warning banner const banner = document.getElementById("warnBanner"); if (banner) { if (rem <= 0) return; if (rem <= 30) { banner.hidden = false; banner.dataset.tone = "risk"; banner.querySelector("span").textContent = "Under 30 seconds — finish your thought now."; } else if (rem <= 120) { banner.hidden = false; banner.dataset.tone = "risk"; banner.querySelector("span").textContent = "2 minutes left."; } else if (rem <= 300) { banner.hidden = false; banner.dataset.tone = "warn"; banner.querySelector("span").textContent = "5 minutes left."; } else if (rem <= 600) { banner.hidden = false; banner.dataset.tone = "info"; banner.querySelector("span").textContent = "10 minutes left."; } else banner.hidden = true; } if (rem <= 0) return finishByTimeout(); }; tick(); lastTick = now(); timerHandle = setInterval(() => { const diff = Math.round((now() - lastTick) / 1000); lastTick = now(); state.session.remaining = Math.max(0, state.session.remaining - diff); tick(); // автосейв каждые ~15 сек if (state.session.remaining % 15 === 0 && !state.session.status) saveSession(state.session); }, 1000); } function stopTimer() { if (timerHandle) { clearInterval(timerHandle); timerHandle = null; } } function renderWriting() { const s = state.session || { type: "personal", typeLabel: "Personal Experience", prompt: "", remaining: 30, essay: "", status: "idle" }; const len = (s.essay || "").length; const st = charStatus(len); const canSubmit = len >= 250; return `
${esc(s.typeLabel)}
${s.paused ? `
Paused
` : ""} ${s.status === "idle" ? `

Your session is waiting

The timer is paused. It will pick up exactly where you left off.

` : ""}
${s.status !== "idle" ? `
${esc(s.prompt || "")}
Time ${fmtTime(s.remaining)}
Characters ${len.toLocaleString()} / 1,500 ${st.label}
${canSubmit ? "" : "Need " + (250 - len) + " more characters"}
` : ""}`; } function bindWriting() { const s = state.session; const ta = document.getElementById("essayText"); if (!ta) return; ta.addEventListener("input", () => { let v = ta.value; if (v.length > 1500) v = v.slice(0, 1500); s.essay = v; const len = v.length; const st = charStatus(len); const st2 = document.getElementById("lenChip"); if (st2) { st2.dataset.tone = st.tone; st2.textContent = st.label; } const strong = ta.parentElement.querySelector(".wcount strong"); if (strong) strong.textContent = len.toLocaleString(); const b = document.getElementById("btnSubmit"); if (b) b.disabled = len < 250; const hint = document.getElementById("needHint"); if (hint) hint.textContent = len < 250 ? "Need " + (250 - len) + " more characters" : ""; }); // авто-пауза при уходе с вкладки (анти-обход) const beforeUnload = (e) => { const live = state.session && state.session.status === "in_progress"; if (live && !state.session.paused) { e.preventDefault(); e.returnValue = ""; } }; window.addEventListener("beforeunload", beforeUnload); document.getElementById("btnBack").onclick = async () => { if (state.view === "writing" && state.session) { if (state.session.essay && !confirm("Save a draft and leave? You can come back to finish.")) return; stopTimer(); state.session.paused = true; state.session.status = "in_progress"; await saveSession({ ...state.session, paused: true }); toast("Session paused — your draft is saved"); nav("practice"); } else nav("practice"); }; document.getElementById("btnDiscard").onclick = async () => { if (!confirm("Discard this essay? This cannot be undone.")) return; if (state.session) await apiPost("api/essays", { action: "discard", id: state.session.id }); state.session = null; saveLocal(); stopTimer(); nav("practice"); }; document.getElementById("btnSubmit").onclick = () => submitEssay(false); } function resumeSession() { if (!state.session) return false; if (state.session.paused) { state.session.paused = false; startTimer(state.session, state.session.remaining); nav("writing"); return true; } return false; } async function submitEssay(auto) { const s = state.session; if (!s) return; const essay = (s.essay || "").trim(); if (auto) { if (essay.length < 250) { /* всё равно сдаём, пометка */ } } stopTimer(); s.autoSubmitted = auto; s.status = "submitting"; s.evaluation = null; const btn = document.getElementById("btnSubmit"); if (btn) { btn.disabled = true; btn.innerHTML = ` Evaluating…`; } document.body.style.cursor = "wait"; try { const evaluation = await window.evaluate({ type: s.type, prompt: s.prompt, essay: s.essay, charCount: s.essay.length, timeUsed: 900 - (s.remaining || 0) }); if (evaluation && evaluation.error) { toast(evaluation.error, "error"); document.body.style.cursor = ""; if (btn) { btn.disabled = false; btn.innerHTML = ` Submit Essay`; } return; } s.status = "completed"; s.evaluation = evaluation; s.submittedAt = new Date().toISOString(); s.timeUsed = 900 - (s.remaining || 0); await persistEssay(s); await loadEssays(); state.currentResult = s; const newlyEarned = checkAchievements(s); if (newlyEarned.length) toast("New achievements: " + ACHIEVEMENTS.filter(a => newlyEarned.includes(a.id)).map(a => a.name).join(", "), "ok"); if (auto) toast("Time is up! Your essay has been submitted.", "ok"); finishing = false; nav("result"); } catch (e) { toast("Ошибка отправки: " + e.message, "error"); document.body.style.cursor = ""; if (btn) { btn.disabled = false; } } } let finishing = false; function finishByTimeout() { stopTimer(); if (state.view !== "writing" || finishing) return; finishing = true; try { submitEssay(true); } finally { /* finishing сбрасывается в submitEssay */ } } /* ================= RESULT (оценка + фидбек) ================= */ const CATS = [ ["content", "Content & Relevance"], ["voice", "Personal Voice"], ["examples", "Examples & Details"], ["organization", "Organization"], ["clarity", "Clarity"], ["grammar", "Grammar & Vocabulary"], ["authenticity", "Authenticity"] ]; function toneForScore(v) { if (v >= 8) return "green"; if (v >= 6.5) return "blue"; if (v >= 5) return "orange"; return "red"; } function renderResult() { const e = state.currentResult; if (!e) return `
No result yet

Pick an essay to see the evaluation.

`; const ev = e.evaluation || {}; const lvl = levelFor(ev.overall || 0); return `
Your evaluation
${esc(e.typeLabel)} · ${fmtDate(e.submittedAt)} · ${fmtClock(e.timeUsed)} · ${e.autoSubmitted ? "auto-submitted" : "submitted"}
${(ev.overall || 0).toFixed(1)}/10
${lvl.name}
Essay length: ${e.charCount.toLocaleString()} characters · Mode: ${ev.mode === "ai" ? "AI evaluation" : "Demo evaluation"}
${CATS.map(([k, label]) => `
${label}${((ev.scores && ev.scores[k]) || 0).toFixed(1)}
`).join("")}
What's Strong
What to Improve
How to Improve
Strongest Part
“${esc(ev.strongestPart || "")}”

A line that shows your personal voice or strong thinking.

${ev.flexNotes && ev.flexNotes.length ? `
Qualities shown in this essay
${ev.flexNotes.map(f => `${esc(f)}`).join("")}
` : ""}
Next Challenge

Based on your weakest skill, try:

${esc((ev.nextChallenge && ev.nextChallenge.label) || "")}
Improvement challenge

Rewrite this sentence from your essay to make it clearer:

${esc(ev.improvementSentence || "—")}
This AI score is for practice only. It is not an official FLEX evaluation and cannot predict your chances of selection.
`; } function bindResult() { const nx = document.getElementById("btnNext"); if (nx) nx.onclick = () => { const nc = state.currentResult && state.currentResult.evaluation && state.currentResult.evaluation.nextChallenge; startSession((nc && nc.type) || "personal", randomPrompt((nc && nc.type) || "personal")); }; const he = document.getElementById("btnHomeR"); if (he) he.onclick = () => { state.currentResult = null; nav("home"); }; const ag = document.getElementById("btnAgain"); if (ag) ag.onclick = () => { state.currentResult = null; nav("practice"); }; const emp = document.getElementById("btnEmptyR"); if (emp) emp.onclick = () => nav("practice"); const ce = document.getElementById("btnChallEval"); if (ce) ce.onclick = () => { const orig = (state.currentResult && state.currentResult.evaluation && state.currentResult.evaluation.improvementSentence) || ""; const nv = document.getElementById("challNew").value; const r = critiqueSentence(orig, nv); const v = document.getElementById("challVerdict"); const tone = r.verdict === "good" ? "ok" : r.verdict === "ok" ? "blue" : "warn"; v.innerHTML = `${r.verdict === "good" ? "Stronger" : "Getting there"} ${esc(r.text)}`; if (r.score) v.innerHTML += ` ${r.score.toFixed(1)} /10 clarity`; }; } /* ================= PROGRESS (дашборд) ================= */ function renderProgress() { const s = stats(); const c = completed(); const lvl = s.count ? levelFor(s.avgScore) : null; // график по времени const series = c.slice().map((e) => ({ label: fmtShortDate(e.submittedAt), value: (e.evaluation && e.evaluation.overall) || 0 })); // средние по категориям const catAvg = {}; CATS.forEach(([k]) => { catAvg[k] = avg(c.map((e) => (e.evaluation && e.evaluation.scores && e.evaluation.scores[k]) || 0)); }); const sorted = [...CATS].sort((a, b) => (catAvg[b[0]] || 0) - (catAvg[a[0]] || 0)); const strong = sorted[0], weak = sorted[sorted.length - 1]; const kpis = [ { l: "Essays completed", v: s.count, i: "clipboard" }, { l: "Average score", v: s.avgScore.toFixed(1), i: "chart" }, { l: "Best score", v: s.best.toFixed(1), i: "trophy" }, { l: "Avg essay length", v: Math.round(s.avgLen).toLocaleString(), i: "file" }, { l: "Avg completion time", v: fmtClock(s.avgTime), i: "clock" }, { l: "Current streak", v: s.current, i: "calendar" }, { l: "Best streak", v: s.bestStreak, i: "calendar" } ]; const ach = ACHIEVEMENTS.map((a) => ({ ...a, got: !!(state.achievements && state.achievements[a.id]) })); return ` ${s.count ? `
You are a ${lvl.name} writer${s.avgScore >= 8 ? " — excellent range" : ""}. Strongest: ${strong[1]} (${(catAvg[strong[0]] || 0).toFixed(1)}). Focus area: ${weak[1]} (${(catAvg[weak[0]] || 0).toFixed(1)}).
` : `
No progress data yet

Complete your first essay to see your statistics here.

`}
${kpis.map((k) => `
6 ? 'data-long="true"' : ""}>${k.v} ${k.l}
`).join("")}
${series.length ? `

Average score over time

last ${series.length} essays
${lineChart(series)}
` : ""} ${s.count ? `

Skill breakdown

by category average
${sorted.map(([k, label]) => `
${label}
${(catAvg[k] || 0).toFixed(1)}
`).join("")}
Strongest: ${strong[1]} Focus: ${weak[1]}
` : ""}

Achievements

${ach.filter(a => a.got).length} / ${ach.length} unlocked
${ach.map((a) => `
${a.name} ${a.got ? "" : ``}
`).join("")}
`; } function lineChart(pts) { const W = 640, H = 170, pad = { l: 28, r: 12, t: 12, b: 28 }; const iw = W - pad.l - pad.r, ih = H - pad.t - pad.b; const n = pts.length || 1; const x = i => pad.l + (n === 1 ? iw / 2 : (i / (n - 1)) * iw); const y = v => pad.t + ih - (v / 10) * ih; const path = pts.map((p, i) => (i ? "L" : "M") + x(i).toFixed(1) + "," + y(p.value).toFixed(1)).join(" "); const area = "M" + x(0).toFixed(1) + "," + (pad.t + ih).toFixed(1) + " " + pts.map((p, i) => "L" + x(i).toFixed(1) + "," + y(p.value).toFixed(1)).join(" ") + " L" + x(n - 1).toFixed(1) + "," + (pad.t + ih).toFixed(1) + " Z"; const grid = [0, 2.5, 5, 7.5, 10].map(g => ` ${g}`).join(""); const dots = pts.map((p, i) => `${p.label}: ${p.value.toFixed(1)}`).join(""); const labels = pts.map((p, i) => `${p.label}`).join(""); return ` ${grid}${dots}${labels} `; } /* ================= HISTORY ================= */ function renderHistory() { const q = (state.historyQuery || "").toLowerCase(); const list = state.essays.filter((e) => e.status === "completed" && (!q || (e.typeLabel + " " + (e.prompt || "")).toLowerCase().includes(q))); return `
Essay history
${list.length} saved ${list.length === 1 ? "essay" : "essays"}
${list.length ? `
${list.map((e) => ` `).join("")}
DateTypePromptScoreLengthTime
${fmtDate(e.submittedAt)} ${esc(e.typeLabel)} ${esc(e.prompt || "")} ${((e.evaluation && e.evaluation.overall) || 0).toFixed(1)} ${(e.charCount || 0).toLocaleString()} ${fmtClock(e.timeUsed || 0)}
` : `
No essays yet

Finished essays will appear here with full scores and feedback.

`}`; } function bindHistory() { const sr = document.getElementById("hSearch"); if (sr) { const on = () => { state.historyQuery = sr.value; render(); const s = document.getElementById("hSearch"); if (s) { s.focus(); s.setSelectionRange(s.value.length, s.value.length); } }; sr.addEventListener("input", on); } const st = document.getElementById("hStart"); if (st) st.onclick = () => nav("practice"); document.querySelectorAll(".hrow").forEach((r) => { r.style.cursor = "pointer"; r.onclick = () => openEssayDetail(r.dataset.id); }); } function openEssayDetail(id) { const e = state.essays.find((x) => x.id === id); if (!e) return; state.currentResult = e; nav("result"); } /* ================= BINDINGS ================= */ function bindView() { // home const bs2 = document.getElementById("btnStart2"); if (bs2) bs2.onclick = () => nav("practice"); const bp = document.getElementById("btnProg"); if (bp) bp.onclick = () => nav("progress"); const pp = document.getElementById("pStart"); if (pp) pp.onclick = () => nav("practice"); // practice document.querySelectorAll(".ptile").forEach((t) => { t.onclick = () => { let type = t.dataset.type; if (type === "random") { const opts = ESSAY_TYPES.filter(x => x.id !== "random"); type = opts[rand(opts.length)].id; } startSession(type, randomPrompt(type)); }; }); if (state.view === "writing") bindWriting(); if (state.view === "result") bindResult(); if (state.view === "history") bindHistory(); const br = document.getElementById("btnResume"); if (br) br.onclick = () => { const s = state.session; s.status = "in_progress"; s.paused = false; nav("writing"); startTimer(s, s.remaining); }; // nav + theme bindShell(); } function goNav(r) { const live = state.session && (state.session.status === "in_progress" || state.session.paused); if (live && state.view !== "writing") { if (r === "practice") { state.session.status = "in_progress"; nav("writing"); resumeSession(); return; } // уход из активной сессии → пауза + экран «Resume» (таймер не идёт) if (!confirm("Pause your essay and continue later? Your progress is saved.")) return; state.session.status = "in_progress"; state.session.paused = true; saveLocal(); nav("writing"); return; } nav(r); } function bindShell() { document.querySelectorAll(".kt-ai-nav-item[data-route]").forEach((n) => { n.onclick = () => goNav(n.dataset.route); }); const nm = document.getElementById("navMain"); if (nm) nm.onclick = () => { const live = state.session && (state.session.status === "in_progress" || state.session.paused); if (live) { state.session.status = "in_progress"; nav("writing"); resumeSession(); } else nav("practice"); }; const theme = document.getElementById("themeBtn"); if (theme) theme.onclick = toggleTheme; const brand = document.getElementById("brandHome"); if (brand) brand.onclick = () => nav("home"); const bs = document.getElementById("btnStart"); if (bs) bs.onclick = () => { if (state.session && state.session.paused) { state.session.status = "in_progress"; nav("writing"); resumeSession(); } else nav("practice"); }; } function toggleTheme() { state.theme = state.theme === "light" ? "dark" : "light"; document.documentElement.setAttribute("data-theme", state.theme); const b = document.getElementById("themeBtn"); if (b) b.innerHTML = ``; saveLocal(); } /* ================= PROMPTS — оригинальные, без копирования FLEX ================= */ const PROMPTS = { personal: [ "Tell about a moment that changed the way you see the world. What is it and why did it stay with you?", "Describe a decision that seemed difficult at the time but you are now glad about. What did it teach?", "Write about a time you had to leave something familiar — a place, a habit, a group. How did you cope?", "Tell about a lesson you learned the hard way. How did it shape who you are?" ], leadership: [ "Describe a time you helped a group reach a goal without formal authority. What did you organize?", "Write about a moment when teamwork failed and what you did to rebuild trust.", "Tell about a responsibility you took on that no one asked you to. Why did you step up?", "Describe how you balanced different opinions inside a team. What was your solution?" ], challenge: [ "Tell about a failure that you now consider a turning point. What did you try differently?", "Write about a conflict you had to resolve. How did you reach an agreement?", "Describe a difficult situation at school or at home and how you responded.", "Tell about a time you were afraid — and did it anyway. What happened afterward?" ], community: [ "Describe something you did to improve your school or neighborhood. What changed because of it?", "Write about volunteering or helping someone. What did you learn from them?", "Tell about a community (school, club, family) that shaped you. How did you give back to it?", "Describe a small act of kindness you organized. How did it spread?" ], future: [ "Tell about a skill or goal you want to master in the next two years. Why is it meaningful to you?", "Write about what an international exchange could teach you beyond travel. What do you want to bring home?", "Describe your ideal version of yourself in 5 years. What habits would get you there?", "Tell about a cause or idea you want to be known for. Why is it important?" ] }; function randomPrompt(type) { const arr = PROMPTS[type] || PROMPTS.personal; return arr[rand(arr.length)]; } /* ================= HELPERS ================= */ function esc(s) { return String(s == null ? "" : s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); } function fmtDate(iso) { if (!iso) return "—"; try { const d = new Date(iso); return d.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }); } catch (_) { return "—"; } } function fmtShortDate(iso) { if (!iso) return ""; const d = new Date(iso); return d.toLocaleDateString("en-GB", { day: "numeric", month: "short" }); } function toast(msg, tone) { const t = document.getElementById("app-toast"); if (!t) return; t.textContent = msg; t.dataset.tone = tone || "info"; t.classList.remove("show"); void t.offsetWidth; t.classList.add("show"); t.setAttribute("data-text", msg); clearTimeout(toast._t); toast._t = setTimeout(() => t.classList.remove("show"), 3200); } /* ================= INIT ================= */ function init() { loadLocal(); document.documentElement.setAttribute("data-theme", state.theme); const tb = document.getElementById("themeBtn"); if (tb) tb.innerHTML = ``; (async () => { await initAI(); await loadEssays(); // восстанавливаем прерванную сессию if (state.session && state.session.status === "in_progress" && !state.session.paused && state.view === "home") { render(); return; // оставим на home, кнопка покажет «resume» } render(); })(); } // Навигация через делегирование на весь документ (пункты меню уже биндятся в bindShell) window.__nav = (v) => nav(v); window.evaluate = evaluate; // ai.js window.rand = rand; init(); })();