Spaces:
Running

File size: 27,047 Bytes
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30247fe
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30247fe
 
 
64378fa
 
30247fe
64378fa
30247fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import { React, html, useEffect, useMemo, useState } from "./runtime.js";
import { useApp } from "./store.js";
import { useEngine } from "./engine.js";
import { useCloud, money } from "./cloud.js";
import { Notice, Pill, FeedbackPanel, Icon, Mark, usePersistent, download, SECTIONS } from "./components.js";
import {
  CREDIT_COSTS,
  PARAGRAPH_RUBRIC,
  SUGGESTED_QUESTIONS,
  TEXTS,
  reviewText,
  wordCount
} from "./marking.js";

function PageHead({ kicker, title, subtitle, right }) {
  return html`<div class="row between" style=${{ alignItems: "flex-start", gap: "16px" }}>
    <div>
      <div class="eyebrow">${kicker}</div>
      <h1 class="page-title">${title}</h1>
      ${subtitle && html`<p class="subtitle">${subtitle}</p>`}
    </div>
    ${right}
  </div>`;
}

// ---------------------------------------------------------------------------
// Model answers
// ---------------------------------------------------------------------------

export function ModelAnswers() {
  const app = useApp();
  const engine = useEngine();
  const [textId, setTextId] = usePersistent("explication.modelAnswer.textId", "macbeth");
  const [question, setQuestion] = usePersistent("explication.modelAnswer.question", "How does Shakespeare present ambition in Macbeth?");
  const [answer, setAnswer] = usePersistent("explication.modelAnswer.answer", "");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const text = TEXTS.find((t) => t.id === textId) || TEXTS[0];

  const generate = async () => {
    setError("");
    if (!engine.canGenerate) {
      setError("A model answer needs a model. Open Settings to load one or connect an endpoint.");
      return;
    }
    if (app.credits < CREDIT_COSTS.modelAnswer) {
      setError("This costs " + CREDIT_COSTS.modelAnswer + " credits. Mark a paragraph to earn more.");
      return;
    }
    app.spend(CREDIT_COSTS.modelAnswer);
    setBusy(true);
    setAnswer("");
    try {
      const result = await engine.chat(
        [
          {
            role: "system",
            content: [
              "You are an experienced GCSE English Literature examiner writing a model answer for study.",
              "Write one developed paragraph, 150-220 words, in British English, at grade 8-9 standard.",
              "Use one short embedded quotation from the named text; never invent a quotation.",
              "Name the method, explain the effect, and finish by returning to the question.",
              "Return only the paragraph."
            ].join(" ")
          },
          { role: "user", content: `Text: ${text.title}\nQuestion: ${question}` }
        ],
        setAnswer
      );
      if (result && result.trim()) setAnswer(result.trim());
    } catch (err) {
      setError(err && err.message ? err.message : "The model answer could not be written.");
      app.addCredits(CREDIT_COSTS.modelAnswer);
    }
    setBusy(false);
  };

  return html`<main class="page narrow">
    <${PageHead} kicker="Model answers" title="See what a strong answer looks like."
      subtitle="A model answer is a worked example, not your work. It is always labelled, and it costs credits because a model writes it."
      right=${html`<${Pill} tone="warn">${CREDIT_COSTS.modelAnswer} credits<//>`} />

    <div class="card" style=${{ marginTop: "18px" }}>
      <div class="grid two">
        <div class="field">
          <label>Text</label>
          <select class="select" value=${textId} onChange=${(e) => setTextId(e.target.value)}>
            ${TEXTS.map((t) => html`<option key=${t.id} value=${t.id}>${t.title}</option>`)}
          </select>
        </div>
        <div class="field">
          <label>Question</label>
          <input class="input" list="answer-questions" value=${question} onInput=${(e) => setQuestion(e.target.value)} />
          <datalist id="answer-questions">${SUGGESTED_QUESTIONS.map((q) => html`<option key=${q} value=${q}></option>`)}</datalist>
        </div>
      </div>
      ${!engine.canGenerate && html`<div style=${{ marginTop: "10px" }}><${Notice} kind="warn">No model is connected. <a href="#/settings">Open Settings</a> to download a Paragraph model or add an endpoint.<//></div>`}
      ${error && html`<div style=${{ marginTop: "10px" }}><${Notice} kind="error">${error}<//></div>`}
      <div class="row between" style=${{ marginTop: "12px" }}>
        <span class="tiny faint">${app.credits} credits available</span>
        <button class="btn primary" onClick=${generate} disabled=${busy || !engine.canGenerate}>
          ${busy ? html`<span class="spin"></span> Writing…` : html`<${Icon} name="sparkle" size=${13} /> Generate model answer`}
        </button>
      </div>
    </div>

    ${answer &&
    html`<div class="card" style=${{ marginTop: "12px", background: "var(--warning-soft)", borderColor: "#f0dcc5" }}>
      <div class="row between">
        <span class="eyebrow" style=${{ color: "var(--warning)" }}>AI-written model answer</span>
        <span class="tiny" style=${{ color: "var(--warning)" }}>${wordCount(answer)} words</span>
      </div>
      <p style=${{ fontFamily: "var(--serif)", fontSize: "16px", lineHeight: 1.7, margin: "10px 0 0", whiteSpace: "pre-wrap" }}>${answer}</p>
      <div class="divider" style=${{ background: "#eedcc8" }}></div>
      <div class="tiny" style=${{ color: "var(--warning)" }}>Study material only — do not submit this as your own work.</div>
    </div>`}
  </main>`;
}

// ---------------------------------------------------------------------------
// Mock exam
// ---------------------------------------------------------------------------

const EXAM_SECONDS = 25 * 60;

export function MockExam() {
  const app = useApp();
  const [textId, setTextId] = usePersistent("explication.mock.textId", "macbeth");
  const [question, setQuestion] = usePersistent("explication.mock.question", "How does Shakespeare present ambition in Macbeth?");
  const [extract, setExtract] = usePersistent("explication.mock.extract", "");
  const [answer, setAnswer] = usePersistent("explication.mock.answer", "");
  const [remaining, setRemaining] = useState(EXAM_SECONDS);
  const [running, setRunning] = useState(false);
  const [feedback, setFeedback] = useState(null);
  const [error, setError] = useState("");
  const text = TEXTS.find((t) => t.id === textId) || TEXTS[0];

  useEffect(() => {
    if (!running) return;
    const timer = setInterval(() => {
      setRemaining((r) => {
        if (r <= 1) {
          setRunning(false);
          return 0;
        }
        return r - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [running]);

  const time = `${String(Math.floor(remaining / 60)).padStart(2, "0")}:${String(remaining % 60).padStart(2, "0")}`;

  const mark = () => {
    setError("");
    if (wordCount(answer) < 20) {
      setError("Write at least a couple of sentences before marking.");
      return;
    }
    if (app.credits < CREDIT_COSTS.mockExam) {
      setError("A marked mock exam costs " + CREDIT_COSTS.mockExam + " credits. Mark a paragraph to earn more.");
      return;
    }
    app.spend(CREDIT_COSTS.mockExam);
    setRunning(false);
    const result = reviewText({ text: answer, question, extract, rubric: PARAGRAPH_RUBRIC, title: text.title });
    setFeedback(result);
    app.recordDraft({
      mode: "Mock exam",
      title: text.title,
      question,
      extract,
      text: answer,
      score: result.total,
      max: result.max,
      feedback: result,
      summary: "Timed mock exam"
    });
  };

  return html`<main class="page narrow">
    <${PageHead} kicker="Mock exam" title="Sit the paper, then mark it."
      subtitle="Twenty-five minutes, one question, one paragraph. Marking costs credits, exactly as it does in the app."
      right=${html`<span class="pill ${remaining === 0 ? "danger" : running ? "warn" : "neutral"}" style=${{ fontFamily: "var(--mono)", fontSize: "13px" }}>${time}</span>`} />

    <div class="card" style=${{ marginTop: "18px" }}>
      <div class="grid two">
        <div class="field"><label>Text</label>
          <select class="select" value=${textId} onChange=${(e) => setTextId(e.target.value)}>
            ${TEXTS.map((t) => html`<option key=${t.id} value=${t.id}>${t.title}</option>`)}
          </select>
        </div>
        <div class="field"><label>Question</label>
          <input class="input" list="mock-questions" value=${question} onInput=${(e) => setQuestion(e.target.value)} />
          <datalist id="mock-questions">${SUGGESTED_QUESTIONS.map((q) => html`<option key=${q} value=${q}></option>`)}</datalist>
        </div>
      </div>
      <div class="field" style=${{ marginTop: "10px" }}>
        <label>Extract <span class="hint">optional</span></label>
        <textarea class="textarea" style=${{ minHeight: "70px" }} value=${extract} onInput=${(e) => setExtract(e.target.value)} placeholder="Paste the passage the question refers to."></textarea>
      </div>
      <div class="row between wrap" style=${{ marginTop: "10px" }}>
        <div class="row">
          <button class="btn small" onClick=${() => setRunning((v) => !v)} disabled=${remaining === 0}>
            <${Icon} name=${running ? "clock" : "clock"} size=${12} /> ${running ? "Pause" : "Start timer"}
          </button>
          <button class="btn small ghost" onClick=${() => { setRunning(false); setRemaining(EXAM_SECONDS); }}>Reset</button>
          <span class="tiny faint">25 minutes</span>
        </div>
        <span class="tiny faint">${wordCount(answer)} words</span>
      </div>
    </div>

    <div class="card" style=${{ marginTop: "12px" }}>
      <textarea class="textarea" style=${{ minHeight: "280px", border: 0, padding: 0, boxShadow: "none" }} value=${answer} onInput=${(e) => setAnswer(e.target.value)} placeholder="Write your answer here. No notes, no interruptions."></textarea>
    </div>

    ${error && html`<div style=${{ marginTop: "10px" }}><${Notice} kind="error">${error}<//></div>`}
    <div class="row between" style=${{ marginTop: "10px" }}>
      <span class="tiny faint">${app.credits} credits · marking costs ${CREDIT_COSTS.mockExam}</span>
      <button class="btn primary" onClick=${mark}><${Icon} name="check" size=${13} /> Finish and mark</button>
    </div>

    ${feedback && html`<div style=${{ marginTop: "12px" }}><${FeedbackPanel} feedback=${feedback} /><//>`}
  </main>`;
}

// ---------------------------------------------------------------------------
// Process log
// ---------------------------------------------------------------------------

export function ProcessLog() {
  const app = useApp();
  const [open, setOpen] = useState(null);
  const [confirmClear, setConfirmClear] = useState(false);
  const drafts = app.drafts;

  const exportMarkdown = () => {
    const lines = ["# My writing process — Explication", "", `Exported ${new Date().toLocaleString("en-GB")}`, ""];
    for (const d of [...drafts].reverse()) {
      lines.push(`## ${d.title || "Untitled"} — ${d.score}/${d.max}`);
      lines.push(`_${new Date(d.at).toLocaleDateString("en-GB")} · ${d.mode}${d.question ? " · " + d.question : ""}_`);
      lines.push("");
      lines.push(d.text);
      if (d.feedback && d.feedback.nextStep) {
        lines.push("");
        lines.push(`**Next step:** ${d.feedback.nextStep}`);
      }
      lines.push("");
    }
    lines.push("Exported from Explication. Nothing left this browser.");
    download("explication-writing-process.md", lines.join("\n"));
  };

  const exportJson = () => {
    download("explication-data.json", JSON.stringify({ settings: app.settings, drafts, credits: app.credits, totalEarned: app.totalEarned, days: app.days }, null, 2), "application/json");
  };

  return html`<main class="page narrow">
    <${PageHead} kicker="Process log" title="How the writing has changed."
      subtitle="Every marked piece, kept privately in this browser. Read the next steps again before your next attempt."
      right=${html`<button class="btn small" onClick=${exportMarkdown} disabled=${drafts.length === 0}><${Icon} name="download" size=${12} /> Export</button>`} />

    <div class="grid three" style=${{ marginTop: "18px" }}>
      <div class="stat"><div class="head">Marked</div><div class="value">${drafts.length}</div><div class="note">Pieces</div></div>
      <div class="stat"><div class="head">Average</div><div class="value">${app.average}%</div><div class="note">Across recent work</div></div>
      <div class="stat"><div class="head">Earned</div><div class="value">${app.totalEarned}</div><div class="note">Credits in total</div></div>
    </div>

    <div class="section-head"><h2 class="section-title">History</h2>
      ${drafts.length > 0 && html`<button class="btn link small" onClick=${() => setConfirmClear(true)}>Clear</button>`}
    </div>

    ${confirmClear &&
    html`<div class="callout red" style=${{ marginBottom: "10px", display: "flex", justifyContent: "space-between", gap: "10px", alignItems: "center" }}>
      <span>Delete all ${drafts.length} marked pieces? This cannot be undone.</span>
      <span class="row">
        <button class="btn small" onClick=${() => setConfirmClear(false)}>Keep</button>
        <button class="btn small danger" onClick=${() => { app.resetProgress(); setConfirmClear(false); }}>Delete</button>
      </span>
    </div>`}

    <div class="card">
      ${drafts.length === 0
        ? html`<div class="empty"><${Mark} size=${34} /><div style=${{ fontSize: "12px" }}>Mark your first paragraph and it will appear here.</div></div>`
        : html`<div class="list">
            ${drafts.map(
              (d) => html`<div key=${d.id}>
                <button class="list-row" style=${{ width: "100%", background: "transparent", border: 0, textAlign: "left", borderTop: "1px solid var(--hairline)" }}
                  onClick=${() => setOpen(open === d.id ? null : d.id)}>
                  <div class="main">
                    <div class="t">${d.title || "Untitled"}${d.question ? " · " + d.question : ""}</div>
                    <div class="s">${new Date(d.at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })} · ${d.mode} · ${wordCount(d.text)} words · +${d.earned || 0} cr</div>
                  </div>
                  <span class=${"pill " + (d.score / d.max >= 0.7 ? "green" : "neutral")}>${d.score}/${d.max}</span>
                  <${Icon} name="chevron" size=${13} />
                </button>
                ${open === d.id &&
                html`<div style=${{ padding: "0 0 14px" }}>
                  <div class="callout" style=${{ background: "var(--deep)", borderColor: "var(--hairline)", fontFamily: "var(--serif)", fontSize: "14px", whiteSpace: "pre-wrap", lineHeight: 1.65 }}>${d.text}</div>
                  ${d.feedback && d.feedback.nextStep && html`<div class="callout blue" style=${{ marginTop: "8px" }}><strong>Next step. </strong>${d.feedback.nextStep}</div>`}
                  <div class="row" style=${{ marginTop: "8px" }}>
                    <button class="btn small ghost danger" onClick=${() => app.deleteDraft(d.id)}><${Icon} name="trash" size=${11} /> Delete this entry</button>
                  </div>
                </div>`}
              </div>`
            )}
          </div>`}
    </div>

    <div class="row" style=${{ marginTop: "12px" }}>
      <button class="btn small" onClick=${exportJson}><${Icon} name="download" size=${12} /> Export data</button>
      <span class="tiny faint">Your writing never leaves this browser.</span>
    </div>
  </main>`;
}

