File size: 24,283 Bytes
5f73f37
1a796bc
5f73f37
1d042ee
1b608f7
5f73f37
 
 
6b91e96
 
 
 
5f73f37
 
 
 
 
6b91e96
5f73f37
 
 
6b91e96
 
 
 
 
 
 
 
 
8056e97
3a29371
6b91e96
3aa70a2
5f73f37
1b608f7
113a89f
 
 
3a29371
 
 
 
 
 
 
 
 
 
 
aee5b3d
3a29371
 
 
 
 
 
 
 
aee5b3d
3a29371
 
 
 
 
 
 
aee5b3d
 
3a29371
 
 
aee5b3d
 
3a29371
 
 
 
113a89f
 
 
 
 
 
 
1b608f7
 
113a89f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333e94b
010f6a5
 
 
 
 
 
 
 
 
113a89f
3a29371
010f6a5
 
333e94b
 
 
 
 
 
 
 
 
 
010f6a5
113a89f
 
 
 
3a29371
113a89f
 
 
b5dcc88
3a29371
113a89f
 
 
e0741ec
113a89f
 
3a29371
 
 
 
 
 
 
 
113a89f
 
 
3a29371
113a89f
3a29371
 
 
 
 
 
113a89f
 
 
 
3a29371
113a89f
 
3a29371
 
aee5b3d
 
113a89f
 
 
3a29371
113a89f
 
 
 
aee5b3d
113a89f
3a29371
1b608f7
113a89f
aee5b3d
113a89f
3a29371
113a89f
 
 
3a29371
113a89f
 
 
e0741ec
 
113a89f
 
 
 
 
 
 
e0741ec
 
ca7c265
e0741ec
113a89f
ca7c265
113a89f
e0741ec
113a89f
 
e0741ec
 
113a89f
 
 
3a29371
 
113a89f
 
 
 
 
 
 
3a29371
 
113a89f
 
3a29371
 
 
 
 
 
 
113a89f
 
 
3a29371
 
 
d93ba85
 
 
b5dcc88
 
646f759
 
b5dcc88
646f759
 
 
 
3a29371
b5dcc88
 
3a29371
 
 
 
aee5b3d
3a29371
 
646f759
 
 
b5dcc88
 
646f759
 
 
3d051d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a29371
3d051d4
 
690e9af
 
ca7c265
 
690e9af
 
ca7c265
690e9af
ca7c265
690e9af
 
 
ca7c265
 
 
 
 
 
690e9af
3a29371
 
aee5b3d
3a29371
690e9af
 
efc2fa3
 
 
3d051d4
 
 
 
ca7c265
 
 
3a29371
ca7c265
aee5b3d
 
ca7c265
 
 
 
 
 
 
 
 
 
 
 
333e94b
ca7c265
 
333e94b
 
3d051d4
 
efc2fa3
3d051d4
 
 
 
 
efc2fa3
3d051d4
efc2fa3
3d051d4
 
 
 
ca7c265
113a89f
 
 
 
 
 
 
d93ba85
113a89f
 
 
efc2fa3
aebbd41
113a89f
 
 
efc2fa3
aebbd41
 
3a29371
 
 
aebbd41
 
efc2fa3
3a29371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aee5b3d
 
3a29371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aebbd41
3a29371
ca7c265
 
 
 
 
 
aebbd41
1d042ee
2da39c0
 
 
5f73f37
56df0a0
6b91e96
 
 
 
7efbd6f
 
1d042ee
5f73f37
 
 
 
 
 
 
1b608f7
1d042ee
1b608f7
5f73f37
7efbd6f
5f73f37
1d042ee
5f73f37
 
 
7efbd6f
 
 
 
 
 
 
 
3a29371
 
 
 
 
 
 
 
 
 
 
6904ddf
3aa70a2
6904ddf
 
 
ca7c265
 
3a29371
 
 
 
ca7c265
 
b5eddff
6904ddf
 
3a29371
6904ddf
 
 
 
