File size: 14,469 Bytes
4e3ac7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* ── Irish Maths AI — Mathaí Frontend ──────────────────────────────── */

let state = {
    role: "",          // "student" | "teacher"
    level: "",         // "primary" | "junior_cycle" | "senior_cycle"
    classGroup: "",    // "5th Class", "Higher Level" etc.
    history: [],       // [{role, content}]
    sending: false,
};

// Elements
const welcomeScreen = document.getElementById("welcomeScreen");
const chatScreen = document.getElementById("chatScreen");
const levelPicker = document.getElementById("levelPicker");
const classPicker = document.getElementById("classPicker");
const classGrid = document.getElementById("classGrid");
const chatMain = document.getElementById("chatMain");
const messages = document.getElementById("messages");
const quickTopics = document.getElementById("quickTopics");
const chatInput = document.getElementById("chatInput");
const sendBtn = document.getElementById("sendBtn");
const headerLevel = document.getElementById("headerLevel");
const topicsSidebar = document.getElementById("topicsSidebar");
const sidebarContent = document.getElementById("sidebarContent");

// ── Welcome Flow ─────────────────────────────────────────────────────

document.getElementById("pickStudent").addEventListener("click", () => {
    state.role = "student";
    document.querySelectorAll(".role-card").forEach(c => c.classList.remove("selected"));
    document.getElementById("pickStudent").classList.add("selected");
    levelPicker.style.display = "block";
    classPicker.style.display = "none";
    levelPicker.scrollIntoView({ behavior: "smooth" });
});

document.getElementById("pickTeacher").addEventListener("click", () => {
    state.role = "teacher";
    state.level = "";
    state.classGroup = "Teacher";
    startChat();
});

document.querySelectorAll(".level-card").forEach(card => {
    card.addEventListener("click", () => {
        state.level = card.dataset.level;

        if (state.level === "primary") {
            showClassPicker([
                "Junior Infants", "Senior Infants",
                "1st Class", "2nd Class",
                "3rd Class", "4th Class",
                "5th Class", "6th Class"
            ]);
        } else if (state.level === "junior_cycle") {
            showClassPicker(["1st Year", "2nd Year", "3rd Year", "Ordinary Level", "Higher Level"]);
        } else if (state.level === "senior_cycle") {
            showClassPicker(["5th Year", "6th Year", "Foundation Level", "Ordinary Level", "Higher Level"]);
        }
    });
});

function showClassPicker(classes) {
    classPicker.style.display = "block";
    classGrid.innerHTML = "";
    classes.forEach(c => {
        const btn = document.createElement("button");
        btn.className = "class-btn";
        btn.textContent = c;
        btn.addEventListener("click", () => {
            state.classGroup = c;
            startChat();
        });
        classGrid.appendChild(btn);
    });
    classPicker.scrollIntoView({ behavior: "smooth" });
}

// ── Start Chat ───────────────────────────────────────────────────────

function startChat() {
    welcomeScreen.style.display = "none";
    chatScreen.style.display = "flex";

    // Set header level text
    if (state.role === "teacher") {
        headerLevel.textContent = "Teacher Mode";
    } else {
        const levelLabels = {
            primary: "Primary",
            junior_cycle: "Junior Cycle",
            senior_cycle: "Senior Cycle"
        };
        headerLevel.textContent = `${levelLabels[state.level] || ""} · ${state.classGroup}`;
    }

    state.history = [];
    messages.innerHTML = "";

    // Show welcome message from Mathaí
    const greeting = state.role === "teacher"
        ? "Hello! 👋 I'm **Mathaí**, your Irish maths teaching assistant. I can help with lesson plans, worksheet ideas, curriculum references and more. What can I help with?"
        : `Hello! 👋 I'm **Mathaí**, your maths buddy! I'm here to help you with any maths questions. Just ask me anything — no question is too simple. What would you like to learn today?`;

    addMessage("ai", greeting);
    loadQuickTopics();
    loadTopicsSidebar();
    chatInput.focus();
}

