961 lines
48 KiB
JavaScript
961 lines
48 KiB
JavaScript
/* ============================================================
|
||
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 = `<svg class="kt-icon"><use href="${ic}"></use></svg><span>${label}</span>`; }
|
||
const ab = document.getElementById("aiBadge");
|
||
if (ab) {
|
||
if (state.aiAvailable) { ab.dataset.tone = "green"; ab.innerHTML = `<svg class="kt-icon kt-icon-sm"><use href="#sparkles"></use></svg> AI ready`; }
|
||
else { ab.dataset.tone = "orange"; ab.innerHTML = `<svg class="kt-icon kt-icon-sm"><use href="#lightbulb"></use></svg> 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 `
|
||
<section class="kt-ai-hero" data-align="center" style="padding-block:clamp(40px,7vh,64px) clamp(24px,4vh,40px)">
|
||
<div class="kt-ai-wrap">
|
||
<div class="kt-ai-chip" data-tone="blue" style="margin-bottom:var(--kt-ai-space-5)">
|
||
<svg class="kt-icon kt-icon-sm"><use href="#sparkles"></use></svg> FLEX Essay Trainer
|
||
</div>
|
||
<h1 class="h1-home">Practice. Write. Improve.<br>Get ready for FLEX.</h1>
|
||
<p class="kt-ai-hero-sub">Practice FLEX-style essay writing with realistic 15-minute challenges and personalized AI feedback.</p>
|
||
<div class="kt-ai-hero-actions">
|
||
<button class="kt-ai-btn" data-variant="primary" data-size="lg" id="btnStart">
|
||
<svg class="kt-icon"><use href="#play"></use></svg> Start Practice
|
||
</button>
|
||
<button class="kt-ai-btn" data-size="lg" id="btnProg">
|
||
<svg class="kt-icon"><use href="#dashboard"></use></svg> My Progress
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<section class="kt-ai-section" data-divider="true" style="padding-block:clamp(24px,5vh,40px)">
|
||
<div class="kt-ai-wrap" style="width:min(1080px,92vw)">
|
||
<div class="kt-ai-kpi-strip" data-cards="true" style="margin-bottom:var(--kt-ai-space-6)">
|
||
${tiles.map((t) => `
|
||
<div class="kt-ai-kpi">
|
||
<svg class="kt-icon kpi-ic"><use href="#${t.i}"></use></svg>
|
||
<span class="value">${t.v}</span>
|
||
<span class="label">${t.l}</span>
|
||
</div>`).join("")}
|
||
</div>
|
||
${s.count ? `
|
||
<div class="kt-ai-card" style="margin-bottom:var(--kt-ai-space-8)">
|
||
<div style="display:flex;align-items:center;gap:14px;flex-wrap:wrap">
|
||
<div class="level-badge" data-tone="${lvl.tone}">
|
||
<svg class="kt-icon"><use href="#trophy"></use></svg> ${lvl.name}
|
||
</div>
|
||
<div style="flex:1;min-width:180px">
|
||
<div class="track"><div class="track-fill" data-tone="${lvl.tone}" style="width:${scoreWidth(s.avgScore, lvl)}%"></div></div>
|
||
<div class="track-labels"><span>Beginner</span><span>Developing</span><span>Strong</span><span>Excellent</span></div>
|
||
</div>
|
||
<div style="text-align:right">
|
||
<div class="lvl-score">${s.avgScore.toFixed(1)}<span class="lvl-x">/10</span></div>
|
||
<div class="meta">your average</div>
|
||
</div>
|
||
</div>
|
||
</div>` : `
|
||
<div class="kt-ai-empty" style="margin-bottom:var(--kt-ai-space-8)">
|
||
<svg class="kt-icon kt-icon-lg"><use href="#rocket"></use></svg>
|
||
<div class="title">No essays yet</div>
|
||
<p>Write your first 15-minute essay to start tracking progress.</p>
|
||
<button class="kt-ai-btn" id="btnStart2" data-size="sm">Choose a topic</button>
|
||
</div>`}
|
||
<div class="kt-ai-section-head" style="max-width:100%;margin-bottom:var(--kt-ai-space-5)">
|
||
<h2 style="font-size:var(--kt-ai-text-lg)">How it works</h2>
|
||
</div>
|
||
<div class="kt-ai-grid" data-cols="3">
|
||
${[
|
||
{ 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) => `
|
||
<article class="kt-ai-tile">
|
||
<span class="kt-ai-tile-icon"><svg class="kt-icon"><use href="#${c.i}"></use></svg></span>
|
||
<h3>${c.t}</h3><p>${c.p}</p>
|
||
</article>`).join("")}
|
||
</div>
|
||
<div class="disclaimer" style="margin-top:var(--kt-ai-space-8)">
|
||
<svg class="kt-icon"><use href="#info"></use></svg>
|
||
<span>This is a practice tool, not an official FLEX program. Scores are AI-based and for training only.</span>
|
||
</div>
|
||
</div>
|
||
</section>`;
|
||
}
|
||
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 `
|
||
<div class="vhead"><div class="vtitle">Choose your challenge</div>
|
||
<div class="vsub">Original FLEX-style prompts. 15 minutes, 250–1500 characters.</div></div>
|
||
<div class="pgrid">
|
||
${ESSAY_TYPES.map((t) => `
|
||
<button class="ptile" data-type="${t.id}">
|
||
<span class="ptile-ic"><svg class="kt-icon kt-icon-lg"><use href="#${t.ic}"></use></svg></span>
|
||
<div class="ptile-b">
|
||
<div class="ptile-t">${t.label}</div>
|
||
<div class="ptile-s">${t.sub}</div>
|
||
</div>
|
||
<svg class="kt-icon ktile-arrow"><use href="#chevronRight"></use></svg>
|
||
</button>`).join("")}
|
||
</div>`;
|
||
}
|
||
|
||
/* ================= 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 `
|
||
<div class="vhead whead">
|
||
<button class="kt-ai-link" id="btnBack"><svg class="kt-icon kt-icon-sm"><use href="#arrowLeft"></use></svg> <span>Back to topics</span></button>
|
||
<div class="wtype"><svg class="kt-icon"><use href="#${(ESSAY_TYPES.find(t=>t.id===s.type)||{ic:"sparkles"}).ic}"></use></svg> ${esc(s.typeLabel)}</div>
|
||
${s.paused ? `<div class="kt-ai-chip" data-tone="blue" style="margin-left:auto"><svg class="kt-icon kt-icon-sm"><use href="#clock"></use></svg> Paused</div>` : ""}
|
||
${s.status === "idle" ? `<div class="idle-card kt-ai-card" style="max-width:520px;margin:var(--kt-ai-space-8) auto">
|
||
<svg class="kt-icon kt-icon-lg" style="margin-bottom:12px"><use href="#rocket"></use></svg>
|
||
<h3 style="font-size:var(--kt-ai-text-lg);margin-bottom:8px">Your session is waiting</h3>
|
||
<p class="meta" style="margin-bottom:16px">The timer is paused. It will pick up exactly where you left off.</p>
|
||
<button class="kt-ai-btn" data-variant="primary" id="btnResume"><svg class="kt-icon"><use href="#play"></use></svg> Resume writing</button>
|
||
</div>` : ""}
|
||
</div>
|
||
${s.status !== "idle" ? `
|
||
<div class="wcard kt-ai-card">
|
||
<div class="wprompt">${esc(s.prompt || "")}</div>
|
||
<textarea id="essayText" class="kt-ai-textarea essay-area" placeholder="Start writing. Aim for 250–1,500 characters…">${esc(s.essay || "")}</textarea>
|
||
<div class="wstat">
|
||
<div class="wtime">
|
||
<svg class="kt-icon"><use href="#clock"></use></svg>
|
||
<span class="meta" id="timeLabel">Time</span>
|
||
<strong id="timerVal" data-warn="">${fmtTime(s.remaining)}</strong>
|
||
</div>
|
||
<div class="wcount">
|
||
<span class="meta">Characters</span>
|
||
<strong>${len.toLocaleString()}</strong><span class="meta"> / 1,500</span>
|
||
<span class="kt-ai-chip" data-tone="${st.tone}" id="lenChip">${st.label}</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="kt-ai-banner" id="warnBanner" data-tone="info" hidden><svg class="kt-icon"><use href="#info"></use></svg><span></span></div>
|
||
<div class="wactions">
|
||
<button class="kt-ai-btn" data-variant="danger" id="btnDiscard"><svg class="kt-icon"><use href="#trash"></use></svg> Discard</button>
|
||
<div class="wl-right">
|
||
<span class="meta" id="needHint">${canSubmit ? "" : "Need " + (250 - len) + " more characters"}</span>
|
||
<button class="kt-ai-btn" data-variant="primary" id="btnSubmit" ${canSubmit ? "" : "disabled"}>
|
||
<svg class="kt-icon"><use href="#send"></use></svg> Submit Essay
|
||
</button>
|
||
</div>
|
||
</div>` : ""}`;
|
||
}
|
||
|
||
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 = `<svg class="kt-icon"><use href="#sync"></use></svg> 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 = `<svg class="kt-icon"><use href="#send"></use></svg> 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 `<div class="vhead"><div class="vtitle">No result yet</div></div><div class="kt-ai-empty"><p>Pick an essay to see the evaluation.</p><button class="kt-ai-btn" id="btnEmptyR">Start Practice</button></div>`;
|
||
const ev = e.evaluation || {};
|
||
const lvl = levelFor(ev.overall || 0);
|
||
return `
|
||
<div class="vhead rhead">
|
||
<div class="vtitle">Your evaluation</div>
|
||
<div class="vsub">${esc(e.typeLabel)} · ${fmtDate(e.submittedAt)} · ${fmtClock(e.timeUsed)} · ${e.autoSubmitted ? "auto-submitted" : "submitted"}</div>
|
||
</div>
|
||
<div class="rgrid">
|
||
<div class="score-hero kt-ai-card">
|
||
<div class="score-big">${(ev.overall || 0).toFixed(1)}<span class="score-x">/10</span></div>
|
||
<div class="score-lvl" data-tone="${lvl.tone}">
|
||
<svg class="kt-icon"><use href="#trophy"></use></svg> ${lvl.name}
|
||
</div>
|
||
<div class="score-bar"><div class="score-bar-fill" data-tone="${lvl.tone}" style="width:${(ev.overall || 0) * 10}%"></div></div>
|
||
<div class="meta">Essay length: ${e.charCount.toLocaleString()} characters · Mode: ${ev.mode === "ai" ? "AI evaluation" : "Demo evaluation"}</div>
|
||
</div>
|
||
<div class="score-cards">
|
||
${CATS.map(([k, label]) => `
|
||
<div class="score-card">
|
||
<div class="sc-top"><span class="sc-label">${label}</span><span class="kt-ai-chip" data-tone="${toneForScore((ev.scores && ev.scores[k]) || 0)}">${((ev.scores && ev.scores[k]) || 0).toFixed(1)}</span></div>
|
||
<div class="sc-track"><div class="sc-fill" data-tone="${toneForScore((ev.scores && ev.scores[k]) || 0)}" style="width:${((ev.scores && ev.scores[k]) || 0) * 10}%"></div></div>
|
||
</div>`).join("")}
|
||
</div>
|
||
</div>
|
||
<div class="rgrid2">
|
||
<div class="kt-ai-card fb-block">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#check-circle"></use></svg> What's Strong</div>
|
||
<ul class="fb-list">${(ev.strengths || []).map(x => `<li>${esc(x)}</li>`).join("") || "<li>—</li>"}</ul>
|
||
</div>
|
||
<div class="kt-ai-card fb-block">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#lightbulb"></use></svg> What to Improve</div>
|
||
<ul class="fb-list">${(ev.improvements || []).map(x => `<li>${esc(x)}</li>`).join("") || "<li>—</li>"}</ul>
|
||
</div>
|
||
<div class="kt-ai-card fb-block">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#pencil"></use></svg> How to Improve</div>
|
||
<ul class="fb-list">${(ev.recommendations || []).map(x => `<li>${esc(x)}</li>`).join("") || "<li>—</li>"}</ul>
|
||
</div>
|
||
<div class="kt-ai-card fb-block strong-part">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#sparkles"></use></svg> Strongest Part</div>
|
||
<blockquote class="quote">“${esc(ev.strongestPart || "")}”</blockquote>
|
||
<p class="meta">A line that shows your personal voice or strong thinking.</p>
|
||
</div>
|
||
</div>
|
||
${ev.flexNotes && ev.flexNotes.length ? `
|
||
<div class="kt-ai-card flexnote">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#rocket"></use></svg> Qualities shown in this essay</div>
|
||
<div class="chips">${ev.flexNotes.map(f => `<span class="kt-ai-chip" data-tone="purple">${esc(f)}</span>`).join("")}</div>
|
||
</div>` : ""}
|
||
<div class="next-challenge">
|
||
<div class="kt-ai-card" style="flex:1">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#chevronRight"></use></svg> Next Challenge</div>
|
||
<p class="meta" style="margin-bottom:12px">Based on your weakest skill, try:</p>
|
||
<div class="next-label">${esc((ev.nextChallenge && ev.nextChallenge.label) || "")}</div>
|
||
<button class="kt-ai-btn" id="btnNext" style="margin-top:12px"><svg class="kt-icon"><use href="#play"></use></svg> Start next essay</button>
|
||
</div>
|
||
</div>
|
||
<div class="chall-card">
|
||
<div class="kt-ai-card">
|
||
<div class="fb-title"><svg class="kt-icon"><use href="#tool"></use></svg> Improvement challenge</div>
|
||
<p class="meta">Rewrite this sentence from your essay to make it clearer:</p>
|
||
<div class="chall-orig">${esc(ev.improvementSentence || "—")}</div>
|
||
<textarea id="challNew" class="kt-ai-textarea" placeholder="Your rewrite…"></textarea>
|
||
<div class="chall-actions">
|
||
<button class="kt-ai-btn" id="btnChallEval"><svg class="kt-icon"><use href="#sparkles"></use></svg> Evaluate rewrite</button>
|
||
<span id="challVerdict" class="meta"></span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="disclaimer" style="margin:var(--kt-ai-space-8) 0 var(--kt-ai-space-4)">
|
||
<svg class="kt-icon"><use href="#info"></use></svg>
|
||
<span>This AI score is for practice only. It is not an official FLEX evaluation and cannot predict your chances of selection.</span>
|
||
</div>
|
||
<div class="ractions">
|
||
<button class="kt-ai-btn" id="btnHomeR"><svg class="kt-icon"><use href="#home"></use></svg> Home</button>
|
||
<button class="kt-ai-btn" data-variant="primary" id="btnAgain"><svg class="kt-icon"><use href="#rocket"></use></svg> New essay</button>
|
||
</div>`;
|
||
}
|
||
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 = `<span class="kt-ai-chip" data-tone="${tone}">${r.verdict === "good" ? "Stronger" : "Getting there"}</span> ${esc(r.text)}`;
|
||
if (r.score) v.innerHTML += ` <strong>${r.score.toFixed(1)}</strong><span class="meta"> /10 clarity</span>`;
|
||
};
|
||
}
|
||
|
||
/* ================= 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 ? `
|
||
<div class="kt-ai-conclusion" style="margin-bottom:var(--kt-ai-space-5)">
|
||
<svg class="kt-icon"><use href="#sparkles"></use></svg>
|
||
<div class="text">You are a <strong>${lvl.name}</strong> writer${s.avgScore >= 8 ? " — excellent range" : ""}. Strongest: <strong>${strong[1]}</strong> (${(catAvg[strong[0]] || 0).toFixed(1)}). Focus area: <strong>${weak[1]}</strong> (${(catAvg[weak[0]] || 0).toFixed(1)}).</div>
|
||
</div>` : `
|
||
<div class="kt-ai-empty" style="margin:var(--kt-ai-space-8) var(--kt-ai-space-6)">
|
||
<svg class="kt-icon kt-icon-lg"><use href="#dashboard"></use></svg>
|
||
<div class="title">No progress data yet</div>
|
||
<p>Complete your first essay to see your statistics here.</p>
|
||
<button class="kt-ai-btn" id="pStart" data-size="sm">Start Practice</button>
|
||
</div>`}
|
||
<div class="kt-ai-kpi-strip" data-cards="true" style="margin-bottom:var(--kt-ai-space-6)">
|
||
${kpis.map((k) => `
|
||
<div class="kt-ai-kpi">
|
||
<svg class="kt-icon kpi-ic"><use href="#${k.i}"></use></svg>
|
||
<span class="value" ${String(k.v).length > 6 ? 'data-long="true"' : ""}>${k.v}</span>
|
||
<span class="label">${k.l}</span>
|
||
</div>`).join("")}
|
||
</div>
|
||
${series.length ? `
|
||
<div class="chart-card kt-ai-card" style="margin-bottom:var(--kt-ai-space-6)">
|
||
<div class="chart-head"><h3>Average score over time</h3><span class="meta">last ${series.length} essays</span></div>
|
||
${lineChart(series)}
|
||
</div>` : ""}
|
||
${s.count ? `
|
||
<div class="cat-card kt-ai-card" style="margin-bottom:var(--kt-ai-space-6)">
|
||
<div class="chart-head"><h3>Skill breakdown</h3><span class="meta">by category average</span></div>
|
||
<div class="catbars">
|
||
${sorted.map(([k, label]) => `
|
||
<div class="cat-row">
|
||
<span class="cat-label">${label}</span>
|
||
<div class="cat-track"><div class="cat-fill" data-tone="${toneForScore(catAvg[k] || 0)}" style="width:${(catAvg[k] || 0) * 10}%"></div></div>
|
||
<span class="cat-val">${(catAvg[k] || 0).toFixed(1)}</span>
|
||
</div>`).join("")}
|
||
</div>
|
||
<div class="cat-concl">
|
||
<span class="kt-ai-chip" data-tone="green">Strongest: ${strong[1]}</span>
|
||
<span class="kt-ai-chip" data-tone="orange">Focus: ${weak[1]}</span>
|
||
</div>
|
||
</div>` : ""}
|
||
<div class="ach-section">
|
||
<div class="chart-head"><h3>Achievements</h3><span class="meta">${ach.filter(a => a.got).length} / ${ach.length} unlocked</span></div>
|
||
<div class="ach-grid">
|
||
${ach.map((a) => `
|
||
<div class="ach-badge ${a.got ? "got" : ""}" data-title="${esc(a.desc)}">
|
||
<span class="ach-ic"><svg class="kt-icon kt-icon-lg"><use href="#${a.icon}"></use></svg></span>
|
||
<span class="ach-name">${a.name}</span>
|
||
${a.got ? "" : `<span class="lock"><svg class="kt-icon kt-icon-sm"><use href="#lock"></use></svg></span>`}
|
||
</div>`).join("")}
|
||
</div>
|
||
</div>`;
|
||
}
|
||
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 => `
|
||
<line x1="${pad.l}" y1="${y(g)}" x2="${W - pad.r}" y2="${y(g)}" class="gc"/>
|
||
<text x="${pad.l - 6}" y="${y(g) + 4}" class="gg" text-anchor="end">${g}</text>`).join("");
|
||
const dots = pts.map((p, i) => `<circle cx="${x(i)}" cy="${y(p.value)}" r="3" class="dot"><title>${p.label}: ${p.value.toFixed(1)}</title></circle>`).join("");
|
||
const labels = pts.map((p, i) => `<text x="${x(i)}" y="${H - 8}" class="gl" text-anchor="middle">${p.label}</text>`).join("");
|
||
return `<svg class="linechart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet">
|
||
${grid}<path class="area" d="${area}"/><path class="line" d="${path}"/>${dots}${labels}
|
||
</svg>`;
|
||
}
|
||
|
||
/* ================= 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 `
|
||
<div class="vhead"><div class="vtitle">Essay history</div>
|
||
<div class="vsub">${list.length} saved ${list.length === 1 ? "essay" : "essays"}</div></div>
|
||
<div class="kt-ai-toolbar" style="margin-bottom:var(--kt-ai-space-4)">
|
||
<input class="kt-ai-search" id="hSearch" placeholder="Search by type or prompt…" value="${esc(state.historyQuery || "")}"/>
|
||
</div>
|
||
${list.length ? `
|
||
<div class="kt-ai-table-wrap" data-framed="true">
|
||
<table class="kt-ai-table">
|
||
<thead><tr>
|
||
<th>Date</th><th>Type</th><th>Prompt</th><th>Score</th><th>Length</th><th>Time</th><th></th>
|
||
</tr></thead>
|
||
<tbody>
|
||
${list.map((e) => `
|
||
<tr class="hrow" data-id="${e.id}">
|
||
<td class="meta">${fmtDate(e.submittedAt)}</td>
|
||
<td><span class="kt-ai-chip" data-tone="gray">${esc(e.typeLabel)}</span></td>
|
||
<td class="prompt-cell">${esc(e.prompt || "")}</td>
|
||
<td><span class="kt-ai-chip" data-tone="${toneForScore((e.evaluation && e.evaluation.overall) || 0)}">${((e.evaluation && e.evaluation.overall) || 0).toFixed(1)}</span></td>
|
||
<td class="meta">${(e.charCount || 0).toLocaleString()}</td>
|
||
<td class="meta">${fmtClock(e.timeUsed || 0)}</td>
|
||
<td><svg class="kt-icon"><use href="#chevronRight"></use></svg></td>
|
||
</tr>`).join("")}
|
||
</tbody>
|
||
</table>
|
||
</div>` : `
|
||
<div class="kt-ai-empty" style="margin:var(--kt-ai-space-8)">
|
||
<svg class="kt-icon kt-icon-lg"><use href="#history"></use></svg>
|
||
<div class="title">No essays yet</div>
|
||
<p>Finished essays will appear here with full scores and feedback.</p>
|
||
<button class="kt-ai-btn" id="hStart" data-size="sm">Start your first one</button>
|
||
</div>`}`;
|
||
}
|
||
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 = `<svg class="kt-icon"><use href="#${state.theme === "dark" ? "sun" : "moon"}"></use></svg>`;
|
||
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 = `<svg class="kt-icon"><use href="#${state.theme === "dark" ? "sun" : "moon"}"></use></svg>`;
|
||
(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();
|
||
})();
|