1a796bc
6904ddf
3a29371
6904ddf
04e2021
6904ddf
 
 
1a796bc
3a29371
6904ddf
 
 
7efbd6f
 
 
1a796bc
7efbd6f
3a29371
7efbd6f
 
1b608f7
7efbd6f
 
 
 
 
 
 
 
 
 
04e2021
67eb455
6b91e96
1d042ee
 
6b91e96
 
7efbd6f
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
let conversation = [
    { role: 'bot', message: 'Hello! I’m Chef Bot, your culinary assistant! What’s your name?' }
];
let selectedItems = [];
let selectionBoxVisible = false;

function addMessage(role, message) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('Chat messages container not found!');
        return;
    }
    const messageDiv = document.createElement('div');
    messageDiv.className = role === 'bot' ? 'bot-message' : 'user-message';
    messageDiv.textContent = message;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    console.log(`Added ${role} message: ${message}`);
}

function sendMessage() {
    const userInput = document.getElementById('userInput');
    if (!userInput) {
        console.error('User input field not found!');
        return;
    }
    const message = userInput.value.trim();
    if (message) {
        addMessage('user', message);
        conversation.push({ role: 'user', message: message });
        selectionBoxVisible = true;
        handleResponse(message);
    } else {
        addMessage('bot', 'Hey, don’t be shy! Type something or add some items to get started! 😄');
    }
    userInput.value = '';
    updateSelectionBox();
}

function handleResponse(userInput) {
    const lowerInput = userInput.toLowerCase();
    let botResponse = '';

    if (conversation.length === 2) {
        botResponse = `Great to meet you, ${userInput}! 🍳 What kind of food are you craving today? Or ask me to help customize a dish!`;
        displayOptions([
            { text: 'Vegetarian', class: 'green' },
            { text: 'Non-Vegetarian', class: 'red' },
            { text: 'Both', class: 'gray' }
        ]);
        addMessage('bot', botResponse);
    } else if (lowerInput === 'vegetarian' || lowerInput === 'non-vegetarian' || lowerInput === 'both') {
        botResponse = `Nice choice! Let me whip up some ${lowerInput} options for you...`;
        addMessage('bot', botResponse);
        fetchMenuItems(lowerInput);
    } else {
        fetch('/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message: userInput, session_id: 'default' })
        })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    addMessage('bot', `Oops! ${data.error}. Let’s try something else!`);
                } else {
                    addMessage('bot', data.response);
                    // Check if the input might be a menu item or ingredient
                    fetchMenuItems(null, userInput);
                }
            })
            .catch(error => {
                addMessage('bot', `Yikes! Couldn’t reach the assistant: ${error.message}. Try searching for 'chicken' or 'paneer'!`);
                fetchMenuItems(null, userInput);
            });
    }
}