// ── Quick Topics ─────────────────────────────────────────────────────

async function loadQuickTopics() {
    try {
        const resp = await fetch("/api/quick-topics");
        const data = await resp.json();
        let topics;

        if (state.role === "teacher") {
            topics = data.teacher || [];
        } else {
            topics = (data.student && data.student[state.level]) || [];
        }

        quickTopics.innerHTML = "";
        topics.forEach(t => {
            const btn = document.createElement("button");
            btn.className = "quick-topic-btn";
            btn.innerHTML = `<span class="qt-icon">${t.icon || "📌"}</span> ${escapeHtml(t.label)}`;
            btn.addEventListener("click", () => {
                chatInput.value = t.query;
                sendMessage();
                quickTopics.style.display = "none";
            });
            quickTopics.appendChild(btn);
        });
    } catch (e) {
        quickTopics.innerHTML = "";
    }
}

// ── Topics Sidebar ───────────────────────────────────────────────────

document.getElementById("topicsBtn").addEventListener("click", () => {
    topicsSidebar.classList.toggle("open");
});
document.getElementById("sidebarClose").addEventListener("click", () => {
    topicsSidebar.classList.remove("open");
});

async function loadTopicsSidebar() {
    const level = state.level || "primary";
    try {
        const resp = await fetch(`/api/curriculum/${level}`);
        const data = await resp.json();
        const strands = data.strands || {};

        sidebarContent.innerHTML = "";
        for (const [key, strand] of Object.entries(strands)) {
            const div = document.createElement("div");
            div.className = "sidebar-strand";

            const header = document.createElement("div");
            header.className = "strand-header";
            header.textContent = strand.label || key;
            div.appendChild(header);

            const topics = strand.topics || {};
            for (const [tKey, topic] of Object.entries(topics)) {
                const btn = document.createElement("button");
                btn.className = "topic-btn";
                btn.textContent = topic.label || tKey;
                btn.addEventListener("click", () => {
                    chatInput.value = `Explain ${topic.label} for ${state.classGroup || "me"}`;
                    topicsSidebar.classList.remove("open");
                    sendMessage();
                });
                div.appendChild(btn);
            }
            sidebarContent.appendChild(div);
        }
    } catch (e) {
        sidebarContent.innerHTML = `<p style="padding:1rem;color:var(--text-muted)">Could not load topics.</p>`;
    }
}

// ── Chat ─────────────────────────────────────────────────────────────

chatInput.addEventListener("keydown", (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

chatInput.addEventListener("input", () => {
    chatInput.style.height = "auto";
    chatInput.style.height = Math.min(chatInput.scrollHeight, 120) + "px";
});

sendBtn.addEventListener("click", sendMessage);

async function sendMessage() {
    const text = chatInput.value.trim();
    if (!text || state.sending) return;

    state.sending = true;
    sendBtn.disabled = true;
    chatInput.value = "";
    chatInput.style.height = "auto";

    // Hide quick topics after first message
    quickTopics.style.display = "none";

    // Add user message
    addMessage("user", text);
    state.history.push({ role: "user", content: text });

    // Show typing indicator
    const typingEl = addTyping();

    try {
        const resp = await fetch("/api/chat", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                message: text,
                level: state.level,
                class_group: state.classGroup,
                role: state.role,
                history: state.history.slice(-10),
            }),
        });
        const data = await resp.json();

        typingEl.remove();

        addMessage("ai", data.reply, data.sources || []);
        state.history.push({ role: "assistant", content: data.reply });
    } catch (e) {
        typingEl.remove();
        addMessage("ai", "Sorry, I couldn't connect. Please check your internet and try again.");
    }

    state.sending = false;
    sendBtn.disabled = false;
    chatInput.focus();
}

// ── Message Rendering ────────────────────────────────────────────────

