File size: 29,632 Bytes
46eb045
f69b06b
46eb045
 
ae2cef0
861f9af
7bc0028
861f9af
46eb045
181d8a1
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28b1994
 
 
 
46eb045
 
 
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f69b06b
6d49e80
861f9af
ae2cef0
 
 
 
 
 
 
861f9af
 
 
 
 
 
 
ae2cef0
 
861f9af
ae2cef0
 
 
 
 
 
 
 
861f9af
 
 
 
 
 
 
 
 
 
ae2cef0
 
 
 
 
 
 
 
861f9af
 
ae2cef0
861f9af
 
 
 
 
 
 
 
 
 
 
ae2cef0
 
 
861f9af
 
 
 
 
 
ae2cef0
861f9af
 
 
ae2cef0
 
 
861f9af
 
 
 
 
 
 
0507f71
181d8a1
28b1994
181d8a1
861f9af
 
28b1994
 
861f9af
181d8a1
ec9b88c
 
32a5464
28b1994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32a5464
 
 
28b1994
 
 
 
 
 
 
 
 
 
 
 
861f9af
28b1994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20f15aa
28b1994
 
20f15aa
28b1994
20f15aa
 
28b1994
 
 
ae2cef0
861f9af
181d8a1
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181d8a1
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181d8a1
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20f15aa
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d49e80
32a5464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d49e80
46eb045
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Elite Visuals AI – Smart Invoice & Final Report</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* (Keep your existing CSS exactly as before – unchanged) */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: linear-gradient(135deg, #f5f7fa 0%, #e9eef5 100%); font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
        .chat-icon { position: fixed; bottom: 28px; right: 28px; width: 64px; height: 64px; background: linear-gradient(145deg, #25D366, #128C7E); border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 10px 25px rgba(0,0,0,0.2); animation: pulse 1.8s infinite; z-index: 1000; }
        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(37,211,102,0.5); } 70% { box-shadow: 0 0 0 15px rgba(37,211,102,0); } 100% { box-shadow: 0 0 0 0 rgba(37,211,102,0); } }
        .chat-icon:hover { transform: scale(1.08); background: #20b859; }
        .chat-icon i { font-size: 32px; color: white; }
        .chat-modal { position: fixed; bottom: 100px; right: 28px; width: 580px; height: 680px; background: rgba(255,255,255,0.98); border-radius: 28px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.35); display: none; flex-direction: column; overflow: hidden; z-index: 1001; animation: slideUpFade 0.3s ease-out; }
        @keyframes slideUpFade { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
        .chat-header { background: linear-gradient(135deg, #075E54, #0b3b32); color: white; padding: 12px 18px; display: flex; justify-content: space-between; align-items: center; }
        .header-buttons { display: flex; gap: 10px; align-items: center; }
        .header-btn { background: rgba(255,255,255,0.2); border: none; width: 32px; height: 32px; border-radius: 50%; cursor: pointer; color: white; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; }
        .header-btn:hover { transform: scale(1.05); background: rgba(255,255,255,0.4); }
        .chat-invoice-container { display: flex; flex: 1; overflow: hidden; transition: all 0.3s ease; }
        .chat-column { flex: 1.5; display: flex; flex-direction: column; background: #f0f2f5; transition: all 0.3s ease; }
        .invoice-column { width: 40%; background: #fff8f0; border-left: 1px solid #ddd; display: flex; flex-direction: column; overflow-y: auto; padding: 12px; gap: 12px; transition: all 0.3s ease; }
        .invoice-column.hidden { display: none; width: 0; padding: 0; }
        .chat-column.expanded { flex: 1; }
        .invoice-title { font-weight: 700; font-size: 1rem; color: #075E54; border-bottom: 2px solid #25D366; padding-bottom: 6px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; }
        .invoice-items { flex: 1; overflow-y: auto; max-height: 280px; }
        .invoice-item { background: white; border-radius: 12px; padding: 8px 12px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .invoice-item-name { font-weight: 500; font-size: 0.8rem; }
        .invoice-item-price { font-size: 0.8rem; color: #2d6a4f; font-weight: 600; }
        .remove-item { color: #e63946; cursor: pointer; font-size: 14px; transition: 0.2s; }
        .remove-item:hover { transform: scale(1.1); }
        .invoice-total { border-top: 2px dashed #ccc; padding-top: 10px; margin-top: 8px; font-weight: 700; font-size: 0.9rem; display: flex; justify-content: space-between; }
        .empty-invoice { color: #888; font-size: 0.75rem; text-align: center; padding: 20px; }
        .final-report-btn, .download-report-btn { background: #25D366; color: white; border: none; border-radius: 25px; padding: 8px 12px; font-size: 0.75rem; font-weight: 600; cursor: pointer; transition: 0.2s; width: 100%; margin-top: 8px; }
        .download-report-btn { background: #2a6d4c; margin-top: 4px; }
        .final-report-btn:hover { background: #128C7E; transform: scale(1.02); }
        .download-report-btn:hover { background: #1e5a3e; transform: scale(1.02); }
        .chat-messages { flex: 1; padding: 12px; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; }
        .message { max-width: 85%; padding: 8px 12px; border-radius: 18px; font-size: 0.8rem; line-height: 1.4; white-space: pre-line; animation: fadeIn 0.2s; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
        .user-msg { background: #DCF8C6; margin-left: auto; border-bottom-right-radius: 4px; }
        .bot-msg { background: white; margin-right: auto; border-bottom-left-radius: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
        .bot-message-wrapper { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; max-width: 85%; margin-right: auto; }
        .bot-message-wrapper .message { margin: 0; max-width: 100%; }
        .confirm-btn { background: #25D366; color: white; border: none; border-radius: 20px; padding: 4px 12px; font-size: 0.7rem; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 4px; }
        .confirm-btn:hover { background: #128C7E; transform: scale(1.02); }
        .live-widget { background: white; border-radius: 16px; margin: 8px 8px 0 8px; overflow: hidden; box-shadow: 0 2px 6px rgba(0,0,0,0.05); }
        .widget-header { background: linear-gradient(135deg, #1e2a3a, #0f172a); color: white; padding: 8px 12px; display: flex; justify-content: space-between; align-items: center; font-size: 0.75rem; font-weight: 600; }
        .widget-controls { display: flex; gap: 10px; }
        .widget-controls button { background: rgba(255,255,255,0.2); border: none; color: white; border-radius: 20px; padding: 2px 8px; font-size: 0.7rem; cursor: pointer; transition: 0.2s; }
        .widget-controls button:hover { background: rgba(255,255,255,0.4); }
        .toggle-widget { cursor: pointer; margin-left: 8px; }
        .widget-content { padding: 10px; display: none; background: #fef9e6; font-size: 0.7rem; }
        .widget-content.show { display: block; }
        .info-row { margin: 4px 0; }
        .info-label { font-weight: 700; color: #075E54; }
        .questions-container { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px; }
        .question-bubble { background: #e4e6eb; padding: 4px 10px; border-radius: 16px; font-size: 0.7rem; cursor: pointer; transition: 0.2s; }
        .question-bubble:hover { background: #d1d4db; transform: translateY(-1px); }
        .typing-indicator { background: white; padding: 6px 12px; border-radius: 20px; display: inline-flex; gap: 4px; width: fit-content; }
        .typing-indicator span { width: 6px; height: 6px; background: #888; border-radius: 50%; animation: wave 1.2s infinite; }
        @keyframes wave { 0%,60%,100% { transform: translateY(0); } 30% { transform: translateY(-4px); } }
        .chat-input-area { display: flex; padding: 10px; background: white; border-top: 1px solid #ddd; gap: 8px; }
        .chat-input-area input { flex: 1; padding: 8px 12px; border: 1px solid #ccc; border-radius: 30px; outline: none; font-size: 0.8rem; }
        .chat-input-area button { background: #25D366; border: none; width: 36px; height: 36px; border-radius: 50%; color: white; cursor: pointer; }
        .media-panel { background: #f0f2f5; border-radius: 16px; padding: 12px; margin: 10px 0; display: none; }
        .media-panel textarea { width: 100%; padding: 8px; border-radius: 12px; border: 1px solid #ccc; }
        .media-panel input[type="file"] { margin: 8px 0; }
        .image-preview { max-width: 100%; max-height: 150px; margin-top: 8px; }
    </style>
</head>
<body>
<div class="chat-icon" id="chatIcon"><i class="fas fa-comment-dots"></i></div>
<div class="chat-modal" id="chatModal">
    <div class="chat-header">
        <h3><i class="fas fa-robot"></i> Elite Visuals AI</h3>
        <div class="header-buttons">
            <button class="header-btn" id="toggleInvoiceBtn" title="Toggle Invoice Panel"><i class="fas fa-eye-slash"></i></button>
            <button class="header-btn" id="closeChat"><i class="fas fa-times"></i></button>
        </div>
    </div>
    <div class="chat-invoice-container" id="chatInvoiceContainer">
        <div class="chat-column" id="chatColumn">
            <div class="chat-messages" id="chatMessages">
                <div class="message bot-msg">✨ Assalam-o-Alaikum! I can help you with website packages, extra features, and **step-by-step project building**. To start a new project, simply say: **"I want to build a website"** – I'll ask you all the requirements and then generate a proposal, project ID, and total invoice. You can also ask about packages or use the confirm buttons below.</div>
                <div class="live-widget" id="liveWidget">
                    <div class="widget-header">
                        <span><i class="fas fa-chart-line"></i> 📊 Live Quote</span>
                        <div class="widget-controls">
                            <button id="hideWidgetBtn"><i class="fas fa-eye-slash"></i> Hide</button>
                            <button id="unhideWidgetBtn" style="display: none;"><i class="fas fa-eye"></i> Show</button>
                            <i class="fas fa-chevron-down toggle-widget" id="toggleIcon"></i>
                        </div>
                    </div>
                    <div class="widget-content" id="widgetContent">
                        <p id="widgetEmptyMsg">💡 Ask about a package/feature to see details.</p>
                        <div id="widgetDetails" style="display: none;"></div>
                    </div>
                </div>
                <div id="defaultQuestionsContainer" class="questions-container"></div>
            </div>
            <div class="chat-input-area">
                <input type="text" id="userInput" placeholder="Ask about price, timeline, confirm Basic, add SEO, or say 'I want to build a website'...">
                <button id="sendBtn"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>
        <div class="invoice-column" id="invoiceColumn">
            <div class="invoice-title">
                <span>🧾 Your Quote</span>
            </div>
            <div class="invoice-items" id="invoiceItems">
                <div class="empty-invoice">✨ No services selected yet.<br>Ask or confirm a package to add.</div>
            </div>
            <div class="invoice-total" id="invoiceTotal">
                <span>Subtotal:</span>
                <span id="totalAmount">PKR 0</span>
            </div>
            <button class="final-report-btn" id="finalReportBtn"><i class="fas fa-file-alt"></i> Generate Final Report</button>
            <button class="download-report-btn" id="downloadReportBtn"><i class="fas fa-download"></i> Download Report</button>
        </div>
    </div>
</div>

<script>
    // ---------- Session ----------
    let sessionId = localStorage.getItem('chat_session_id');
    if (!sessionId) {
        sessionId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 8);
        localStorage.setItem('chat_session_id', sessionId);
    }
    const API_URL = "/api/chat";
    const DEFAULT_QUESTIONS = [
        "Basic website price and timeline?",
        "Standard package details",
        "Premium package details",
        "Extra: live chat cost increase?",
        "Add e-commerce to my quote",
        "I want to build a website",
        "Contact number"
    ];
    
    let storedProjectId = localStorage.getItem(`project_id_${sessionId}`) || null;
    let invoiceItems = [];
    let nextId = 1;
    
    function parsePrice(priceStr) {
        let match = priceStr.match(/(\d[\d,]+)/);
        if (match) return parseInt(match[0].replace(/,/g, ''));
        return 0;
    }
    
    function parseTimelineDays(timelineStr) {
        if (!timelineStr) return 0;
        let match = timelineStr.match(/(\d+)\s*-\s*(\d+)\s*days?/);
        if (match) return parseInt(match[2]);
        match = timelineStr.match(/(\d+)\s*days?/);
        if (match) return parseInt(match[1]);
        return 0;
    }
    
    function updateInvoiceDisplay() {
        const container = document.getElementById('invoiceItems');
        const totalSpan = document.getElementById('totalAmount');
        if (invoiceItems.length === 0) {
            container.innerHTML = '<div class="empty-invoice">✨ No services selected yet.<br>Ask or confirm a package to add.</div>';
            totalSpan.innerText = 'PKR 0';
            return;
        }
        let html = '';
        let total = 0;
        invoiceItems.forEach(item => {
            const priceNum = parsePrice(item.price);
            total += priceNum;
            html += `
                <div class="invoice-item" data-id="${item.id}">
                    <div class="invoice-item-name">${item.name}</div>
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <span class="invoice-item-price">${item.price}</span>
                        <span class="remove-item" data-id="${item.id}"><i class="fas fa-times-circle"></i></span>
                    </div>
                </div>
            `;
        });
        container.innerHTML = html;
        totalSpan.innerText = `PKR ${total.toLocaleString()}`;
        document.querySelectorAll('.remove-item').forEach(el => {
            el.addEventListener('click', (e) => {
                const id = parseInt(el.dataset.id);
                removeInvoiceItem(id);
            });
        });
    }
    
    function removeInvoiceItem(id) {
        invoiceItems = invoiceItems.filter(item => item.id !== id);
        updateInvoiceDisplay();
    }
    
    function addInvoiceItem(serviceName, priceStr, serviceKey = null, timelineDays = null) {
        if (serviceKey && invoiceItems.some(item => item.serviceKey === serviceKey)) return false;
        const newItem = { id: nextId++, name: serviceName, price: priceStr, serviceKey: serviceKey || serviceName, timelineDays: timelineDays };
        invoiceItems.push(newItem);
        updateInvoiceDisplay();
        return true;
    }
    
    // ---------- Auto-add from bot messages (NOW DISABLED – only manual confirm buttons) ----------
    function autoAddFromBotMessage(text) {
        // Only extract Project ID – DO NOT automatically add any service
        const match = text.match(/Project ID:\s*`([A-Z0-9\-]+)`/i);
        if (match) {
            storedProjectId = match[1];
            localStorage.setItem(`project_id_${sessionId}`, storedProjectId);
        }
        // No automatic additions anymore!
    }
    
    // ---------- Media Upload ----------
    let mediaPanel = null;
    function createMediaPanel() {
        if (mediaPanel) return;
        const chatArea = document.getElementById('chatMessages');
        const panel = document.createElement('div');
        panel.className = 'media-panel';
        panel.innerHTML = `
            <label>Additional Notes (text):</label>
            <textarea id="mediaText" rows="2" placeholder="Type any notes..."></textarea>
            <label>Upload Image (optional):</label>
            <input type="file" id="mediaImage" accept="image/*">
            <img id="mediaPreview" class="image-preview" style="display:none;">
            <button id="mediaSubmitBtn" class="confirm-btn" style="margin-top:8px;">Submit Media</button>
        `;
        chatArea.appendChild(panel);
        mediaPanel = panel;
        const mediaTextarea = document.getElementById('mediaText');
        const mediaFileInput = document.getElementById('mediaImage');
        const mediaImagePreview = document.getElementById('mediaPreview');
        const submitBtn = document.getElementById('mediaSubmitBtn');
        mediaFileInput.onchange = () => {
            const file = mediaFileInput.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    mediaImagePreview.src = e.target.result;
                    mediaImagePreview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                mediaImagePreview.style.display = 'none';
            }
        };
        submitBtn.onclick = async () => {
            const text = mediaTextarea.value.trim();
            let imageBase64 = '';
            if (mediaFileInput.files[0]) {
                const file = mediaFileInput.files[0];
                imageBase64 = await new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.onload = (e) => resolve(e.target.result);
                    reader.readAsDataURL(file);
                });
            }
            try {
                const res = await fetch('/api/upload_media', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ session_id: sessionId, text: text, image: imageBase64 })
                });
                const data = await res.json();
                if (data.status === 'ok') {
                    userInput.value = "DONE";
                    sendMessage();
                    mediaPanel.style.display = 'none';
                } else {
                    alert("Failed to upload media");
                }
            } catch (err) {
                alert("Upload error");
            }
        };
    }
    
    function showMediaPanel() {
        if (!mediaPanel) createMediaPanel();
        mediaPanel.style.display = 'block';
    }
    
    // ---------- Message Functions (with confirm button only) ----------
    function addMessageWithConfirm(text, sender, widgetData = null) {
        const chatMessagesDiv = document.getElementById('chatMessages');
        if (sender === 'user') {
            const div = document.createElement('div');
            div.className = 'message user-msg';
            div.innerText = text;
            chatMessagesDiv.appendChild(div);
            chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
            return;
        }
        const wrapper = document.createElement('div');
        wrapper.className = 'bot-message-wrapper';
        const msgDiv = document.createElement('div');
        msgDiv.className = 'message bot-msg';
        msgDiv.innerText = text;
        wrapper.appendChild(msgDiv);
        
        // Check for media request
        if (text.startsWith("MEDIA_REQUEST|")) {
            const cleanMsg = text.replace("MEDIA_REQUEST|", "");
            msgDiv.innerText = cleanMsg;
            showMediaPanel();
        } else {
            // Only extract Project ID, no auto-add
            autoAddFromBotMessage(text);
        }
        
        let serviceName = null, servicePrice = null, serviceKey = null, timelineStr = null;
        if (widgetData) {
            if (widgetData.package) {
                serviceName = `${widgetData.package} Website Package`;
                servicePrice = widgetData.price;
                serviceKey = `pkg_${widgetData.package}`;
                timelineStr = widgetData.timeline;
            } else if (widgetData.service) {
                serviceName = widgetData.service;
                servicePrice = widgetData.price;
                serviceKey = `svc_${widgetData.service}`;
                timelineStr = widgetData.timeline;
            } else if (widgetData.extra_feature) {
                serviceName = `Extra: ${widgetData.extra_feature}`;
                servicePrice = widgetData.extra_cost;
                serviceKey = `extra_${widgetData.extra_feature}`;
                timelineStr = widgetData.extra_timeline;
            }
        }
        // Add a confirm button for packages/extra features (manual addition)
        if (serviceName && servicePrice) {
            const confirmBtn = document.createElement('button');
            confirmBtn.className = 'confirm-btn';
            confirmBtn.innerHTML = '<i class="fas fa-check-circle"></i> Confirm & Add to Quote';
            confirmBtn.onclick = () => {
                const timelineDays = timelineStr ? parseTimelineDays(timelineStr) : null;
                addInvoiceItem(serviceName, servicePrice, serviceKey, timelineDays);
                confirmBtn.disabled = true;
                confirmBtn.style.opacity = '0.6';
                confirmBtn.innerText = '✓ Added';
            };
            wrapper.appendChild(confirmBtn);
        }
        chatMessagesDiv.appendChild(wrapper);
        chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
    }
    
    function addMessage(text, sender) {
        const div = document.createElement('div');
        div.className = `message ${sender === 'user' ? 'user-msg' : 'bot-msg'}`;
        div.innerText = text;
        document.getElementById('chatMessages').appendChild(div);
        chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
    }
    
    // ---------- History Loading ----------
    let historyLoaded = false;
    async function loadChatHistory() {
        try {
            const res = await fetch(`/api/history?session_id=${sessionId}`);
            const data = await res.json();
            if (data.messages && data.messages.length) {
                const chatMessagesDiv = document.getElementById('chatMessages');
                const children = Array.from(chatMessagesDiv.children);
                let welcomeIndex = -1;
                for (let i = 0; i < children.length; i++) {
                    const child = children[i];
                    if (child.classList && child.classList.contains('message') && 
                        child.classList.contains('bot-msg') && 
                        child.innerText.includes("Assalam-o-Alaikum")) {
                        welcomeIndex = i;
                        break;
                    }
                }
                for (let i = children.length - 1; i >= 0; i--) {
                    if (i !== welcomeIndex) {
                        children[i].remove();
                    }
                }
                for (let msg of data.messages) {
                    if (msg.role === 'user') {
                        addMessage(msg.content, 'user');
                    } else if (msg.role === 'assistant') {
                        addMessage(msg.content, 'bot');
                    }
                }
            }
        } catch (err) {
            console.error("History load error", err);
        }
    }
    
    // ---------- UI Event Listeners ----------
    const chatIcon = document.getElementById('chatIcon');
    const chatModal = document.getElementById('chatModal');
    const closeChat = document.getElementById('closeChat');
    const sendBtn = document.getElementById('sendBtn');
    const userInput = document.getElementById('userInput');
    const chatMessagesDiv = document.getElementById('chatMessages');
    const questionsContainer = document.getElementById('defaultQuestionsContainer');
    const finalReportBtn = document.getElementById('finalReportBtn');
    const downloadReportBtn = document.getElementById('downloadReportBtn');
    finalReportBtn.onclick = () => {
        if (invoiceItems.length === 0) {
            addMessageWithConfirm("❌ No services added yet.", 'bot');
            return;
        }
        let report = "📋 **Final Project Report**\n\n**Selected Services:**\n";
        let totalPrice = 0, totalDays = 0;
        invoiceItems.forEach(item => {
            totalPrice += parsePrice(item.price);
            report += `- ${item.name}: ${item.price}\n`;
            if (item.timelineDays) totalDays += item.timelineDays;
        });
        report += `\n💰 Total: PKR ${totalPrice.toLocaleString()}`;
        if (totalDays) report += `\n⏱️ Timeline: ${totalDays} days`;
        if (storedProjectId) report += `\n\n📌 Project ID: ${storedProjectId}`;
        addMessageWithConfirm(report, 'bot');
    };
    downloadReportBtn.onclick = () => {
        if (invoiceItems.length === 0) { alert("No services selected."); return; }
        let content = "ELITE VISUALS – QUOTE REPORT\n\nDate: "+new Date().toLocaleString()+"\n\nServices:\n";
        let total = 0;
        invoiceItems.forEach(item => {
            total += parsePrice(item.price);
            content += `• ${item.name}: ${item.price}\n`;
        });
        content += `\nTOTAL: PKR ${total.toLocaleString()}`;
        if (storedProjectId) content += `\n\nProject ID: ${storedProjectId}`;
        const blob = new Blob([content], {type:"text/plain"});
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = `quote_${Date.now()}.txt`;
        a.click();
        URL.revokeObjectURL(a.href);
    };
    
    const invoiceColumn = document.getElementById('invoiceColumn');
    const chatColumn = document.getElementById('chatColumn');
    const toggleInvoiceBtn = document.getElementById('toggleInvoiceBtn');
    let invoiceHidden = false;
    toggleInvoiceBtn.onclick = () => {
        if (invoiceHidden) {
            invoiceColumn.classList.remove('hidden');
            chatColumn.classList.remove('expanded');
            toggleInvoiceBtn.innerHTML = '<i class="fas fa-eye-slash"></i>';
        } else {
            invoiceColumn.classList.add('hidden');
            chatColumn.classList.add('expanded');
            toggleInvoiceBtn.innerHTML = '<i class="fas fa-eye"></i>';
        }
        invoiceHidden = !invoiceHidden;
    };
    
    function renderQuestionBubbles() {
        questionsContainer.innerHTML = '';
        DEFAULT_QUESTIONS.forEach(q => {
            const bubble = document.createElement('div');
            bubble.className = 'question-bubble';
            bubble.innerText = q;
            bubble.onclick = () => { userInput.value = q; sendMessage(); };
            questionsContainer.appendChild(bubble);
        });
    }
    
    let typingDiv = null;
    function showTyping() {
        if (typingDiv) return;
        typingDiv = document.createElement('div');
        typingDiv.className = 'typing-indicator';
        typingDiv.innerHTML = '<span></span><span></span><span></span>';
        chatMessagesDiv.appendChild(typingDiv);
        chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
    }
    function hideTyping() {
        if (typingDiv) { typingDiv.remove(); typingDiv = null; }
    }
    
    async function sendMessage() {
        const msg = userInput.value.trim();
        if (!msg) return;
        if (questionsContainer) questionsContainer.style.display = 'none';
        addMessageWithConfirm(msg, 'user');
        userInput.value = '';
        showTyping();
        try {
            const res = await fetch(API_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: msg, session_id: sessionId })
            });
            const data = await res.json();
            hideTyping();
            addMessageWithConfirm(data.reply, 'bot', data.widget);
        } catch (err) {
            hideTyping();
            addMessageWithConfirm("❌ Server error. Try again.", 'bot');
        }
    }
    
    chatIcon.onclick = async () => {
        chatModal.style.display = 'flex';
        if (questionsContainer.children.length === 0) renderQuestionBubbles();
        if (!historyLoaded) {
            await loadChatHistory();
            historyLoaded = true;
        }
    };
    closeChat.onclick = () => chatModal.style.display = 'none';
    sendBtn.onclick = sendMessage;
    userInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); });
    renderQuestionBubbles();
    
    const widgetContent = document.getElementById('widgetContent');
    const toggleIcon = document.getElementById('toggleIcon');
    const hideWidgetBtn = document.getElementById('hideWidgetBtn');
    const unhideWidgetBtn = document.getElementById('unhideWidgetBtn');
    const liveWidget = document.getElementById('liveWidget');
    let widgetOpen = false;
    toggleIcon.onclick = (e) => {
        e.stopPropagation();
        if (widgetOpen) {
            widgetContent.classList.remove('show');
            toggleIcon.classList.remove('fa-chevron-up');
            toggleIcon.classList.add('fa-chevron-down');
        } else {
            widgetContent.classList.add('show');
            toggleIcon.classList.remove('fa-chevron-down');
            toggleIcon.classList.add('fa-chevron-up');
        }
        widgetOpen = !widgetOpen;
    };
    hideWidgetBtn.onclick = () => {
        liveWidget.style.display = 'none';
        hideWidgetBtn.style.display = 'none';
        unhideWidgetBtn.style.display = 'inline-flex';
    };
    unhideWidgetBtn.onclick = () => {
        liveWidget.style.display = 'block';
        hideWidgetBtn.style.display = 'inline-flex';
        unhideWidgetBtn.style.display = 'none';
    };
    function updateWidget(data) {
        // Not critical for core functionality
    }
    updateWidget(null);
</script>
</body>
</html>