function updateSelectionBox() {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) return;

    const existingBox = document.querySelector('.selection-box');
    if (existingBox) existingBox.remove();

    if (!selectionBoxVisible && selectedItems.length === 0) return;

    const selectionBox = document.createElement('div');
    selectionBox.className = 'selection-box';

    const vegButton = document.createElement('button');
    vegButton.textContent = 'Vegetarian';
    vegButton.className = 'dietary-button green';
    vegButton.onclick = () => fetchMenuItems('vegetarian');
    selectionBox.appendChild(vegButton);

    const nonVegButton = document.createElement('button');
    nonVegButton.textContent = 'Non-Vegetarian';
    nonVegButton.className = 'dietary-button red';
    nonVegButton.onclick = () => fetchMenuItems('non-vegetarian');
    selectionBox.appendChild(nonVegButton);

    const bothButton = document.createElement('button');
    bothButton.textContent = 'Both';
    bothButton.className = 'dietary-button gray';
    bothButton.onclick = () => fetchMenuItems('both');
    selectionBox.appendChild(bothButton);

    const label = document.createElement('span');
    label.textContent = 'Selected Items:';
    selectionBox.appendChild(label);

    selectedItems.forEach((item, index) => {
        const itemContainer = document.createElement('div');
        itemContainer.className = 'selected-item';

        const img = document.createElement('img');
        img.src = item.image_url || 'https://via.placeholder.com/30';
        img.alt = item.name;
        img.className = 'selected-item-image';
        itemContainer.appendChild(img);

        const itemSpan = document.createElement('span');
        itemSpan.textContent = `${item.name} (Qty: ${item.quantity || 1})`;
        itemContainer.appendChild(itemSpan);

        const removeButton = document.createElement('button');
        removeButton.textContent = 'Remove';
        removeButton.className = 'remove-button';
        removeButton.onclick = () => {
            selectedItems.splice(index, 1);
            addMessage('bot', `Removed "${item.name}" from your selection.`);
            updateSelectionBox();
        };
        itemContainer.appendChild(removeButton);

        selectionBox.appendChild(itemContainer);
    });

    const textInput = document.createElement('input');
    textInput.type = 'text';
    textInput.placeholder = 'Add Sector_Detail__c item...';
    textInput.className = 'manual-input';
    textInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && textInput.value.trim()) {
            const itemName = textInput.value.trim();
            fetchSectorItemDetails(itemName);
            textInput.value = '';
        }
    });
    selectionBox.appendChild(textInput);

    if (selectedItems.length > 0) {
        const quantityInput = document.createElement('input');
        quantityInput.type = 'number';
        quantityInput.min = '1';
        quantityInput.value = '1';
        quantityInput.placeholder = 'Quantity';
        quantityInput.className = 'quantity-input';
        selectionBox.appendChild(quantityInput);

        const submitButton = document.createElement('button');
        submitButton.textContent = 'Submit to Salesforce';
        submitButton.className = 'submit-button';
        submitButton.onclick = () => promptAndSubmit(quantityInput.value);
        selectionBox.appendChild(submitButton);

        const orderNameInput = document.createElement('input');
        orderNameInput.type = 'text';
        orderNameInput.placeholder = 'Custom Order Name (optional)';
        orderNameInput.className = 'order-name-input';
        selectionBox.appendChild(orderNameInput);
    }

    chatMessages.appendChild(selectionBox);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    console.log('Updated selection box with items:', selectedItems.map(item => ({ name: item.name, category: item.category })));
}

function fetchMenuItems(dietaryPreference, searchTerm = '') {
    const payload = {};
    if (dietaryPreference) payload.dietary_preference = dietaryPreference;
    if (searchTerm) payload.search_term = searchTerm;
    fetch('/get_menu_items', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                addMessage('bot', `Oops! Trouble fetching items: ${data.error}. Try again or search something specific.`);
            } else if (data.menu_items.length > 0) {
                addMessage('bot', `Found ${data.menu_items.length} item${data.menu_items.length > 1 ? 's' : ''} for "${searchTerm || dietaryPreference}"!`);
                displayItemsList(data.menu_items, 'menuItemsList', true);
            } else {
                addMessage('bot', `No items found for "${searchTerm || dietaryPreference}". Try something like "paneer" or "chicken"!`);
            }
            console.log(`Fetched items for ${searchTerm || dietaryPreference}:`, data.menu_items);
        })
        .catch(error => {
            addMessage('bot', `Yikes! Couldn’t reach Salesforce: ${error.message}. I’ll retry in a sec...`);
            setTimeout(() => fetchMenuItems(dietaryPreference, searchTerm), 2000);
        });
}

function suggestItems(searchTerm) {
    fetch('/suggest_items', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ search_term: searchTerm })
    })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                addMessage('bot', `Couldn’t find anything for "${searchTerm}": ${data.error}. Got another idea?`);
            } else if (data.suggestions.length > 0) {
                addMessage('bot', `Check out these suggestions for "${searchTerm}" from Ingredient_Object__c:`);
                displayItemsList(data.suggestions, 'suggestionsList', false);
            } else {
                addMessage('bot', `No matches for "${searchTerm}" in Ingredient_Object__c. Try "chicken" or "paneer"?`);
            }
            console.log(`Suggestions for ${searchTerm}:`, data.suggestions);
        })
        .catch(error => {
            addMessage('bot', `Error fetching suggestions: ${error.message}. Retrying...`);
            setTimeout(() => suggestItems(searchTerm), 2000);
        });
}