function addMessage(type, content, sources = []) {
    const div = document.createElement("div");
    div.className = `msg msg-${type}`;

    const avatar = document.createElement("div");
    avatar.className = "msg-avatar";
    avatar.textContent = type === "user" ? "🙋" : "🧮";

    const bubble = document.createElement("div");
    bubble.className = "msg-bubble";

    if (type === "ai") {
        bubble.innerHTML = renderMarkdown(content);
        // Render KaTeX
        if (window.renderMathInElement) {
            renderMathInElement(bubble, {
                delimiters: [
                    { left: "$$", right: "$$", display: true },
                    { left: "$", right: "$", display: false },
                    { left: "\\(", right: "\\)", display: false },
                    { left: "\\[", right: "\\]", display: true },
                ],
                throwOnError: false,
            });
        }

        // Add source tags
        if (sources.length > 0) {
            const sourcesDiv = document.createElement("div");
            sourcesDiv.className = "msg-sources";
            const seen = new Set();
            sources.forEach(s => {
                const key = `${s.strand} · ${s.topic}`;
                if (seen.has(key)) return;
                seen.add(key);
                const tag = document.createElement("span");
                tag.className = "source-tag";
                tag.textContent = key;
                sourcesDiv.appendChild(tag);
            });
            bubble.appendChild(sourcesDiv);
        }
    } else {
        bubble.textContent = content;
    }

    div.appendChild(avatar);
    div.appendChild(bubble);
    messages.appendChild(div);
    scrollToBottom();
}

function addTyping() {
    const div = document.createElement("div");
    div.className = "msg msg-ai";
    div.id = "typing-indicator";

    const avatar = document.createElement("div");
    avatar.className = "msg-avatar";
    avatar.textContent = "🧮";

    const bubble = document.createElement("div");
    bubble.className = "msg-bubble";
    bubble.innerHTML = `<div class="typing-dots"><span></span><span></span><span></span></div>`;

    div.appendChild(avatar);
    div.appendChild(bubble);
    messages.appendChild(div);
    scrollToBottom();
    return div;
}

function scrollToBottom() {
    chatMain.scrollTop = chatMain.scrollHeight;
}

// ── Simple Markdown → HTML ───────────────────────────────────────────

function renderMarkdown(text) {
    if (!text) return "";
    let html = escapeHtml(text);

    // Bold: **text**
    html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
    // Italic: *text*
    html = html.replace(/\*(.+?)\*/g, "<em>$1</em>");
    // Inline code: `text`
    html = html.replace(/`(.+?)`/g, "<code>$1</code>");
    // Unordered list items: - text or • text
    html = html.replace(/^[\-•]\s+(.+)$/gm, "<li>$1</li>");
    // Ordered list items: 1. text
    html = html.replace(/^\d+\.\s+(.+)$/gm, "<li>$1</li>");
    // Wrap consecutive <li> in <ul>
    html = html.replace(/((?:<li>.*<\/li>\n?)+)/g, "<ul>$1</ul>");
    // Headings: ### text
    html = html.replace(/^###\s+(.+)$/gm, "<strong>$1</strong>");
    // Paragraphs (double newline)
    html = html.replace(/\n\n/g, "</p><p>");
    // Single newlines
    html = html.replace(/\n/g, "<br>");

    return `<p>${html}</p>`;
}

function escapeHtml(str) {
    const div = document.createElement("div");
    div.textContent = str;
    return div.innerHTML;
}

// ── Header Buttons ───────────────────────────────────────────────────

document.getElementById("backBtn").addEventListener("click", () => {
    chatScreen.style.display = "none";
    welcomeScreen.style.display = "flex";
    state.history = [];
    // Reset selections
    document.querySelectorAll(".role-card").forEach(c => c.classList.remove("selected"));
    levelPicker.style.display = "none";
    classPicker.style.display = "none";
});

document.getElementById("newChatBtn").addEventListener("click", () => {
    state.history = [];
    messages.innerHTML = "";
    quickTopics.style.display = "flex";
    loadQuickTopics();

    const greeting = state.role === "teacher"
        ? "Fresh start! What would you like help with?"
        : "Let's start fresh! 🎯 What maths topic can I help you with?";
    addMessage("ai", greeting);
    chatInput.focus();
});