File size: 13,244 Bytes
a16cceb
1415771
a93166b
1415771
a93166b
1415771
 
a93166b
1415771
a93166b
 
 
 
 
 
1415771
a93166b
1415771
 
a93166b
 
1415771
a93166b
 
88d6659
a93166b
 
 
 
 
 
 
 
1415771
a93166b
 
 
 
 
 
 
 
1415771
a93166b
1415771
a93166b
1415771
a93166b
88d6659
1415771
 
a93166b
1415771
 
a93166b
 
a16cceb
 
 
 
336f4d8
8ba3a2d
 
 
 
 
 
 
 
 
88d6659
8ba3a2d
 
 
 
 
336f4d8
8ba3a2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1415771
 
8ba3a2d
1415771
8ba3a2d
 
1415771
 
336f4d8
 
1415771
336f4d8
 
 
 
 
 
 
 
 
 
 
 
8ba3a2d
 
1415771
 
 
8ba3a2d
88d6659
8ba3a2d
 
 
 
 
88d6659
8ba3a2d
 
 
 
88d6659
1415771
88d6659
 
1415771
 
88d6659
 
 
1415771
 
 
 
 
 
88d6659
1415771
 
88d6659
1415771
88d6659
 
 
1415771
88d6659
1415771
88d6659
 
336f4d8
a16cceb
1415771
88d6659
 
336f4d8
a16cceb
 
 
 
 
 
 
 
 
 
1415771
88d6659
 
 
1415771
 
88d6659
 
 
 
336f4d8
 
 
88d6659
 
1415771
88d6659
1415771
 
 
 
a16cceb
88d6659
a16cceb
 
 
 
 
88d6659
a16cceb
88d6659
 
1415771
88d6659
 
 
 
 
1415771
88d6659
1415771
88d6659
 
 
 
 
 
 
 
 
 
336f4d8
 
 
1415771
 
 
336f4d8
 
 
 
 
88d6659
 
 
 
840ac72
 
88d6659
840ac72
 
 
88d6659
 
 
 
 
 
 
1415771
88d6659
 
 
 
1415771
 
88d6659
 
840ac72
 
 
 
 
 
1415771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

let currentImageUrl = "";
let stream = null;
let capturedFile = null; 

document.getElementById('imageInput').addEventListener('change', function() {
    capturedFile = null; 
    if (this.files.length > 0) {
        analyzeFood(); 
    }
});

async function startCamera() {
    const cameraContainer = document.getElementById('cameraContainer');
    const video = document.getElementById('videoElement');
    
    try {
        stream = await navigator.mediaDevices.getUserMedia({ 
            video: { facingMode: 'environment' } 
        });
        video.srcObject = stream;
        cameraContainer.classList.remove('hidden'); 
    } catch (err) {
        console.error("Lỗi xin quyền camera:", err);
        alert("Không thể mở Camera! Hãy đảm bảo bạn đã cấp quyền trong trình duyệt.");
    }
}

function stopCamera() {
    const cameraContainer = document.getElementById('cameraContainer');
    if (stream) {
        stream.getTracks().forEach(track => track.stop());
    }
    cameraContainer.classList.add('hidden'); 
}

function capturePhoto() {
    const video = document.getElementById('videoElement');
    const canvas = document.getElementById('canvasElement');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);  

    canvas.toBlob(function(blob) {
        capturedFile = new File([blob], "camera_capture.jpg", { type: "image/jpeg" });
        
        // Thông báo và dọn dẹp
        alert("📸 Đã chụp ảnh thành công! Hãy bấm 'Quét ảnh' để AI phân tích.");
        document.getElementById('imageInput').value = ""; 
        stopCamera(); 
        analyzeFood();
        
    }, 'image/jpeg', 0.9); 
}