function fetchItemDetails(itemName) {
    fetch('/get_item_details', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ item_name: itemName })
    })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                addMessage('bot', `Couldn’t find "${itemName}" in Ingredient_Object__c. Add it manually in the box below!`);
                updateSelectionBox();
            } else {
                const details = data.item_details;
                if (selectedItems.some(item => item.name === details.name)) {
                    addMessage('bot', `"${details.name}" is already in your selection!`);
                } else {
                    selectedItems.push({ ...details, quantity: 1 });
                    addMessage('bot', `Added "${itemName}" to your selection! Check the box below.`);
                    updateSelectionBox();
                }
            }
        })
        .catch(error => {
            addMessage('bot', `Trouble fetching "${itemName}": ${error.message}. Add it manually or I’ll retry...`);
            updateSelectionBox();
            setTimeout(() => fetchItemDetails(itemName), 2000);
        });
}

function fetchSectorItemDetails(itemName) {
    fetch('/get_sector_item_details', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ item_name: itemName })
    })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                addMessage('bot', `Sorry, I couldn’t find "${itemName}" in Sector_Detail__c. Try another item!`);
            } else {
                const details = data.item_details;
                if (selectedItems.some(item => item.name === details.name)) {
                    addMessage('bot', `"${details.name}" is already in your selection!`);
                } else {
                    selectedItems.push({ ...details, quantity: 1 });
                    addMessage('bot', `Added "${details.name}" to your selection from Sector_Detail__c! Check the box below.`);
                    updateSelectionBox();
                }
            }
        })
        .catch(error => {
            addMessage('bot', `Error fetching details for "${itemName}": ${error.message}. I’ll retry in a sec...`);
            setTimeout(() => fetchSectorItemDetails(itemName), 2000);
        });
}

function showDescriptionPopup(item) {
    const existingPopup = document.querySelector('.description-popup');
    if (existingPopup) existingPopup.remove();

    const popup = document.createElement('div');
    popup.className = 'description-popup';

    const content = document.createElement('div');
    content.className = 'popup-content';

    const img = document.createElement('img');
    img.src = item.image_url || 'https://via.placeholder.com/100';
    img.alt = item.name;
    img.className = 'popup-image';
    content.appendChild(img);

    const title = document.createElement('h3');
    title.textContent = item.name;
    content.appendChild(title);

    const desc = document.createElement('p');
    desc.textContent = item.description || 'No description available';
    content.appendChild(desc);

    if (item.source === 'Menu_Item__c') {
        const fields = [
            { label: 'Category', value: item.category },
            { label: 'Veg/Non-Veg', value: item.veg_nonveg },
            { label: 'Ingredients', value: item.ingredients },
            { label: 'Nutritional Info', value: item.nutritional_info },
            { label: 'Price', value: item.price ? `$${item.price.toFixed(2)}` : 'N/A' },
            { label: 'Sector', value: item.sector },
            { label: 'Spice Levels', value: item.spice_levels },
            { label: 'Dynamic Dish', value: item.dynamic_dish ? 'Yes' : 'No' }
        ];
        fields.forEach(field => {
            if (field.value) {
                const p = document.createElement('p');
                p.className = 'menu-item-field';
                p.innerHTML = `<strong>${field.label}:</strong> ${field.value}`;
                content.appendChild(p);
            }
        });
    } else {
        const category = document.createElement('p');
        category.textContent = `Category: ${item.category || 'Not specified'}`;
        content.appendChild(category);
    }

    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'button-container';

    const addButton = document.createElement('button');
    addButton.textContent = 'Add';
    addButton.className = 'popup-add-button';
    addButton.onclick = () => {
        const selectedItem = {
            name: item.name,
            image_url: item.image_url || '',
            category: item.category || 'Not specified',
            description: item.description || 'No description available',
            source: item.source,
            quantity: 1
        };
        if (item.source === 'Menu_Item__c') {
            selectedItem.ingredients = item.ingredients;
            selectedItem.nutritional_info = item.nutritional_info;
            selectedItem.price = item.price;
            selectedItem.sector = item.sector;
            selectedItem.spice_levels = item.spice_levels;
            selectedItem.veg_nonveg = item.veg_nonveg;
            selectedItem.dynamic_dish = item.dynamic_dish;
        }
        if (selectedItems.some(existing => existing.name === selectedItem.name)) {
            addMessage('bot', `"${selectedItem.name}" is already in your selection!`);
        } else {
            selectedItems.push(selectedItem);
            addMessage('bot', `Added "${selectedItem.name}" to your selection! Check the box below.`);
            updateSelectionBox();
        }
        popup.remove();
    };
    buttonContainer.appendChild(addButton);

    const closeButton = document.createElement('button');
    closeButton.textContent = 'Close';
    closeButton.className = 'popup-close-button';
    closeButton.onclick = () => popup.remove();
    buttonContainer.appendChild(closeButton);

    content.appendChild(buttonContainer);
    popup.appendChild(content);
    document.body.appendChild(popup);
}

