File size: 29,174 Bytes
7d37d91
94df454
 
7d37d91
 
 
 
 
94df454
 
 
 
 
 
 
 
 
 
 
7d37d91
94df454
 
 
 
 
 
 
 
7d37d91
94df454
 
7d37d91
 
 
94df454
 
 
 
 
7d37d91
94df454
 
 
7d37d91
 
94df454
 
 
 
 
 
 
 
7d37d91
 
 
 
94df454
7d37d91
 
 
94df454
7d37d91
94df454
 
7d37d91
 
 
0aa7d82
94df454
7d37d91
94df454
 
 
0aa7d82
 
94df454
 
 
0aa7d82
 
7d37d91
94df454
7d37d91
94df454
 
 
0aa7d82
7d37d91
94df454
 
 
7d37d91
0aa7d82
7d37d91
94df454
 
 
0aa7d82
 
94df454
 
0aa7d82
 
94df454
 
7d37d91
94df454
7d37d91
0aa7d82
7d37d91
 
0aa7d82
7d37d91
 
0aa7d82
 
94df454
7d37d91
94df454
 
 
 
7d37d91
0aa7d82
7d37d91
0aa7d82
 
94df454
 
 
 
7d37d91
 
94df454
 
 
 
 
 
 
 
 
 
 
0aa7d82
 
7d37d91
94df454
7d37d91
94df454
 
7d37d91
0aa7d82
94df454
 
 
0aa7d82
 
 
94df454
 
 
 
 
 
0aa7d82
94df454
 
 
0aa7d82
 
7d37d91
94df454
7d37d91
 
 
 
0aa7d82
7d37d91
94df454
0aa7d82
7d37d91
0aa7d82
7d37d91
94df454
 
 
 
 
 
 
 
 
 
 
7d37d91
0aa7d82
7d37d91
 
94df454
7d37d91
 
0aa7d82
 
94df454
 
7d37d91
0aa7d82
 
7d37d91
94df454
7d37d91
 
0aa7d82
 
7d37d91
94df454
7d37d91
94df454
7d37d91
 
 
 
 
 
0aa7d82
94df454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa7d82
94df454
 
 
7d37d91
 
 
94df454
7d37d91
94df454
 
0aa7d82
94df454
7d37d91
 
0aa7d82
7d37d91
94df454
0aa7d82
7d37d91
 
 
 
 
 
 
 
 
94df454
 
 
7d37d91
 
0aa7d82
 
94df454
7d37d91
 
 
 
 
 
 
 
 
 
 
 
 
 
94df454
 
 
7d37d91
 
0aa7d82
 
94df454
7d37d91
 
94df454
7d37d91
94df454
7d37d91
 
 
 
94df454
7d37d91
94df454
 
 
 
7d37d91
 
0aa7d82
 
94df454
0aa7d82
 
7d37d91
94df454
7d37d91
94df454
0aa7d82
 
94df454
7d37d91
0aa7d82
94df454
7d37d91
94df454
 
7d37d91
0aa7d82
 
94df454
 
 
0aa7d82
 
94df454
0aa7d82
 
7d37d91
 
 
 
 
 
0aa7d82
7d37d91
94df454
0aa7d82
7d37d91
94df454
 
7d37d91
0aa7d82
94df454
7d37d91
94df454
 
 
0aa7d82
 
94df454
 
 
 
0aa7d82
7d37d91
 
 
0aa7d82
7d37d91
 
94df454
7d37d91
0aa7d82
7d37d91
94df454
 
 
 
 
 
 
7d37d91
 
 
 
 
94df454
7d37d91
 
94df454
 
7d37d91
 
 
 
 
94df454
 
7d37d91
 
 
94df454
 
7d37d91
 
 
94df454
7d37d91
94df454
7d37d91
 
 
 
94df454
 
 
7d37d91
 
 
 
94df454
 
 
 
 
 
 
 
 
 
 
 
 
7d37d91
94df454
7d37d91
 
0aa7d82
 