async function analyzeFood() {
    const fileInput = document.getElementById('imageInput');
    const loadingDiv = document.getElementById('loading');
    const editorArea = document.getElementById('editorArea');
    const selectedLang = document.getElementById('outputLanguage').value;

    let fileToUpload = null;
    if (capturedFile) {
        fileToUpload = capturedFile;
    } else if (fileInput.files.length > 0) {
        fileToUpload = fileInput.files[0];
    }

    if (!fileToUpload) {
        alert("Vui lòng chọn ảnh hoặc chụp ảnh trước!");
        return;
    }

    const formData = new FormData();
    formData.append('file', fileToUpload);
    formData.append('language', selectedLang);
    loadingDiv.classList.remove('hidden');
    editorArea.classList.add('hidden');
    loadingDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });

    try {
        const response = await fetch('/analyze', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        loadingDiv.classList.add('hidden');

        if (data.success) {
            currentImageUrl = data.image_url;
            document.getElementById('editImg').src = currentImageUrl;
            document.getElementById('editName').value = data.data.dish_name;
            let rawPrice = String(data.data.price);
            let numericPrice = parseInt(rawPrice.replace(/\D/g, ''), 10);
            if (!isNaN(numericPrice)) {
            document.getElementById('editPrice').value = numericPrice.toLocaleString('en-US') + " VND";
            } 
            else {
            document.getElementById('editPrice').value = rawPrice;
            }
            document.getElementById('editDesc').value = data.data.description;
            document.getElementById('editNutri').value = data.data.nutrition_summary; 
            
            // Hiển thị tags WIP 
            const tagsDiv = document.getElementById('editTags');
            tagsDiv.innerHTML = ''; 
            if (data.data.tags && data.data.tags.length > 0) {
                data.data.tags.forEach(tag => {
                    const span = document.createElement('span');
                    span.className = 'smart-tag';
                    span.innerText = tag;
                    tagsDiv.appendChild(span);
                });
            }




            editorArea.classList.remove('hidden');
            editorArea.scrollIntoView({ behavior: 'smooth', block: 'start' });
            
            capturedFile = null; 
            fileInput.value = ""; 
        } else {
            alert("Lỗi từ Server: " + data.message);
        }

    } catch (error) {
        console.error("Error:", error);
        loadingDiv.classList.add('hidden');
        alert("Không thể kết nối đến Server.");
    }
}


function switchTab(tabId) {
     document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.add('hidden');
    });
    
    
    document.querySelectorAll('.nav-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
     document.getElementById(tabId).classList.remove('hidden');
    
     document.getElementById('btn-' + tabId).classList.add('active');
    
     window.scrollTo({ top: 0, behavior: 'smooth' });
}
 
 let menuItems = JSON.parse(localStorage.getItem('myRestaurantMenu')) || [];

 document.addEventListener('DOMContentLoaded', () => {
    renderMenu();
});

 async function analyzeForMenu(inputElement) {
    if (!inputElement.files || inputElement.files.length === 0) return;
    
    const file = inputElement.files[0];
    const loadingDiv = document.getElementById('menuLoading');
    const selectedLang = document.getElementById('outputLanguage').value;
    loadingDiv.classList.remove('hidden');
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('language', selectedLang);
    try {
        const response = await fetch('/analyze', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        loadingDiv.classList.add('hidden');

        if (data.success) {
             let rawPrice = String(data.data.price);
            let numericPrice = parseInt(rawPrice.replace(/\D/g, ''), 10);
            let formattedPrice = !isNaN(numericPrice) ? numericPrice.toLocaleString('en-US') + " VND" : rawPrice;

             const newItem = {
                id: Date.now(),  
                imageUrl: data.image_url,
                name: data.data.dish_name,
                price: formattedPrice,
                description: data.data.description,
                nutrition: data.data.nutrition_summary,

                tags: data.data.tags || []
            };

             menuItems.push(newItem);
            localStorage.setItem('myRestaurantMenu', JSON.stringify(menuItems));
            
             renderMenu();
            
             inputElement.value = "";
        } else {
            alert("Server Error: " + data.message);
        }

    } catch (error) {
        console.error("Error:", error);
        loadingDiv.classList.add('hidden');
        alert("Cannot connect to the server. Please try again later.");
    }
}

 function removeFromMenu(id) {
    menuItems = menuItems.filter(item => item.id !== id);
    localStorage.setItem('myRestaurantMenu', JSON.stringify(menuItems));
    renderMenu();
}

 function renderMenu() {
    const listContainer = document.getElementById('menuList');
    listContainer.innerHTML = ''; 

    if (menuItems.length === 0) {
        listContainer.innerHTML = '<p class="empty-menu-msg">Your menu is empty. Add some dishes!</p>';
        return;
    }

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

        // Delete if needed
        let tagsHtml = '';
        if (item.tags && item.tags.length > 0) {
            tagsHtml = '<div class="tags-container" style="margin-bottom: 10px;">' + 
                       item.tags.map(t => `<span class="smart-tag">${t}</span>`).join('') + 
                       '</div>';
        }



        // remove tagsHTML if you want to hide tags in menu list
        itemDiv.innerHTML = `
            <img src="${item.imageUrl}" alt="${item.name}" class="menu-item-img">
            <div class="menu-item-info">
                <div class="menu-item-header">
                    <h4 class="menu-item-name" contenteditable="true" onblur="updateMenuItem(${item.id}, 'name', this.innerText)" title="Click to edit">${item.name}</h4>
                    <span class="menu-item-price" contenteditable="true" onblur="updateMenuItem(${item.id}, 'price', this.innerText)" title="Click to edit">${item.price}</span>
                </div>
                ${tagsHtml}
                <p class="menu-item-desc" contenteditable="true" onblur="updateMenuItem(${item.id}, 'description', this.innerText)" title="Click to edit">${item.description}</p>
                <p class="menu-item-nutri" contenteditable="true" onblur="updateMenuItem(${item.id}, 'nutrition', this.innerText.replace('Nutrition: ', ''))" title="Click to edit">Nutrition: ${item.nutrition}</p>
            </div>
            <button onclick="removeFromMenu(${item.id})" class="remove-btn">✖ Remove</button>
        `;
        listContainer.appendChild(itemDiv);
    });
}

 function exportToPDF() {
    if (menuItems.length === 0) {
        alert("Cannot export an empty menu!");
        return;
    }
    
     window.print();
}