function displayItemsList(items, containerId, isDetailed = false) {
    const container = document.getElementById(containerId);
    if (!container) {
        console.error(`${containerId} container not found!`);
        addMessage('bot', 'Something’s off with the display. Try again?');
        return;
    }
    container.innerHTML = '';
    container.className = 'ingredients-list';

    items.forEach(item => {
        const itemDiv = document.createElement('div');
        itemDiv.className = 'ingredient-item';

        const img = document.createElement('img');
        img.src = item.image_url || 'https://via.placeholder.com/60';
        img.alt = item.name;
        img.className = 'ingredient-image';
        itemDiv.appendChild(img);

        const contentDiv = document.createElement('div');
        contentDiv.className = 'ingredient-content';

        const nameDiv = document.createElement('div');
        nameDiv.textContent = item.name;
        nameDiv.className = 'ingredient-name';
        contentDiv.appendChild(nameDiv);

        if (item.source === 'Menu_Item__c' && isDetailed) {
            const fields = [
                { label: 'Price', value: item.price ? `$${item.price.toFixed(2)}` : 'N/A' },
                { label: 'Veg/Non-Veg', value: item.veg_nonveg },
                { label: 'Spice Level', value: item.spice_levels },
                { label: 'Category', value: item.category },
                { label: 'Ingredients', value: item.ingredients },
                { label: 'Nutritional Info', value: item.nutritional_info },
                { label: 'Sector', value: item.sector },
                { label: 'Dynamic Dish', value: item.dynamic_dish ? 'Yes' : 'No' }
            ];
            fields.forEach(field => {
                if (field.value) {
                    const p = document.createElement('p');
                    p.className = 'menu-item-field';
                    p.innerHTML = `<strong>${field.label}:</strong> ${field.value}`;
                    contentDiv.appendChild(p);
                }
            });
        } else if (item.source === 'Sector_Detail__c' && isDetailed) {
            const desc = document.createElement('p');
            desc.className = 'menu-item-field';
            desc.innerHTML = `<strong>Description:</strong> ${item.description}`;
            contentDiv.appendChild(desc);
        }

        itemDiv.appendChild(contentDiv);

        const addButton = document.createElement('button');
        addButton.textContent = 'Add';
        addButton.className = 'show-desc-button';
        addButton.onclick = () => {
            const selectedItem = {
                name: item.name,
                image_url: item.image_url || '',
                category: item.category || 'Not specified',
                description: item.description || 'No description available',
                source: item.source,
                quantity: 1
            };
            if (item.source === 'Menu_Item__c') {
                selectedItem.ingredients = item.ingredients;
                selectedItem.nutritional_info = item.nutritional_info;
                selectedItem.price = item.price;
                selectedItem.sector = item.sector;
                selectedItem.spice_levels = item.spice_levels;
                selectedItem.veg_nonveg = item.veg_nonveg;
                selectedItem.dynamic_dish = item.dynamic_dish;
            }
            if (selectedItems.some(existing => existing.name === selectedItem.name)) {
                addMessage('bot', `"${selectedItem.name}" is already in your selection!`);
            } else {
                selectedItems.push(selectedItem);
                addMessage('bot', `Added "${selectedItem.name}" to your selection! Check the box below.`);
                updateSelectionBox();
            }
        };
        itemDiv.appendChild(addButton);

        if (item.source === 'Sector_Detail__c' && isDetailed) {
            const showDescButton = document.createElement('button');
            showDescButton.textContent = 'Show Details';
            showDescButton.className = 'show-desc-button';
            showDescButton.onclick = () => showDescriptionPopup(item);
            itemDiv.appendChild(showDescButton);
        }

        container.appendChild(itemDiv);
    });
}

