forked from anushkasark08/The-Lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2419 lines (2072 loc) · 85.3 KB
/
Copy pathscript.js
File metadata and controls
2419 lines (2072 loc) · 85.3 KB
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =============================================
// DOM ELEMENTS & GLOBAL VARIABLES
// =============================================
const nav = document.getElementById("nav");
const navToggle = document.getElementById("navToggle");
const navMenu = document.getElementById("navMenu");
const navLinks = document.querySelectorAll(".nav-link");
const heroBg = document.getElementById("heroBg");
const reservationBg = document.getElementById("reservationBg");
const reservationForm = document.getElementById("reservationForm");
const dateInput = document.getElementById("reservation-date") || document.getElementById("date");
const timeSelect = document.getElementById("time");
const guestsSelect = document.getElementById("guests");
const themeToggle = document.getElementById("themeToggle");
const menuSearch = document.getElementById("menu-search");
const backToTopBtn = document.getElementById("backToTop");
const filterBtns = document.querySelectorAll(".filter-btn");
const menuTabs = document.querySelectorAll(".menu-tab");
const menuPanels = document.querySelectorAll(".menu-panel");
const dietBtns = document.querySelectorAll(".diet-btn");
const cuisineDropdown = document.getElementById("cuisine-filter");
const heroScroll = document.querySelector(".hero-scroll");
const currentYear = document.getElementById("current-year");
// Order & Features globals
const orderDock = document.querySelector(".order-dock") || document.getElementById("orderDock");
const orderToggle = document.querySelector(".order-toggle") || document.getElementById("orderToggle");
const orderTabs = document.querySelectorAll(".order-tab");
const orderViews = document.querySelectorAll(".order-view");
const cartCountEl = document.querySelector(".cart-count") || document.getElementById("cartCount");
const cartTotalEl = document.querySelector(".cart-total") || document.getElementById("cartTotal");
const checkoutBtn = document.querySelector(".order-checkout") || document.getElementById("checkoutBtn");
const cartItemsEl = document.getElementById("cartItems");
const favoriteItemsEl = document.getElementById("favoriteItems");
const isTouchDevice = window.matchMedia('(hover: none) and (pointer: coarse)').matches;
// Initial state
let cart = [];
let favorites = [];
let autoScrollInterval = null;
// =============================================
// UTILITIES
// =============================================
function saveStoredList(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.warn("Saving to storage failed:", e);
}
}
function getStoredList(key) {
try {
return JSON.parse(localStorage.getItem(key)) || [];
} catch (e) {
console.warn("Storage access failed:", e);
return [];
}
}
function updateDeviceHints() {
const scrollHintMouse = document.querySelector('.scroll-hint-mouse');
const scrollHintTouch = document.querySelector('.scroll-hint-touch');
if (scrollHintMouse && scrollHintTouch) {
scrollHintMouse.style.display = isTouchDevice ? 'none' : '';
scrollHintTouch.style.display = isTouchDevice ? '' : 'none';
}
}
// =============================================
// EMAILJS CONFIGURATION
// =============================================
const EMAILJS_CONFIG = {
publicKey: 'abc123XYZ',
serviceId: 'service_abc1234',
guestTemplateId: 'template_guest01',
adminTemplateId: 'template_admin02',
};
if (typeof emailjs !== 'undefined' && EMAILJS_CONFIG.publicKey !== 'YOUR_PUBLIC_KEY') {
emailjs.init(EMAILJS_CONFIG.publicKey);
}
// =============================================
// NAVIGATION & SCROLLING
// =============================================
function updateActiveNavLink() {
const scrollPosition = window.scrollY + 150;
document.querySelectorAll("section[id]").forEach((section) => {
const sectionTop = section.offsetTop;
const sectionHeight = section.offsetHeight;
const sectionId = section.id;
if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
const hasLink = Array.from(navLinks).some((link) => link.dataset.section === sectionId);
if (!hasLink) return;
navLinks.forEach((link) => {
link.classList.remove('active');
if (link.getAttribute('data-section') === sectionId) {
link.classList.add('active');
}
});
}
});
}
function handleScroll() {
const currentScroll = window.scrollY;
if (nav) {
nav.classList.toggle("scrolled", currentScroll > 50);
}
if (!isTouchDevice) {
if (heroBg) {
heroBg.style.transform = `translateY(${currentScroll * 0.5}px)`;
}
const reservationSection = document.getElementById("reservation");
if (reservationBg && reservationSection && currentScroll > window.innerHeight) {
const offset = (currentScroll - reservationSection.offsetTop) * 0.3;
reservationBg.style.transform = `translateY(${offset}px)`;
}
}
if (backToTopBtn) {
backToTopBtn.classList.toggle("visible", currentScroll > 300);
}
updateActiveNavLink();
}
function smoothScroll(e) {
const targetId = this.getAttribute('href');
if (!targetId || targetId.startsWith('http') || targetId === '#') return;
const target = document.querySelector(targetId);
if (!target) return;
e.preventDefault();
const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
window.scrollTo({
top: target.offsetTop - 80,
behavior: prefersReduced ? "auto" : "smooth"
});
closeMobileMenu();
}
function toggleMobileMenu() {
if (!navToggle || !navMenu) return;
navToggle.classList.toggle("active");
navMenu.classList.toggle("active");
document.body.style.overflow = navMenu.classList.contains("active") ? "hidden" : "";
}
function closeMobileMenu() {
if (!navToggle || !navMenu) return;
navToggle.classList.remove("active");
navMenu.classList.remove("active");
document.body.style.overflow = "";
}
function setupAutoScroll() {
if (!heroScroll) return;
function stopAutoScroll() {
if (autoScrollInterval) {
clearInterval(autoScrollInterval);
autoScrollInterval = null;
}
}
function startAutoScroll() {
autoScrollInterval = setInterval(() => {
window.scrollBy({ top: 2, behavior: "instant" });
if (window.scrollY + window.innerHeight >= document.body.scrollHeight) {
stopAutoScroll();
}
}, 15);
}
heroScroll.addEventListener("click", () => {
autoScrollInterval ? stopAutoScroll() : startAutoScroll();
});
["mousemove", "touchstart", "keydown", "wheel", "pointerdown"].forEach((eventName) => {
window.addEventListener(eventName, stopAutoScroll, { passive: true });
});
}
// =============================================
// THEME TOGGLE
// =============================================
function updateThemeImages(isLight) {
const heroImg = document.querySelector("#heroBg img");
const resImg = document.querySelector("#reservationBg img");
const lightImg = "./images/hero-restaurant-daytime.png";
const darkImg = "./images/hero-restaurant.jpg";
if (heroImg) heroImg.src = isLight ? lightImg : darkImg;
if (resImg) resImg.src = isLight ? lightImg : darkImg;
}
function setupThemeToggle() {
if (!themeToggle) return;
let savedTheme = null;
try { savedTheme = localStorage.getItem("theme"); } catch (e) {}
const isLightOnLoad = savedTheme === "light";
document.body.classList.toggle("light-theme", isLightOnLoad);
themeToggle.textContent = isLightOnLoad ? "\u2600" : "\u263E";
updateThemeImages(isLightOnLoad);
themeToggle.addEventListener("click", () => {
const isLight = document.body.classList.toggle("light-theme");
try { localStorage.setItem("theme", isLight ? "light" : "dark"); } catch (e) {}
themeToggle.textContent = isLight ? "\u2600" : "\u263E";
updateThemeImages(isLight);
});
}
// ── Scroll effects & Parallax ──
function handleScroll() {
const currentScroll = window.scrollY;
// Scroll Progress Bar Update
const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
const progress = totalHeight > 0 ? (currentScroll / totalHeight) * 100 : 0;
const progressBar = document.getElementById("scrollProgressBar");
if (progressBar) {
progressBar.style.width = `${progress}%`;
}
if (nav) {
nav.classList.toggle("scrolled", currentScroll > 50);
}
if (!isTouchDevice) {
if (heroBg) {
heroBg.style.transform = `translateY(${currentScroll * 0.5}px)`;
}
const reservationSection = document.getElementById("reservation");
if (reservationBg && reservationSection && currentScroll > window.innerHeight) {
const offset = (currentScroll - reservationSection.offsetTop) * 0.3;
reservationBg.style.transform = `translateY(${offset}px)`;
}
}
if (backToTopBtn) {
backToTopBtn.classList.toggle("visible", currentScroll > 300);
}
updateActiveNavLink();
}
function updateActiveNavLink() {
const sections = document.querySelectorAll('section[id]');
const scrollPosition = window.scrollY + 150;
sections.forEach((section) => {
const sectionTop = section.offsetTop;
const sectionHeight = section.offsetHeight;
const sectionId = section.getAttribute('id');
if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
const hasLink = Array.from(navLinks).some((link) => link.dataset.section === sectionId);
if (!hasLink) return;
navLinks.forEach((link) => {
link.classList.remove('active');
if (link.getAttribute('data-section') === sectionId) {
link.classList.add('active');
}
});
}
});
}
// ── Mobile menu ──
function toggleMobileMenu() {
if (!navToggle || !navMenu) return;
navToggle.classList.toggle('active');
navMenu.classList.toggle('active');
document.body.style.overflow = navMenu.classList.contains('active') ? 'hidden' : '';
}
function closeMobileMenu() {
if (!navToggle || !navMenu) return;
navToggle.classList.remove('active');
navMenu.classList.remove('active');
document.body.style.overflow = '';
}
// ── Menu Tabs and Filtering ──
// =============================================
// MENU FILTERING & TABS
// =============================================
function switchMenuTab(e) {
const targetTab = e.target.dataset.tab;
if (!targetTab) return;
menuTabs.forEach((tab) => tab.classList.remove('active'));
e.target.classList.add('active');
menuPanels.forEach((panel) => {
panel.classList.remove('active');
if (panel.id === targetTab) {
panel.classList.add('active');
}
});
filterMenuItems(getActiveFilter(), menuSearch ? menuSearch.value : '', getActiveDiet());
}
function getActiveFilter() {
const activeBtn = document.querySelector('.filter-btn.active');
return activeBtn ? activeBtn.dataset.filter : 'all';
}
function getActiveDiet() {
const activeBtn = document.querySelector('.diet-btn.active');
return activeBtn ? (activeBtn.dataset.type || activeBtn.dataset.diet) : 'all';
}
function filterMenuItems(filter = 'all', searchText = '', diet = 'all') {
const menuItems = document.querySelectorAll('.menu-item');
let visibleCount = 0;
const searchLower = (menuSearch ? menuSearch.value.trim() : searchText).toLowerCase();
// Escape special regex characters to prevent errors on user input like "(", "."
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Apply or remove highlight on a single element, preserving original text
function applyHighlight(el, query) {
if (!el) return;
if (!el.dataset.original) {
el.dataset.original = el.textContent;
}
const original = el.dataset.original;
if (query) {
const regex = new RegExp(`(${escapeRegex(query)})`, 'gi');
el.innerHTML = original.replace(regex, '<span class="search-highlight">$1</span>');
} else {
el.textContent = original;
}
}
menuItems.forEach((item) => {
const h3 = item.querySelector('.polaroid-caption h3');
const descEl = item.querySelector('.back-content > p');
const ingredientsEl = item.querySelector('.back-ingredients span');
const itemName = (h3?.textContent || '').toLowerCase();
const itemDesc = (descEl?.textContent || '').toLowerCase();
const itemIngredients = (ingredientsEl?.textContent || '').toLowerCase();
const category = item.dataset.category || 'all';
const itemDiet = item.dataset.diet || item.dataset.type || 'all';
const matchesSearch = !searchLower ||
itemName.includes(searchLower) ||
itemDesc.includes(searchLower) ||
itemIngredients.includes(searchLower);
const matchesFilter = filter === 'all' || category === filter;
const matchesDiet = diet === 'all' || itemDiet === diet;
// Apply highlight to name, description, and ingredients
applyHighlight(h3, searchLower);
applyHighlight(descEl, searchLower);
applyHighlight(ingredientsEl, searchLower);
if (matchesSearch && matchesFilter && matchesDiet) {
item.classList.remove('hidden-item', 'diet-hidden');
item.style.display = "";
visibleCount++;
} else {
item.classList.add('hidden-item', 'diet-hidden');
item.style.display = "none";
}
});
menuPanels.forEach((panel) => {
if (panel.classList.contains('active')) {
let noResultsMsg = panel.querySelector('.diet-no-results') || panel.querySelector('.no-results');
if (!noResultsMsg) {
noResultsMsg = document.createElement('p');
noResultsMsg.className = 'diet-no-results';
noResultsMsg.textContent = (typeof i18next !== 'undefined' && i18next.t)
? i18next.t("menu.diet_no_results")
: 'No items match the selected filter.';
const menuItemsContainer = panel.querySelector('.menu-items');
if (menuItemsContainer) {
menuItemsContainer.appendChild(noResultsMsg);
} else {
panel.appendChild(noResultsMsg);
}
}
if (visibleCount === 0) {
noResultsMsg.classList.add('visible');
noResultsMsg.style.display = 'block';
} else {
noResultsMsg.classList.remove('visible');
noResultsMsg.style.display = 'none';
}
}
});
}
function displayCategoryCount() {
const categoryBtns = document.querySelectorAll('.filter-btn:not([data-filter="all"])');
const countEl = document.getElementById('menu-category-count');
if (countEl) countEl.textContent = categoryBtns.length + ' Menu Categories Available';
}
// =============================================
// RESERVATION API & SYSTEM
// =============================================
function setReservationDateRange() {
if (!dateInput) return;
const tomorrow = new Date(Date.now() + 86400000);
const maxDate = new Date(Date.now() + 90 * 86400000);
dateInput.min = tomorrow.toISOString().split('T')[0];
dateInput.max = maxDate.toISOString().split('T')[0];
}
const TOTAL_TABLES = 12;
const mockBookings = {};
function getAvailableTables(dateStr, timeStr, guestsCount) {
if (mockBookings[dateStr] && mockBookings[dateStr][timeStr] !== undefined) {
return mockBookings[dateStr][timeStr];
}
const hash = dateStr.split('-').join('') + timeStr.replace(':', '') + (guestsCount || '2');
let num = parseInt(hash, 10);
const hour = parseInt(timeStr.split(':')[0], 10);
if (hour >= 18 && hour <= 20) num += 7;
const booked = (num % (TOTAL_TABLES + 3)) - 1;
return Math.max(0, TOTAL_TABLES - Math.max(0, booked));
}
class ReservationAPI {
constructor() {
this.baseURL = 'http://localhost:5000/api';
this.token = localStorage.getItem('token');
}
setToken(token) {
this.token = token;
if (token) localStorage.setItem('token', token);
else localStorage.removeItem('token');
}
getHeaders() {
const headers = { 'Content-Type': 'application/json' };
if (this.token) headers['Authorization'] = `Bearer ${this.token}`;
return headers;
}
async getAvailableSlots(date, guests) {
try {
const response = await fetch(`${this.baseURL}/reservations/slots?date=${date}&guests=${guests}`, { headers: this.getHeaders() });
return response.json();
} catch (e) {
return { success: false, error: e.message };
}
}
async createReservation(data) {
try {
const response = await fetch(`${this.baseURL}/reservations`, { method: 'POST', headers: this.getHeaders(), body: JSON.stringify(data) });
return response.json();
} catch (e) {
return { success: false, error: e.message };
}
}
}
const reservationAPI = new ReservationAPI();
async function updateAvailableSlots() {
if (!dateInput || !timeSelect) return;
const date = dateInput.value;
const guests = guestsSelect ? guestsSelect.value : 2;
if (!date || !guests || guests < 1) return;
try {
const result = await reservationAPI.getAvailableSlots(date, guests);
if (result.success && result.data && result.data.slots) {
timeSelect.innerHTML = '<option value="">Select Time</option>';
if (typeof i18next !== 'undefined' && i18next.t) {
timeSelect.options[0].textContent = i18next.t("reservation.select_time");
}
result.data.slots.forEach(slot => {
const option = document.createElement('option');
option.value = slot.time;
option.textContent = slot.time + (slot.available ? ' ✅' : ' ❌');
option.disabled = !slot.available;
timeSelect.appendChild(option);
});
const existingMsg = document.getElementById('availability-msg');
if (existingMsg) existingMsg.remove();
const availableCount = result.data.slots.filter(s => s.available).length;
if (availableCount === 0) {
const msg = document.createElement('p');
msg.id = 'availability-msg';
msg.style.color = '#c9a962';
msg.textContent = '⚠️ No tables available for this date and party size';
timeSelect.parentNode.appendChild(msg);
}
}
} catch (error) {
console.error('Error fetching availability:', error);
}
}
function updateAvailableTimes() {
if (!dateInput || !timeSelect) return;
const selectedDate = dateInput.value;
const guests = guestsSelect ? guestsSelect.value : "2";
if(!selectedDate) return;
const todayStr = new Date().toISOString().split('T')[0];
const now = new Date();
const currentHours = now.getHours();
const currentMins = now.getMinutes();
Array.from(timeSelect.options).forEach(opt => {
if(!opt.value) return;
const [optHours, optMins] = opt.value.split(':').map(Number);
let isPast = false;
if (selectedDate === todayStr) {
if (optHours < currentHours || (optHours === currentHours && optMins <= currentMins + 30)) {
isPast = true;
}
}
const tables = getAvailableTables(selectedDate, opt.value, guests);
if (isPast || tables === 0) {
opt.disabled = true;
opt.textContent = formatBookingTime(opt.value) + " (Unavailable)";
if (isPast && opt.selected) timeSelect.value = '';
} else {
opt.disabled = false;
opt.textContent = formatBookingTime(opt.value);
}
});
if (typeof reservationAPI !== 'undefined' && reservationAPI.token) {
updateAvailableSlots();
}
}
function formatBookingDate(dateStr) {
if (!dateStr) return dateStr;
const d = new Date(dateStr + 'T00:00:00');
return d.toLocaleDateString('en-IN', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
}
function formatBookingTime(timeStr) {
if (!timeStr || !timeStr.includes(':')) return timeStr;
const [h, m] = timeStr.split(':').map(Number);
const period = h >= 12 ? 'PM' : 'AM';
const hour12 = h % 12 || 12;
return `${hour12}:${String(m).padStart(2, '0')} ${period}`;
}
function addError(input, message) {
input.style.borderColor = "#c94a4a";
const error = document.createElement("small");
error.className = "error-message";
error.style.color = "#c94a4a";
error.textContent = message;
input.parentElement.appendChild(error);
}
function showReservationToast(type, message) {
const existing = document.querySelector('.reservation-toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = `reservation-toast reservation-toast--${type}`;
toast.innerHTML = `
<div class="reservation-toast__icon">${type === 'success' ? '✓' : '✕'}</div>
<div class="reservation-toast__body">
<p class="reservation-toast__title">${type === 'success' ? 'Reservation Requested!' : 'Something went wrong'}</p>
<p class="reservation-toast__msg">${message}</p>
</div>
<button class="reservation-toast__close" aria-label="Close">✕</button>
`;
document.body.appendChild(toast);
requestAnimationFrame(() => toast.classList.add('reservation-toast--visible'));
toast.querySelector('.reservation-toast__close').addEventListener('click', () => {
toast.classList.remove('reservation-toast--visible');
setTimeout(() => toast.remove(), 400);
});
setTimeout(() => {
toast.classList.remove('reservation-toast--visible');
setTimeout(() => toast.remove(), 400);
}, 6000);
}
async function handleFormSubmit(e) {
e.preventDefault();
let isValid = true;
const emailInput = document.getElementById("email");
const phoneInput = document.getElementById("phone");
const selectedTableInput = document.getElementById("selected-table");
const submitBtn = reservationForm.querySelector('button[type="submit"]');
reservationForm.querySelectorAll(".error-message").forEach((error) => error.remove());
reservationForm.querySelectorAll("input, select, textarea").forEach((input) => {
const invalid = input.required && !input.value.trim();
input.style.borderColor = invalid ? "#c94a4a" : "";
if (invalid) isValid = false;
});
if (emailInput && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(emailInput.value.trim())) {
addError(emailInput, typeof i18next !== 'undefined' && i18next.t ? i18next.t('reservation.email_error') : "Please enter a valid email address.");
isValid = false;
}
if (phoneInput && phoneInput.value.replace(/\D/g, "").length !== 10) {
addError(phoneInput, typeof i18next !== 'undefined' && i18next.t ? i18next.t('reservation.phone_error') : "Phone number must contain exactly 10 digits.");
isValid = false;
}
if (selectedTableInput && !selectedTableInput.value) {
const mapContainer = document.querySelector(".seating-map-container");
if (mapContainer) {
addError(mapContainer, typeof i18next !== 'undefined' && i18next.t ? i18next.t('reservation.table_error') : "Please select an available table on the map.");
isValid = false;
}
}
if (!isValid) return;
const originalText = submitBtn.textContent;
const dateVal = dateInput?.value;
const timeVal = timeSelect?.value;
const guestsVal = guestsSelect?.value || '2';
const requestsVal = document.getElementById('requests')?.value || 'None';
const selectedZone = document.getElementById('selected-zone')?.value || 'main';
const selectedTable = selectedTableInput?.value || '';
const structuredRequests = selectedTable ? `[Zone: ${selectedZone.toUpperCase()}, Table: ${selectedTable}] ${requestsVal}`.trim() : requestsVal.trim();
const formData = {
guest_name: document.getElementById('name').value.trim(),
guest_email: emailInput.value.trim(),
guest_phone: phoneInput ? phoneInput.value.trim() : document.getElementById('phone').value.trim(),
guest_count: guestsVal,
booking_date: formatBookingDate(dateVal),
booking_time: formatBookingTime(timeVal),
special_requests: structuredRequests,
restaurant_name: 'The Lighthouse',
restaurant_phone: '(555) 123-4567',
restaurant_email: 'reservations@thelighthouse.com',
};
submitBtn.textContent = 'Sending…';
submitBtn.disabled = true;
// 1. API Route
if (reservationAPI && reservationAPI.token) {
try {
const apiData = { date: dateVal, time: timeVal, guests: guestsVal, specialRequests: structuredRequests };
const result = await reservationAPI.createReservation(apiData);
if (result.success) {
showReservationToast('success', `Reservation confirmed for ${selectedTable}! Check your email for details.`);
addLoyaltyPoints(100, "Table Reservation");
showDigitalTicket(formData.guest_name, formData.booking_date, formData.booking_time, formData.guest_count, selectedTable);
showReservationSuccessModal(dateVal, timeVal, guestsVal);
showReservationToast('success', `Reservation confirmed for ${selectedTable || formData.guest_count + ' guest(s)'}! Check your email for details.`);
if (typeof addLoyaltyPoints === 'function') addLoyaltyPoints(100, "Table Reservation");
reservationForm.reset();
updateAvailableTimes();
submitBtn.textContent = originalText;
submitBtn.disabled = false;
return;
}
} catch (err) {
console.warn('API reservation failed, trying EmailJS fallback', err);
}
}
// 2. Demo / Fallback Route
if (typeof emailjs === 'undefined' || EMAILJS_CONFIG.publicKey === 'YOUR_PUBLIC_KEY' || EMAILJS_CONFIG.publicKey === 'abc123XYZ') {
console.warn('[EmailJS] Not configured — running in demo mode.');
await new Promise(r => setTimeout(r, 1200));
showReservationToast('success', `Thank you, ${formData.guest_name}! We've registered your request for ${formData.guest_count} guest(s) at ${selectedTable} on ${formData.booking_date} at ${formData.booking_time}.`);
addLoyaltyPoints(100, "Table Reservation");
showDigitalTicket(formData.guest_name, formData.booking_date, formData.booking_time, formData.guest_count, selectedTable);
showReservationSuccessModal(dateVal, timeVal, guestsVal);
showReservationToast('success', `Thank you, ${formData.guest_name}! We've registered your request for ${formData.guest_count} guest(s) at ${selectedTable || 'your table'} on ${formData.booking_date} at ${formData.booking_time}.`);
if (typeof addLoyaltyPoints === 'function') addLoyaltyPoints(100, "Table Reservation");
reservationForm.reset();
updateAvailableTimes();
submitBtn.textContent = originalText;
submitBtn.disabled = false;
} else {
try {
await emailjs.send(EMAILJS_CONFIG.serviceId, EMAILJS_CONFIG.guestTemplateId, formData);
await emailjs.send(EMAILJS_CONFIG.serviceId, EMAILJS_CONFIG.adminTemplateId, formData);
showReservationToast('success', `Thank you, ${formData.guest_name}! A confirmation for ${selectedTable} has been sent to ${formData.guest_email}.`);
addLoyaltyPoints(100, "Table Reservation");
showDigitalTicket(formData.guest_name, formData.booking_date, formData.booking_time, formData.guest_count, selectedTable);
showReservationSuccessModal(dateVal, timeVal, guestsVal);
reservationForm.reset();
updateAvailableTimes();
} catch (err) {
console.error('[EmailJS] Error:', err);
showReservationToast('error', 'We couldn\'t send your confirmation email. Please call us at (555) 123-4567.');
} finally {
submitBtn.textContent = originalText;
submitBtn.disabled = false;
}
return;
}
// 3. EmailJS Route
try {
await emailjs.send(EMAILJS_CONFIG.serviceId, EMAILJS_CONFIG.guestTemplateId, formData);
await emailjs.send(EMAILJS_CONFIG.serviceId, EMAILJS_CONFIG.adminTemplateId, formData);
showReservationToast('success', `Thank you, ${formData.guest_name}! A confirmation has been sent to ${formData.guest_email}.`);
if (typeof addLoyaltyPoints === 'function') addLoyaltyPoints(100, "Table Reservation");
reservationForm.reset();
updateAvailableTimes();
} catch (err) {
console.error('[EmailJS] Error:', err);
showReservationToast('error', 'We couldn\'t send your confirmation email. Please call us at (555) 123-4567 or try again.');
} finally {
submitBtn.textContent = originalText;
submitBtn.disabled = false;
}
}
// =============================================
// SEATING ZONE MAP (Feature)
// =============================================
function setupSeatingMap() {
const zoneCards = document.querySelectorAll(".zone-card");
const seatingMap = document.getElementById("seating-map");
const selectedZoneInput = document.getElementById("selected-zone");
const selectedTableInput = document.getElementById("selected-table");
if (!zoneCards.length || !seatingMap) return;
function renderSeatingMap() {
const zone = selectedZoneInput.value;
const dateVal = dateInput?.value || "today";
const timeVal = timeSelect?.value || "18:00";
seatingMap.innerHTML = "";
selectedTableInput.value = "";
for (let t = 1; t <= 10; t++) {
const tableBtn = document.createElement("button");
tableBtn.type = "button";
tableBtn.className = "seating-table";
let capacity = 2;
if (t % 3 === 0) capacity = 4;
else if (t === 10) capacity = 6;
tableBtn.innerHTML = `T${t} <span>${capacity} Seats</span>`;
const seed = dateVal.replace(/-/g, "") + timeVal.replace(/:/g, "") + zone + t;
let hash = 0;
for (let i = 0; i < seed.length; i++) {
hash = seed.charCodeAt(i) + ((hash << 5) - hash);
}
const isReserved = Math.abs(hash) % 3 === 0;
if (isReserved) {
tableBtn.classList.add("reserved");
tableBtn.disabled = true;
} else {
tableBtn.classList.add("available");
tableBtn.addEventListener("click", () => {
document.querySelectorAll(".seating-table").forEach(btn => btn.classList.remove("selected"));
tableBtn.classList.add("selected");
selectedTableInput.value = `Table ${t} (${zone.toUpperCase()})`;
});
}
seatingMap.appendChild(tableBtn);
}
}
zoneCards.forEach(card => {
card.addEventListener("click", () => {
zoneCards.forEach(c => c.classList.remove("active"));
card.classList.add("active");
selectedZoneInput.value = card.dataset.zone;
renderSeatingMap();
});
});
dateInput?.addEventListener("change", renderSeatingMap);
timeSelect?.addEventListener("change", renderSeatingMap);
if (reservationForm) {
reservationForm.addEventListener("reset", () => {
zoneCards.forEach(c => c.classList.remove("active"));
const mainZoneCard = document.querySelector('.zone-card[data-zone="main"]');
if (mainZoneCard) mainZoneCard.classList.add("active");
if (selectedZoneInput) selectedZoneInput.value = "main";
setTimeout(renderSeatingMap, 0);
});
}
renderSeatingMap();
}
// =============================================
// INTERSECTION OBSERVER & ANIMATIONS
// =============================================
function setupIntersectionObserver() {
const animatedElements = document.querySelectorAll(
".about-content, .menu-panel, .reservation-form, .location-info"
);
const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (prefersReduced || !("IntersectionObserver" in window)) {
animatedElements.forEach((el) => el.classList.add("visible"));
return;
}
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
observer.unobserve(entry.target);
}
});
},
{ rootMargin: "0px 0px -50px 0px" }
);
animatedElements.forEach((el) => observer.observe(el));
}
function handleCardFlip() {
const cards = document.querySelectorAll('.food-card-3d');
if (isTouchDevice) {
cards.forEach((card) => {
card.addEventListener('click', function (e) {
if (e.target.closest('a') || e.target.closest('button') || e.target.closest('.menu-action-btn')) return;
this.classList.toggle('flipped');
});
});
}
}
document.addEventListener('click', function (e) {
if (!e.target.closest('.food-card-3d')) {
document.querySelectorAll('.food-card-3d.flipped').forEach((card) => {
card.classList.remove('flipped');
});
}
});
function initSkeletonLoaders() {
const cards = document.querySelectorAll(".food-card, .polaroid-image-wrapper");
cards.forEach((card) => {
const img = card.querySelector("img");
if (!img) return;
img.classList.add("image-hidden");
const revealImage = () => {
img.classList.remove("image-hidden");
img.classList.add("image-loaded");
};
if (img.complete && img.naturalWidth > 0) {
revealImage();
} else {
img.addEventListener("load", revealImage, { once: true });
img.addEventListener("error", revealImage, { once: true });
}
});
}
// =============================================
// REVIEWS
// =============================================
function setupReviews() {
const storageKey = "lighthouse_reviews";
const reviewForm = document.getElementById("review-form");
const reviewMsg = document.getElementById("review-msg");
const starBtns = document.querySelectorAll("#star-input .star-btn");
const ratingInput = document.getElementById("review-rating");
let selectedRating = 0;
const pinnedReview = {
name: "Rasshi Srivastav",
rating: 5,
text: "Absolutely loved the food and ambience! Every dish was crafted with such care and the atmosphere was warm and elegant. A truly memorable dining experience - will definitely be coming back!",
date: "14 May 2026",
};
function getReviews() {
try {
return JSON.parse(localStorage.getItem(storageKey)) || [];
} catch {
return [];
}
}
function renderReviews() {
const grid = document.getElementById("reviews-grid");
if (!grid) return;
grid.innerHTML = "";
// Apply translations to pinned review if available
const activePinned = {
...pinnedReview,
text: typeof i18next !== 'undefined' && i18next.t && i18next.t('reviews.pinned_review_text') !== 'reviews.pinned_review_text'
? i18next.t('reviews.pinned_review_text') : pinnedReview.text,
date: typeof i18next !== 'undefined' && i18next.t && i18next.t('reviews.pinned_review_date') !== 'reviews.pinned_review_date'
? i18next.t('reviews.pinned_review_date') : pinnedReview.date,
};
[activePinned, ...getReviews()].forEach((review) => {
const card = document.createElement("div");
card.className = "review-card";
const rating = Math.max(0, Math.min(5, Math.round(Number(review.rating) || 0)));
const stars = "\u2605".repeat(rating) + "\u2606".repeat(5 - rating);
card.innerHTML = `
<div class="review-stars">${stars}</div>
<p class="review-text"></p>
<div class="review-author">
<div class="review-avatar"></div>
<div>
<span class="review-name"></span>
<span class="review-date"></span>
</div>
</div>
`;
card.querySelector(".review-text").textContent = review.text;
card.querySelector(".review-avatar").textContent = review.name.slice(0, 2).toUpperCase();
card.querySelector(".review-name").textContent = review.name;
card.querySelector(".review-date").textContent = review.date;
grid.appendChild(card);
});
}
function isMeaningfulReview(text) {
const value = text.trim();
const words = value.split(/\s+/);
return words.length >= 3 && !/^(.)\1+$|^[a-zA-Z]{1,6}$/.test(value);
}
if (starBtns.length) {
starBtns.forEach(btn => {
btn.addEventListener('mouseenter', () => {
const val = +btn.dataset.value;
starBtns.forEach((s) => s.classList.toggle('active', +s.dataset.value <= val));
});
btn.addEventListener('mouseleave', () => {
starBtns.forEach((s) => s.classList.toggle('active', +s.dataset.value <= selectedRating));
});
btn.addEventListener('click', (e) => {
selectedRating = parseInt(e.target.dataset.value, 10);
if (ratingInput) ratingInput.value = selectedRating;
starBtns.forEach((s) => s.classList.toggle('active', +s.dataset.value <= selectedRating));
});
});
}
if (reviewForm) {
reviewForm.addEventListener('submit', (e) => {
e.preventDefault();
const nameInput = document.getElementById("review-name");
const textInput = document.getElementById("review-text");
const name = nameInput ? nameInput.value.trim() : "";
const text = textInput ? textInput.value.trim() : "";
if (!reviewMsg) return;
reviewMsg.style.display = "block";
if (selectedRating === 0) {
reviewMsg.textContent = typeof i18next !== 'undefined' && i18next.t ? i18next.t('reviews.rating_error') : "Please select a rating.";