7d37d91
0aa7d82
 
94df454
7d37d91
94df454
7d37d91
94df454
7d37d91
94df454
0aa7d82
 
94df454
0aa7d82
 
7d37d91
0aa7d82
7d37d91
94df454
 
7d37d91
94df454
 
 
 
 
 
 
 
 
 
 
7d37d91
 
 
 
 
94df454
7d37d91
 
94df454
7d37d91
 
 
 
 
 
 
94df454
7d37d91
 
94df454
7d37d91
 
94df454
7d37d91
94df454
 
 
7d37d91
94df454
 
0aa7d82
94df454
 
0aa7d82
 
 
7d37d91
 
 
 
 
 
94df454
0aa7d82
 
7d37d91
 
 
0aa7d82
 
7d37d91
0aa7d82
7d37d91
 
94df454
 
 
 
0aa7d82
94df454
0aa7d82
 
7d37d91
 
 
 
 
 
94df454
 
 
 
 
 
 
 
 
7d37d91
94df454
7d37d91
 
 
 
94df454
7d37d91
 
94df454
7d37d91
 
 
0aa7d82
7d37d91
94df454
 
 
 
7d37d91
94df454
7d37d91
 
94df454
7d37d91
 
0aa7d82
 
7d37d91
 
 
94df454
7d37d91
 
94df454
 
 
 
 
 
 
 
 
 
 
 
7d37d91
0aa7d82
7d37d91
94df454
7d37d91
 
 
 
94df454
 
 
 
 
 
 
 
 
 
7d37d91
94df454
0aa7d82
7d37d91
 
 
94df454
7d37d91
94df454
 
 
 
7d37d91
94df454
7d37d91
0aa7d82
7d37d91
0aa7d82
7d37d91
 
 
 
94df454
7d37d91
 
94df454
7d37d91
0aa7d82
7d37d91
 
 
94df454
7d37d91
0aa7d82
94df454
7d37d91
 
 
 
 
 
 
94df454
7d37d91
 
 
 
 
94df454
7d37d91
 
 
 
94df454
 
7d37d91
94df454
 
7d37d91
0aa7d82
 
7d37d91
0aa7d82
7d37d91
 
0aa7d82
7d37d91
 
94df454
 
7d37d91
 
 
 
 
0aa7d82
7d37d91
94df454
0aa7d82
94df454
7d37d91
94df454
 
 
7d37d91
0aa7d82
7d37d91
 
94df454
 
 
 
 
 
0aa7d82
94df454
 
7d37d91
94df454
 
7d37d91
0aa7d82
94df454
7d37d91
 
94df454
 
 
0aa7d82
7d37d91
 
 
 
94df454
0aa7d82
 
7d37d91
0aa7d82
7d37d91
94df454
7d37d91
 
 
 
94df454
0aa7d82
94df454
 
0aa7d82
94df454
 
 
 
 
7d37d91
 
0aa7d82
 
7d37d91
94df454
 
 
 
 
0aa7d82
 
7d37d91
 
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
// ═══════════════════════════════════════════════
// PIXELAI CHAT v2.1 β€” script.js
// API-Ready Β· Chat History Β· Minimal Pixel Design
// ═══════════════════════════════════════════════