function displayOptions(options) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('Chat messages container not found for options!');
        return;
    }
    const optionsDiv = document.createElement('div');
    optionsDiv.style.marginTop = '10px';

    options.forEach(opt => {
        const button = document.createElement('button');
        button.textContent = opt.text;
        button.className = `option-button ${opt.class}`;
        button.onclick = () => {
            addMessage('user', opt.text);
            conversation.push({ role: 'user', message: opt.text });
            selectionBoxVisible = true;
            handleResponse(opt.text);
            updateSelectionBox();
        };
        optionsDiv.appendChild(button);
    });

    const backButton = document.createElement('button');
    backButton.textContent = 'Go Back';
    backButton.className = 'option-button';
    backButton.style.marginTop = '10px';
    backButton.onclick = () => resetConversation();
    optionsDiv.appendChild(document.createElement('br'));
    optionsDiv.appendChild(backButton);

    chatMessages.appendChild(optionsDiv);
}

function promptAndSubmit(quantity) {
    const orderNameInput = document.querySelector('.order-name-input');
    const customOrderName = orderNameInput ? orderNameInput.value.trim() : '';
    if (confirm(`Submit ${selectedItems.length} items with quantity ${quantity}?`)) {
        submitToSalesforce(customOrderName, quantity);
    } else {
        addMessage('bot', 'Submission cancelled. Add more items or try again!');
    }
}

function submitToSalesforce(customOrderName, quantity) {
    if (selectedItems.length === 0) {
        addMessage('bot', 'No items to submit yet! Add some tasty picks first! 😊');
        return;
    }

    const itemsToSubmit = selectedItems.map(item => ({
        name: item.name,
        category: item.category || 'Not specified',
        description: item.description || 'No description available',
        image_url: item.image_url || '',
        quantity: parseInt(quantity) || 1
    }));

    fetch('/submit_items', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: itemsToSubmit, custom_order_name: customOrderName })
    })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                addMessage('bot', `Uh-oh! Failed to submit items: ${data.error}. Want to try again?`);
            } else {
                addMessage('bot', `${data.success}! Your culinary choices are now saved under Ingredient_Name__c: ${data.ingredient_name}. What’s next on the menu?`);
                selectedItems = [];
                updateSelectionBox();
            }
        })
        .catch(error => {
            addMessage('bot', `Error submitting items: ${error.message}. I’ll retry shortly...`);
            setTimeout(() => submitToSalesforce(customOrderName, quantity), 2000);
        });
}

function resetConversation() {
    const userName = conversation.length > 1 ? conversation[1].message : 'Friend';
    conversation = [
        { role: 'bot', message: `Hello! I’m Chef Bot, your culinary assistant! What’s your name?` },
        { role: 'user', message: userName },
        { role: 'bot', message: `Great to meet you, ${userName}! 🍳 What kind of food are you craving today? Or ask me to help customize a dish!` }
    ];
    selectedItems = [];
    selectionBoxVisible = true;
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = '';
    conversation.forEach(msg => addMessage(msg.role, msg.message));
    displayOptions([
        { text: 'Vegetarian', class: 'green' },
        { text: 'Non-Vegetarian', class: 'red' },
        { text: 'Both', class: 'gray' }
    ]);
    document.getElementById('suggestionsList').innerHTML = '';
    document.getElementById('menuItemsList').innerHTML = '';
    updateSelectionBox();
}

document.getElementById('userInput').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') sendMessage();
});

console.log('Chef Bot script loaded successfully!');