function updateMenuItem(id, field, newValue) {
    const itemIndex = menuItems.findIndex(item => item.id === id);
    if (itemIndex > -1) {
        menuItems[itemIndex][field] = newValue;
        localStorage.setItem('myRestaurantMenu', JSON.stringify(menuItems));
    }
}

function changeTheme() {
    const selectBox = document.getElementById('menuTheme');
    const bgImage = document.getElementById('printBgImage');
    const pdfArea = document.getElementById('pdfArea');
    const restaurantTitle = document.getElementById('restaurantName'); 
    const selectedUrl = selectBox.value;

    pdfArea.className = 'pdf-container'; 
    restaurantTitle.style.marginLeft = "0"; 
    restaurantTitle.style.borderBottom = "";

    restaurantTitle.style.marginLeft = "0";       
    restaurantTitle.style.marginRight = "0";     
    restaurantTitle.style.borderBottom = "";      
    pdfArea.classList.remove('theme-08');

    if (selectedUrl === "none") {
        bgImage.style.display = "none";
        bgImage.src = "";
        
   
        restaurantTitle.style.color = "#2c3e50"; 
        restaurantTitle.style.borderBottomColor = "#2c3e50";
    } else {
        bgImage.src = selectedUrl;
        bgImage.style.display = "block";
        
   
        if (selectedUrl.includes("06")) { 
         
            restaurantTitle.style.color = "#6d301f"; 
            
            restaurantTitle.style.borderBottomColor = "#6d301f";
           
        } 
        else if (selectedUrl.includes("08")) { 
         
            restaurantTitle.style.color = "#ffffff"; 
            restaurantTitle.style.marginLeft = "150px";
            restaurantTitle.style.borderBottom = "none";
            pdfArea.classList.add('theme-08');
            
        } 
        else if (selectedUrl.includes("07")) { 
         
            restaurantTitle.style.color = "#4673e5"; 
            restaurantTitle.style.marginRight = "180px";
            restaurantTitle.style.borderBottom = "none";
            restaurantTitle.style.fontFamily = "'Montserrat', serif";
            pdfArea.classList.add('theme-08');
        }
        else if (selectedUrl.includes("05")) { 
         
            restaurantTitle.style.color = "#dfebb1"; 
            restaurantTitle.style.borderBottom = "none";
            pdfArea.classList.add('theme-08');  
        }
    }
}


function limitTitleLength(event) {
    const title = event.target;
    if (event.key === 'Enter') {
        event.preventDefault();
        return;
    }
    const allowedKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'];
    if (title.innerText.length >= 32 && !allowedKeys.includes(event.key)) {
        event.preventDefault();
    }
}

document.addEventListener('DOMContentLoaded', function() { 
    changeTheme();
});

function updateUILanguage() {
    const selectedLang = document.getElementById('outputLanguage').value;
    localStorage.setItem('app_lang', selectedLang);

    const elements = document.querySelectorAll('[data-i18n]');

    if (uiTranslations[selectedLang]) {
        elements.forEach(el => {
            const key = el.getAttribute('data-i18n');
            
            if (uiTranslations[selectedLang][key]) {
                if (el.tagName === 'TITLE') {
                    document.title = uiTranslations[selectedLang][key];
                } else {
                    el.innerHTML = uiTranslations[selectedLang][key];
                }
            }
        });
    }
}

document.getElementById('outputLanguage').addEventListener('change', updateUILanguage);
document.addEventListener('DOMContentLoaded', function() {
    const savedLang = localStorage.getItem('app_lang');
    if (savedLang) {
        document.getElementById('outputLanguage').value = savedLang; 
    }

    updateUILanguage();
    if (typeof changeTheme === "function") {
        changeTheme();
    }
});