(function () {
    "use strict";

    // ── Quick DOM selector ──
    const $ = (s) => document.querySelector(s);
    const $$ = (s) => document.querySelectorAll(s);

    // ── DOM Elements ──
    const cursor        = $("#cursor");
    const sidebar       = $("#sidebar");
    const sidebarOverlay= $("#sidebarOverlay");
    const menuBtn       = $("#menuBtn");
    const sidebarClose  = $("#sidebarClose");
    const newChatBtn    = $("#newChatBtn");
    const chatHistoryList = $("#chatHistoryList");
    const chatArea      = $("#chatArea");
    const chatInput     = $("#chatInput");
    const sendBtn       = $("#sendBtn");
    const typingEl      = $("#typing");
    const typingAvatar  = $("#typingAvatar");
    const welcomeEl     = $("#welcome");
    const pixelArtEl    = $("#pixelArt");
    const quickActions  = $("#quickActions");
    const currentChatTitle = $("#currentChatTitle");
    const statusDot     = $("#statusDot");
    const statusText    = $("#statusText");
    const toastContainer = $("#toastContainer");
    const floatingContainer = $("#floatingPixels");

    // API settings
    const apiProviderEl  = $("#apiProvider");
    const apiKeyEl       = $("#apiKey");
    const apiModelEl     = $("#apiModel");
    const apiEndpointEl  = $("#apiEndpoint");
    const systemPromptEl = $("#systemPrompt");
    const saveApiBtn     = $("#saveApiBtn");
    const apiStatusEl    = $("#apiStatus");
    const toggleApiKeyBtn= $("#toggleApiKey");

    // Dialog
    const dialogOverlay  = $("#dialogOverlay");
    const dialogTitle    = $("#dialogTitle");
    const dialogMsg      = $("#dialogMsg");
    const dialogCancel   = $("#dialogCancel");
    const dialogConfirm  = $("#dialogConfirm");

    // Buttons
    const exportBtn  = $("#exportBtn");
    const clearAllBtn = $("#clearAllBtn");

    // ── State ──
    let currentChatId = null;
    let isProcessing  = false;
    let abortController = null;

    // ═══════════════════════════════
    // STORAGE
    // ═══════════════════════════════
    const KEYS = {
        CHATS:  "pixelai_chats",
        ACTIVE: "pixelai_active_chat",
        CONFIG: "pixelai_api_config",
    };

    function load(key, fallback) {
        try {
            const d = localStorage.getItem(key);
            return d ? JSON.parse(d) : fallback;
        } catch { return fallback; }
    }

    function save(key, data) {
        try { localStorage.setItem(key, JSON.stringify(data)); }
        catch (e) { console.error("Storage error:", e); }
    }

    // ═══════════════════════════════
    // CHAT DATA
    // ═══════════════════════════════
    function allChats()       { return load(KEYS.CHATS, {}); }
    function saveAllChats(c)  { save(KEYS.CHATS, c); }
    function getChat(id)      { return allChats()[id] || null; }

    function saveChat(id, chat) {
        const c = allChats();
        c[id] = chat;
        saveAllChats(c);
    }

    function deleteChat(id) {
        const c = allChats();
        delete c[id];
        saveAllChats(c);
    }

    function genId() {
        return "chat_" + Date.now() + "_" + Math.random().toString(36).substr(2, 6);
    }

    function createChat() {
        const id = genId();
        const chat = {
            id,
            title: "New Chat",
            messages: [],
            createdAt: Date.now(),
            updatedAt: Date.now(),
        };
        saveChat(id, chat);
        return chat;
    }

    function chatTitle(chat) {
        if (chat.messages.length > 0) {
            const first = chat.messages.find((m) => m.role === "user");
            if (first) {
                const t = first.content.substring(0, 45);
                return t + (first.content.length > 45 ? "..." : "");
            }
        }
        return "New Chat";
    }

    function fmtDate(ts) {
        const diff = Date.now() - ts;
        if (diff < 60000)    return "Just now";
        if (diff < 3600000)  return Math.floor(diff / 60000) + "m ago";
        if (diff < 86400000) return Math.floor(diff / 3600000) + "h ago";
        if (diff < 604800000) return Math.floor(diff / 86400000) + "d ago";
        return new Date(ts).toLocaleDateString();
    }

    function getTime() {
        return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
    }

    function escHtml(s) {
        const d = document.createElement("div");
        d.textContent = s;
        return d.innerHTML;
    }

    // ═══════════════════════════════
    // RENDER SIDEBAR HISTORY
    // ═══════════════════════════════
    function renderHistory() {
        const chats = allChats();
        const sorted = Object.values(chats).sort((a, b) => b.updatedAt - a.updatedAt);

        if (!sorted.length) {
            chatHistoryList.innerHTML =
                '<div class="history-empty">No chats yet.<br>Start a new conversation!</div>';
            return;
        }

        chatHistoryList.innerHTML = sorted.map((ch) => `
            <div class="history-item ${ch.id === currentChatId ? "active" : ""}" data-id="${ch.id}">
                <span class="history-item-icon">β—ˆ</span>
                <div class="history-item-content" data-action="load" data-id="${ch.id}">
                    <div class="history-item-title">${escHtml(chatTitle(ch))}</div>
                    <div class="history-item-date">${fmtDate(ch.updatedAt)} Β· ${ch.messages.length} msgs</div>
                </div>
                <button class="history-item-delete" data-action="delete" data-id="${ch.id}" title="Delete chat">βœ•</button>
            </div>
        `).join("");
    }

    // ═══════════════════════════════
    // LOAD / NEW CHAT
    // ═══════════════════════════════
    function loadChat(id) {
        const chat = getChat(id);
        if (!chat) return;

        currentChatId = id;
        save(KEYS.ACTIVE, id);

        chatArea.innerHTML = "";

        if (chat.messages.length === 0) {
            // Show welcome
            const w = document.createElement("div");
            w.className = "welcome";
            w.innerHTML = `
                <div class="pixel-art-display" id="pixelArtInner"></div>
                <h2>WELCOME TO<br>PIXELAI CHAT</h2>
                <p>Your retro-futuristic AI companion.<br>Open the <span class="highlight">☰ MENU</span> to configure your API key.</p>
                <div class="welcome-arrow">← Click the menu button</div>
            `;
            chatArea.appendChild(w);
            buildPixelArt(w.querySelector(".pixel-art-display"));
            quickActions.style.display = "flex";
        } else {
            quickActions.style.display = "none";
            chat.messages.forEach((msg) => {
                appendMsg(msg.content, msg.role === "user", msg.time, false, msg.role === "error");
            });
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        currentChatTitle.textContent = chatTitle(chat);
        renderHistory();
        closeSidebar();
    }

    function startNewChat() {
        const chat = createChat();
        loadChat(chat.id);
        toast("New chat created!", "success");
    }

    // ═══════════════════════════════
    // API CONFIG
    // ═══════════════════════════════
    const DEFAULT_CFG = {
        provider: "openai",
        apiKey: "",
        model: "gpt-4o-mini",
        endpoint: "",
        systemPrompt: "You are a helpful AI assistant. Keep responses concise and clear.",
    };

    function loadCfg()  { return load(KEYS.CONFIG, { ...DEFAULT_CFG }); }
    function saveCfg(c) { save(KEYS.CONFIG, c); }

    function populateSettings() {
        const c = loadCfg();
        apiProviderEl.value  = c.provider;
        apiKeyEl.value       = c.apiKey;
        apiModelEl.value     = c.model;
        apiEndpointEl.value  = c.endpoint;
        systemPromptEl.value = c.systemPrompt;
        updateDefaults(c.provider);
    }

    function updateDefaults(provider) {
        const map = {
            openai:    { model: "gpt-4o-mini",               ep: "https://api.openai.com/v1/chat/completions" },
            anthropic: { model: "claude-3-5-sonnet-20241022", ep: "https://api.anthropic.com/v1/messages" },
            google:    { model: "gemini-1.5-flash",           ep: "" },
            custom:    { model: "",                           ep: "" },
        };
        const d = map[provider] || map.openai;
        apiModelEl.placeholder    = d.model || "model name";
        apiEndpointEl.placeholder = d.ep || "https://your-api.com/v1/chat";
    }

    // ═══════════════════════════════
    // API CALL
    // ═══════════════════════════════
    function buildRequest(config, messages) {
        const p = config.provider;

        if (p === "openai" || p === "custom") {
            return {
                url: config.endpoint || "https://api.openai.com/v1/chat/completions",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": `Bearer ${config.apiKey}`,
                },
                body: {
                    model: config.model,
                    messages: [
                        { role: "system", content: config.systemPrompt },
                        ...messages.map((m) => ({ role: m.role, content: m.content })),
                    ],
                    max_tokens: 2048,
                    temperature: 0.7,
                },
                parse: (d) => {
                    if (d.choices?.[0]) return d.choices[0].message.content;
                    throw new Error(d.error?.message || "Invalid API response");
                },
            };
        }

        if (p === "anthropic") {
            return {
                url: config.endpoint || "https://api.anthropic.com/v1/messages",
                headers: {
                    "Content-Type": "application/json",
                    "x-api-key": config.apiKey,
                    "anthropic-version": "2023-06-01",
                    "anthropic-dangerous-direct-browser-access": "true",
                },
                body: {
                    model: config.model,
                    max_tokens: 2048,
                    system: config.systemPrompt,
                    messages: messages.map((m) => ({ role: m.role, content: m.content })),
                },
                parse: (d) => {
                    if (d.content?.[0]) return d.content[0].text;
                    throw new Error(d.error?.message || "Invalid API response");
                },
            };
        }

        if (p === "google") {
            return {
                url: `https://generativelanguage.googleapis.com/v1beta/models/${config.model}:generateContent?key=${config.apiKey}`,
                headers: { "Content-Type": "application/json" },
                body: {
                    system_instruction: { parts: [{ text: config.systemPrompt }] },
                    contents: messages.map((m) => ({
                        role: m.role === "assistant" ? "model" : "user",
                        parts: [{ text: m.content }],
                    })),
                    generationConfig: { maxOutputTokens: 2048, temperature: 0.7 },
                },
                parse: (d) => {
                    if (d.candidates?.[0]?.content?.parts?.[0])
                        return d.candidates[0].content.parts[0].text;
                    throw new Error(d.error?.message || "Invalid Gemini response");
                },
            };
        }

        throw new Error("Unknown provider: " + p);
    }

    async function callAPI(messages) {
        const config = loadCfg();
        if (!config.apiKey) {
            throw new Error("No API key! Open ☰ MENU β†’ API Settings to configure.");
        }

        const req = buildRequest(config, messages);
        abortController = new AbortController();

        const res = await fetch(req.url, {
            method: "POST",
            headers: req.headers,
            body: JSON.stringify(req.body),
            signal: abortController.signal,
        });

        if (!res.ok) {
            const err = await res.json().catch(() => ({}));
            throw new Error(err.error?.message || `API Error ${res.status}: ${res.statusText}`);
        }

        return req.parse(await res.json());
    }

    // ═══════════════════════════════
    // SEND MESSAGE
    // ═══════════════════════════════
    async function sendMessage() {
        const text = chatInput.value.trim();
        if (!text || isProcessing) return;

        isProcessing = true;
        setUI("loading");

        // Hide welcome
        const w = chatArea.querySelector(".welcome");
        if (w) w.remove();
        quickActions.style.display = "none";

        // Ensure active chat
        if (!currentChatId) {
            const ch = createChat();
            currentChatId = ch.id;
            save(KEYS.ACTIVE, currentChatId);
        }

        const time = getTime();
        const userMsg = { role: "user", content: text, time };
        appendMsg(text, true, time, true);
        addMsgToChat(currentChatId, userMsg);

        chatInput.value = "";
        chatInput.focus();
        showTyping();

        try {
            const chat = getChat(currentChatId);
            const reply = await callAPI(chat.messages);
            hideTyping();

            const aiTime = getTime();
            const aiMsg = { role: "assistant", content: reply, time: aiTime };
            appendMsg(reply, false, aiTime, true);
            addMsgToChat(currentChatId, aiMsg);

            currentChatTitle.textContent = chatTitle(getChat(currentChatId));
            renderHistory();
            setUI("ready");
        } catch (err) {
            hideTyping();
            if (err.name === "AbortError") {
                toast("Request cancelled.", "info");
            } else {
                appendMsg("⚠ " + err.message, false, getTime(), true, true);
                toast(err.message, "error");
            }
            setUI("error");
            setTimeout(() => setUI("ready"), 3000);
        }

        isProcessing = false;
    }

    function addMsgToChat(id, msg) {
        const chat = getChat(id);
        if (!chat) return;
        chat.messages.push(msg);
        chat.updatedAt = Date.now();
        chat.title = chatTitle(chat);
        saveChat(id, chat);
    }

    // ═══════════════════════════════
    // DOM: APPEND MESSAGE
    // ═══════════════════════════════
    function appendMsg(text, isUser, time, animate = true, isError = false) {
        const msg = document.createElement("div");
        msg.className = `message ${isUser ? "user" : "ai"} ${isError ? "error" : ""}`;
        if (!animate) msg.style.animation = "none";

        const av = document.createElement("div");
        av.className = "avatar";
        createAvatar(av, !isUser);

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

        const msgSpan = document.createElement("span");
        msgSpan.className = "msg-text";

        const timeSpan = document.createElement("span");
        timeSpan.className = "time";
        timeSpan.textContent = time;

        bubble.appendChild(msgSpan);
        bubble.appendChild(timeSpan);
        msg.appendChild(av);
        msg.appendChild(bubble);
        chatArea.appendChild(msg);

        if (!isUser && animate && !isError) {
            typewriter(msgSpan, text);
        } else {
            msgSpan.textContent = text;
        }

        chatArea.scrollTop = chatArea.scrollHeight;
    }

    function typewriter(el, text) {
        let i = 0;
        function tick() {
            if (i < text.length) {
                el.textContent += text[i++];
                chatArea.scrollTop = chatArea.scrollHeight;
                setTimeout(tick, 14);
            }
        }
        tick();
    }

    // ═══════════════════════════════
    // UI HELPERS
    // ═══════════════════════════════
    function showTyping() { typingEl.classList.add("active"); chatArea.scrollTop = chatArea.scrollHeight; }
    function hideTyping() { typingEl.classList.remove("active"); }

    function setUI(state) {
        const map = {
            ready:   { cls: "status-dot", label: "READY",    dis: false },
            loading: { cls: "status-dot loading", label: "THINKING", dis: true },
            error:   { cls: "status-dot error", label: "ERROR",    dis: false },
        };
        const s = map[state] || map.ready;
        statusDot.className  = s.cls;
        statusText.textContent = s.label;
        chatInput.disabled   = s.dis;
        sendBtn.disabled     = s.dis;
    }

    // ═══════════════════════════════
    // TOAST
    // ═══════════════════════════════
    function toast(msg, type = "info") {
        const t = document.createElement("div");
        t.className = `toast ${type}`;
        t.textContent = msg;
        toastContainer.appendChild(t);
        setTimeout(() => t.remove(), 3200);
    }

    // ═══════════════════════════════
    // CONFIRM DIALOG
    // ═══════════════════════════════
    function confirm(title, message) {
        return new Promise((resolve) => {
            dialogTitle.textContent = title;
            dialogMsg.textContent   = message;
            dialogOverlay.classList.add("active");

            function done(val) {
                dialogOverlay.classList.remove("active");
                dialogCancel.removeEventListener("click", onNo);
                dialogConfirm.removeEventListener("click", onYes);
                resolve(val);
            }
            function onNo()  { done(false); }
            function onYes() { done(true); }

            dialogCancel.addEventListener("click", onNo);
            dialogConfirm.addEventListener("click", onYes);
        });
    }

    // ═══════════════════════════════
    // SIDEBAR
    // ═══════════════════════════════
    function openSidebar() {
        sidebar.classList.add("open");
        sidebarOverlay.classList.add("active");
        renderHistory();
    }

    function closeSidebar() {
        sidebar.classList.remove("open");
        sidebarOverlay.classList.remove("active");
    }

    // ═══════════════════════════════
    // EXPORT
    // ═══════════════════════════════
    function exportChats() {
        const data = JSON.stringify(allChats(), null, 2);
        const blob = new Blob([data], { type: "application/json" });
        const url  = URL.createObjectURL(blob);
        const a    = document.createElement("a");
        a.href = url;
        a.download = `pixelai_export_${Date.now()}.json`;
        a.click();
        URL.revokeObjectURL(url);
        toast("Chats exported!", "success");
    }

    // ═══════════════════════════════
    // PIXEL ART & AVATARS
    // ═══════════════════════════════
    const ROBOT = [
        0,0,1,1,1,1,0,0,
        0,1,0,1,1,0,1,0,
        0,1,1,1,1,1,1,0,
        0,1,2,1,1,2,1,0,
        0,1,1,1,1,1,1,0,
        0,0,1,0,0,1,0,0,
        0,1,1,1,1,1,1,0,
        0,1,0,0,0,0,1,0,
    ];
    const ART_C = ["transparent", "#00ff88", "#ff00aa"];

    function buildPixelArt(container) {
        if (!container) return;
        container.innerHTML = "";
        ROBOT.forEach((v) => {
            const p = document.createElement("div");
            p.className = "p";
            p.style.background = ART_C[v];
            container.appendChild(p);
        });
    }

    function createAvatar(container, isAI) {
        const ai   = [0,1,1,1,1,0, 1,0,1,1,0,1, 1,1,1,1,1,1, 1,2,1,1,2,1, 1,1,1,1,1,1, 0,1,0,0,1,0];
        const user = [0,0,1,1,0,0, 0,1,1,1,1,0, 1,2,1,1,2,1, 1,1,1,1,1,1, 0,1,2,2,1,0, 0,0,1,1,0,0];
        const pat  = isAI ? ai : user;
        const cols = isAI ? ["transparent","#00ff88","#ff00aa"] : ["transparent","#ff00aa","#00ff88"];
        container.innerHTML = "";
        pat.forEach((v) => {
            const p = document.createElement("div");
            p.className = "avatar-pixel";
            p.style.background = cols[v];
            container.appendChild(p);
        });
    }

    // ═══════════════════════════════
    // CUSTOM CURSOR
    // ═══════════════════════════════
    let trailN = 0;

    document.addEventListener("mousemove", (e) => {
        cursor.style.left = (e.clientX - 2) + "px";
        cursor.style.top  = (e.clientY - 2) + "px";

        if (++trailN % 3 === 0) {
            const t = document.createElement("div");
            t.className = "cursor-trail";
            t.style.left = (e.clientX - 2) + "px";
            t.style.top  = (e.clientY - 2) + "px";
            document.body.appendChild(t);
            setTimeout(() => { t.style.opacity = "0"; }, 80);
            setTimeout(() => t.remove(), 500);
        }
    });

    document.addEventListener("mousedown", () => cursor.classList.add("click"));
    document.addEventListener("mouseup",   () => cursor.classList.remove("click"));

    // ═══════════════════════════════
    // FLOATING PIXELS
    // ═══════════════════════════════
    function spawnPixel() {
        const p = document.createElement("div");
        p.className = "floating-pixel";
        p.style.left = Math.random() * 100 + "%";
        p.style.animationDuration = (8 + Math.random() * 15) + "s";
        const size = (2 + Math.random() * 4) + "px";
        p.style.width = p.style.height = size;
        p.style.background = Math.random() > 0.5 ? "#00ff88" : "#ff00aa";
        floatingContainer.appendChild(p);
        p.addEventListener("animationend", () => { p.remove(); spawnPixel(); });
    }
    for (let i = 0; i < 18; i++) setTimeout(spawnPixel, Math.random() * 5000);

    // ═══════════════════════════════
    // LOGO GLITCH
    // ═══════════════════════════════
    const logoText = $(".logo-text");
    setInterval(() => {
        if (Math.random() > 0.95 && logoText) {
            logoText.style.textShadow = `
                ${(Math.random()*4-2).toFixed(1)}px 0 rgba(255,0,170,0.7),
                ${(Math.random()*4-2).toFixed(1)}px 0 rgba(0,255,136,0.7)`;
            setTimeout(() => {
                logoText.style.textShadow = "2px 2px 0 rgba(0,255,136,0.15)";
            }, 100);
        }
    }, 200);

    // ═══════════════════════════════
    // EVENT LISTENERS
    // ═══════════════════════════════

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

    // Quick actions
    quickActions.addEventListener("click", (e) => {
        const btn = e.target.closest(".quick-btn");
        if (btn) { chatInput.value = btn.dataset.prompt; sendMessage(); }
    });

    // Sidebar open/close
    menuBtn.addEventListener("click", openSidebar);
    sidebarClose.addEventListener("click", closeSidebar);
    sidebarOverlay.addEventListener("click", closeSidebar);

    // New chat
    newChatBtn.addEventListener("click", startNewChat);

    // History list clicks
    chatHistoryList.addEventListener("click", async (e) => {
        const target = e.target.closest("[data-action]");
        if (!target) return;

        const action = target.dataset.action;
        const id     = target.dataset.id;

        if (action === "load") {
            loadChat(id);
        } else if (action === "delete") {
            const ok = await confirm("Delete Chat", "Permanently delete this chat?");
            if (ok) {
                deleteChat(id);
                if (id === currentChatId) startNewChat();
                else renderHistory();
                toast("Chat deleted.", "info");
            }
        }
    });

    // Export
    exportBtn.addEventListener("click", exportChats);

    // Clear all
    clearAllBtn.addEventListener("click", async () => {
        const ok = await confirm("Clear All", "Delete ALL chat history? This cannot be undone.");
        if (ok) {
            saveAllChats({});
            startNewChat();
            toast("All chats cleared.", "info");
        }
    });

    // API provider change
    apiProviderEl.addEventListener("change", () => updateDefaults(apiProviderEl.value));

    // Toggle API key
    toggleApiKeyBtn.addEventListener("click", () => {
        const show = apiKeyEl.type === "password";
        apiKeyEl.type = show ? "text" : "password";
        toggleApiKeyBtn.textContent = show ? "β—Ž" : "β—‰";
    });

    // Save API config
    saveApiBtn.addEventListener("click", () => {
        const cfg = {
            provider:     apiProviderEl.value,
            apiKey:       apiKeyEl.value.trim(),
            model:        apiModelEl.value.trim() || DEFAULT_CFG.model,
            endpoint:     apiEndpointEl.value.trim(),
            systemPrompt: systemPromptEl.value.trim() || DEFAULT_CFG.systemPrompt,
        };
        saveCfg(cfg);
        apiStatusEl.textContent = "βœ“ Saved!";
        apiStatusEl.style.color = "var(--accent)";
        setTimeout(() => { apiStatusEl.textContent = ""; }, 2500);
        toast("API config saved!", "success");
    });

    // Keyboard: Escape
    document.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            if (sidebar.classList.contains("open")) closeSidebar();
            if (dialogOverlay.classList.contains("active")) {
                dialogOverlay.classList.remove("active");
            }
            if (isProcessing && abortController) {
                abortController.abort();
                isProcessing = false;
                hideTyping();
                setUI("ready");
            }
        }
    });

    // ═══════════════════════════════
    // INIT
    // ═══════════════════════════════
    function init() {
        buildPixelArt(pixelArtEl);
        createAvatar(typingAvatar, true);
        populateSettings();

        const lastId = load(KEYS.ACTIVE, null);
        const chats  = allChats();

        if (lastId && chats[lastId]) {
            loadChat(lastId);
        } else if (Object.keys(chats).length) {
            const latest = Object.values(chats).sort((a, b) => b.updatedAt - a.updatedAt);
            loadChat(latest[0].id);
        } else {
            startNewChat();
        }

        chatInput.focus();

        console.log(
            "%cβ—ˆ PixelAI v2.1 Ready β—ˆ",
            "color:#00ff88; font-size:14px; font-family:monospace; background:#0a0a0a; padding:8px 16px;"
        );
    }

    init();
})();