// ---------------------------------------------------------------------------
// Settings
// ---------------------------------------------------------------------------

export function Settings() {
  const app = useApp();
  const engine = useEngine();
  const cloud = useCloud();
  const [baseUrl, setBaseUrl] = useState(engine.endpoint.baseUrl);
  const [endpointModel, setEndpointModel] = useState(engine.endpoint.model);
  const [key, setKey] = useState(engine.endpoint.key);
  const [saved, setSaved] = useState(false);
  const [confirmReset, setConfirmReset] = useState(false);

  const saveEndpoint = () => {
    engine.setEndpoint({ baseUrl, model: endpointModel, key });
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  return html`<main class="page narrow">
    <${PageHead} kicker="Settings" title="How Explication works here."
      subtitle="Your name, your exam board and the model behind the feedback. Everything is stored locally in this browser." />

    <div class="section-head"><h2 class="section-title">You</h2></div>
    <div class="card">
      <div class="grid two">
        <div class="field"><label>Name <span class="hint">optional</span></label>
          <input class="input" value=${app.settings.name} onInput=${(e) => app.setSettings({ name: e.target.value })} placeholder="What should the coach call you?" />
        </div>
        <div class="field"><label>Year group</label>
          <select class="select" value=${app.settings.yearGroup} onChange=${(e) => app.setSettings({ yearGroup: e.target.value })}>
            ${["Year 9", "Year 10", "Year 11", "Year 12", "Year 13"].map((y) => html`<option key=${y} value=${y}>${y}</option>`)}
          </select>
        </div>
        <div class="field"><label>Exam board</label>
          <select class="select" value=${app.settings.board} onChange=${(e) => app.setSettings({ board: e.target.value })}>
            ${["AQA", "Edexcel", "OCR", "WJEC", "CCEA"].map((b) => html`<option key=${b} value=${b}>${b}</option>`)}
          </select>
        </div>
        <div class="field"><label>Credits</label><input class="input" value=${`${app.credits} available · ${app.totalEarned} earned`} disabled /></div>
      </div>
    </div>

    <div class="section-head"><h2 class="section-title">Marking</h2></div>
    <div class="card">
      <div class="row between">
        <div>
          <div style=${{ fontWeight: 600 }}>Rule-based review</div>
          <div class="tiny faint" style=${{ maxWidth: "520px", marginTop: "3px", lineHeight: 1.55 }}>
            Paragraph, essay, poetry, improve and mock-exam marking all run here: the rubric, quotation checking and the next-step guidance work with no model and no network.
          </div>
        </div>
        <${Pill} tone="green">Always on</${Pill}>
      </div>
      <div class="divider"></div>
      <div class="row between">
        <div>
          <div style=${{ fontWeight: 600 }}>Paragraph models <span class="tiny faint">offline</span></div>
          <div class="tiny faint" style=${{ maxWidth: "560px", marginTop: "3px", lineHeight: 1.55 }}>
            The real Paragraph family, published by quantilimited. Download a model once and run it in the Mac or iOS app, or any GGUF runner. The weights are not loaded in this browser tab.
          </div>
        </div>
        <${Pill} tone="green">${cloud.models.filter((m) => m.enabled !== false).length} models</${Pill}>
      </div>
      <div class="grid two" style=${{ marginTop: "12px" }}>
        ${cloud.models
          .filter((m) => m.enabled !== false)
          .map((m) => {
            const allowed = cloud.canDownload(m.min_tier);
            return html`<div class="card" style=${{ padding: "12px" }}>
              <div class="row between">
                <div style=${{ fontWeight: 600 }}>${m.name}</div>
                <span class="pill neutral">Tier ${m.min_tier}</span>
              </div>
              <div class="tiny faint" style=${{ marginTop: "2px" }}>${m.base_model || m.model_name}${m.params ? " · " + m.params : ""}</div>
              <div class="tiny faint" style=${{ marginTop: "2px" }}>
                ${m.download_size}${m.format ? " · " + m.format : ""}${m.essays ? " · " + m.essays + " essays" : ""}
              </div>
              <p class="tiny faint" style=${{ marginTop: "6px", lineHeight: 1.5 }}>${m.note}</p>
              <div class="row wrap" style=${{ gap: "8px", marginTop: "8px" }}>
                ${m.card_url && html`<a class="btn small" href=${m.card_url} target="_blank" rel="noopener">Model card</a>`}
                ${m.download_url
                  ? allowed
                    ? html`<a class="btn small primary" href=${m.download_url} target="_blank" rel="noopener"><${Icon} name="download" size=${12} /> Download</a>`
                    : html`<span class="tiny faint"><${Icon} name="lock" size=${12} /> Included in a plan · <a href="#/pricing">See plans</a></span>`
                  : html`<span class="tiny faint">Safetensors only — no GGUF build yet</span>`}
              </div>
            </div>`;
          })}
      </div>

      <div class="divider"></div>
      <div style=${{ fontWeight: 600 }}>Your OpenAI-compatible endpoint</div>
      <div class="tiny faint" style=${{ marginTop: "3px" }}>
        Optional. Bring any endpoint that speaks <span class="mono">POST /chat/completions</span>. The key is kept in this browser only and sent only to that URL.
      </div>
      <div class="grid two" style=${{ marginTop: "10px" }}>
        <div class="field"><label>Base URL</label><input class="input" value=${baseUrl} onInput=${(e) => setBaseUrl(e.target.value)} placeholder="http://127.0.0.1:11434/v1" /></div>
        <div class="field"><label>Model</label><input class="input" value=${endpointModel} onInput=${(e) => setEndpointModel(e.target.value)} placeholder="qwen2.5:7b" /></div>
      </div>
      <div class="field" style=${{ marginTop: "10px" }}><label>API key <span class="hint">optional</span></label>
        <input class="input" type="password" value=${key} onInput=${(e) => setKey(e.target.value)} placeholder="sk-…" autocomplete="off" />
      </div>
      <div class="row between" style=${{ marginTop: "10px" }}>
        <span class="tiny faint">${engine.hasEndpoint ? "Connected: " + engine.endpoint.model : "No endpoint connected yet."}</span>
        <button class="btn primary small" onClick=${saveEndpoint}>${saved ? "Saved" : "Save endpoint"}</button>
      </div>
    </div>

    <div class="section-head"><h2 class="section-title">Hosted models</h2>
      <a class="btn link small" href="#/pricing">See plans</a>
    </div>
    <div class="card">
      ${!cloud.configured
        ? html`<div class="row between wrap">
            <div style=${{ maxWidth: "520px" }}>
              <div style=${{ fontWeight: 600 }}>Not connected</div>
              <div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>
                Hosted models run on the site owner's API keys and are metered against a plan's budget. Connect Supabase and choose a plan to use them.
              </div>
            </div>
            <a class="btn small" href="#/connect">Connect Supabase</a>
          </div>`
        : !cloud.user
        ? html`<div class="row between wrap">
            <div style=${{ maxWidth: "520px" }}>
              <div style=${{ fontWeight: 600 }}>Sign in to use hosted models</div>
              <div class="tiny faint" style=${{ marginTop: "3px" }}>Your plan's included budget is attached to your account.</div>
            </div>
            <a class="btn small" href="#/account">Sign in</a>
          </div>`
        : !cloud.plan
        ? html`<div class="row between wrap">
            <div style=${{ maxWidth: "520px" }}>
              <div style=${{ fontWeight: 600 }}>No plan on this account</div>
              <div class="tiny faint" style=${{ marginTop: "3px" }}>A subscription includes hosted model usage. You can keep using your own key or the free offline model.</div>
            </div>
            <a class="btn small primary" href="#/pricing">Choose a plan</a>
          </div>`
        : html`<div>
            <div class="row between wrap">
              <div>
                <div style=${{ fontWeight: 600 }}>${cloud.plan.name}</div>
                <div class="tiny faint" style=${{ marginTop: "2px" }}>
                  ${cloud.budget.limit ? Math.max(0, Math.round((cloud.budget.remaining / cloud.budget.limit) * 100)) + "% of your included AI left this period" : "No hosted AI included"}
                </div>
              </div>
              <a class="btn small" href="#/account">Manage</a>
            </div>
            ${cloud.budget.limit > 0 &&
            html`<div class="row wrap" style=${{ marginTop: "10px" }}>
              <select class="select" style=${{ maxWidth: "320px" }} value=${engine.hostedId} onChange=${(e) => engine.setHostedModel(e.target.value)}>
                <option value="">Use the offline model instead</option>
                ${cloud.models
                  .filter((m) => m.enabled !== false && m.endpoint_url)
                  .map((m) => html`<option key=${m.id} value=${m.id}>${m.name} · ${m.host || "hosted"}</option>`)}
              </select>
              <span class="tiny faint">${engine.hostedReady ? "In use when no personal endpoint is set." : ""}</span>
            </div>`}
          </div>`}
    </div>

    <div class="section-head"><h2 class="section-title">Data</h2></div>
    <div class="card">
      <div class="row between wrap">
        <div>
          <div style=${{ fontWeight: 600 }}>Export</div>
          <div class="tiny faint">Download your drafts, settings and credits as JSON.</div>
        </div>
        <button class="btn small" onClick=${() => download("explication-data.json", JSON.stringify({ settings: app.settings, drafts: app.drafts, credits: app.credits, totalEarned: app.totalEarned, days: app.days }, null, 2), "application/json")}>Export data</button>
      </div>
      <div class="divider"></div>
      <div class="row between wrap">
        <div>
          <div style=${{ fontWeight: 600 }}>Reset progress</div>
          <div class="tiny faint">Clears drafts, credits and streaks. Settings are kept.</div>
        </div>
        ${confirmReset
          ? html`<span class="row"><button class="btn small" onClick=${() => setConfirmReset(false)}>Cancel</button><button class="btn small danger" onClick=${() => { app.resetProgress(); setConfirmReset(false); }}>Reset</button></span>`
          : html`<button class="btn small danger" onClick=${() => setConfirmReset(true)}>Reset</button>`}
      </div>
    </div>

    <div class="section-head"><h2 class="section-title">About</h2></div>
    <div class="card">
      <div class="row" style=${{ gap: "12px" }}>
        <${Mark} size=${40} />
        <div>
          <div style=${{ fontWeight: 600 }}>Explication for the web</div>
          <div class="tiny faint">Version 1.0 · GCSE English Literature · British English</div>
        </div>
      </div>
      <p class="tiny faint" style=${{ marginTop: "10px", lineHeight: 1.6 }}>
        The same rubric, credit economy, quotation checking and process log as the Mac and iOS app. On the web the marking runs as a deterministic review; connect a model for chat, model answers and rewritten suggestions. No account, no analytics, no uploads.
      </p>
    </div>
  </main>`;
}