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
669 lines (559 loc) · 20.4 KB
/
Copy pathscript.js
File metadata and controls
669 lines (559 loc) · 20.4 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
// =============================================
// DOM ELEMENTS
// =============================================
const nav = document.getElementById("nav");
const cuisineDropdown = document.getElementById("cuisine-filter");
const menuSearch = document.getElementById("menu-search");
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");
const timeSelect = document.getElementById("time");
const themeToggle = document.getElementById("themeToggle");
// FIX #4 — Declare filterBtns, menuTabs, menuPanels (were used but never declared)
const filterBtns = document.querySelectorAll(".filter-btn");
const menuTabs = document.querySelectorAll(".menu-tab");
const menuPanels = document.querySelectorAll(".menu-panel");
// ── Device detection ───
const isTouchDevice = window.matchMedia('(hover: none) and (pointer: coarse)').matches;
// ── FIX #9 — show correct scroll hint based on input type ────────
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';
}
// ── FIX #13 — Date validation: min = tomorrow, max = 90 days out ─────
if (dateInput) {
const tomorrow = new Date(Date.now() + 86400000);
const maxDate = new Date(Date.now() + 90 * 86400000);
dateInput.setAttribute('min', tomorrow.toISOString().split('T')[0]);
dateInput.setAttribute('max', maxDate.toISOString().split('T')[0]);
dateInput.addEventListener('change', updateAvailableTimes);
}
// ── FIX #11 — Disable past time slots when today is selected ─────
function updateAvailableTimes() {
if (!dateInput || !timeSelect) return;
const selectedDate = dateInput.value;
const todayStr = new Date().toISOString().split('T')[0];
const now = new Date();
const currentHours = now.getHours();
const currentMins = now.getMinutes();
timeSelect.querySelectorAll('option').forEach((option) => {
if (!option.value) return;
const [optHours, optMins] = option.value.split(':').map(Number);
if (selectedDate === todayStr) {
const isPast =
optHours < currentHours ||
(optHours === currentHours && optMins <= currentMins + 30);
option.disabled = isPast;
if (isPast && option.selected) {
timeSelect.value = '';
}
} else {
option.disabled = false;
}
});
}
// ── Navigation scroll effect ──
function handleScroll() {
const currentScroll = window.scrollY;
// Sticky nav background
nav.classList.toggle('scrolled', currentScroll > 50);
// Parallax skipped on touch devices
if (!isTouchDevice) {
if (heroBg) {
heroBg.style.transform = `translateY(${currentScroll * 0.5}px)`;
}
if (reservationBg && currentScroll > window.innerHeight) {
const sectionTop = document.getElementById('reservation').offsetTop;
const offset = (currentScroll - sectionTop) * 0.3;
reservationBg.style.transform = `translateY(${offset}px)`;
}
}
updateActiveNavLink();
}
// ── Active nav link on scroll ───
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) {
navLinks.forEach((link) => {
link.classList.remove('active');
if (link.getAttribute('data-section') === sectionId) {
link.classList.add('active');
}
});
}
});
}
// ── Mobile menu ───
function toggleMobileMenu() {
navToggle.classList.toggle('active');
navMenu.classList.toggle('active');
document.body.style.overflow = navMenu.classList.contains('active') ? 'hidden' : '';
}
function closeMobileMenu() {
navToggle.classList.remove('active');
navMenu.classList.remove('active');
document.body.style.overflow = '';
}
// Menu tabs functionality
function switchMenuTab(e) {
const targetTab = e.target.dataset.tab;
// Update tab buttons
menuTabs.forEach((tab) => {
tab.classList.remove("active");
});
e.target.classList.add("active");
// Update panels
menuPanels.forEach((panel) => {
panel.classList.remove("active");
if (panel.id === targetTab) {
panel.classList.add("active");
}
});
}
//
// Theme Toggle
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "light") {
document.body.classList.add("light-theme");
themeToggle.textContent = "☀️";
} else {
themeToggle.textContent = "🌙";
}
themeToggle.addEventListener("click", () => {
document.body.classList.toggle("light-theme");
const isLight = document.body.classList.contains("light-theme");
if (isLight) {
localStorage.setItem("theme", "light");
themeToggle.textContent = "☀️";
} else {
localStorage.setItem("theme", "dark");
themeToggle.textContent = "🌙";
}
});
// ── Menu Search and Filter ─────────────────────────
// FIX #1 — Use the correct parameter names (timeFilter, cuisineFilter) instead of undefined 'filter'
function filterMenuItems(timeFilter, cuisineFilter, searchText) {
const menuItems = document.querySelectorAll(".menu-item");
let visibleCount = 0;
menuItems.forEach((item) => {
const itemName = item.querySelector('h3')?.textContent?.toLowerCase() || '';
const category = item.dataset.category;
const matchesSearch = !searchText || itemName.includes(searchText.toLowerCase());
const matchesTime = timeFilter === 'all' || category === timeFilter;
const matchesCuisine = !cuisineFilter || cuisineFilter === 'all' || item.dataset.cuisine === cuisineFilter;
if (matchesSearch && matchesTime && matchesCuisine) {
item.classList.remove('hidden-item');
visibleCount++;
} else {
item.classList.add('hidden-item');
}
});
// Handle "No Results" display
let noResults = document.querySelector(".no-results");
if (visibleCount === 0) {
if (!noResults) {
noResults = document.createElement('p');
noResults.className = 'no-results';
noResults.textContent = 'No menu items found.';
document.querySelector('.menu-content')?.appendChild(noResults);
}
} else if (noResults) {
noResults.remove();
}
}
function triggerFilter() {
const activeBtn = document.querySelector(".filter-btn.active");
const timeFilter = activeBtn ? activeBtn.dataset.filter : "all";
const cuisineFilter = cuisineDropdown ? cuisineDropdown.value : "all";
const searchText = menuSearch ? menuSearch.value : "";
filterMenuItems(timeFilter, cuisineFilter, searchText);
}
if (cuisineDropdown) {
cuisineDropdown.addEventListener("change", triggerFilter);
}
if (menuSearch) {
menuSearch.addEventListener("input", triggerFilter);
}
// Filter buttons
filterBtns.forEach((btn) => {
btn.addEventListener("click", () => {
filterBtns.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
triggerFilter();
});
});
// FIX #2 — Removed duplicate menuSearch 'input' listener (was calling filterMenuItems with wrong/missing args)
// Smooth scroll for navigation links
function smoothScroll(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
const targetSection = document.querySelector(targetId);
if (targetSection) {
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
window.scrollTo({
top: targetSection.offsetTop - 80,
behavior: prefersReduced ? 'auto' : 'smooth',
});
}
closeMobileMenu();
}
// ── Reservation form submission ──
function handleFormSubmit(e) {
e.preventDefault();
const inputs = reservationForm.querySelectorAll('input, select, textarea');
let isValid = true;
inputs.forEach((input) => {
if (input.required && !input.value) {
input.style.borderColor = '#c94a4a';
isValid = false;
} else {
input.style.borderColor = '';
}
});
const emailInput = document.getElementById('email');
const phoneInput = document.getElementById('phone');
// Remove old error messages
document.querySelectorAll('.error-message').forEach(el => el.remove());
// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailInput && !emailRegex.test(emailInput.value.trim())) {
emailInput.style.borderColor = '#c94a4a';
const emailError = document.createElement('small');
emailError.className = 'error-message';
emailError.style.color = '#c94a4a';
emailError.textContent = 'Please enter a valid email address.';
emailInput.parentElement.appendChild(emailError);
isValid = false;
}
// Phone validation
if (phoneInput) {
const phoneValue = phoneInput.value.replace(/\D/g, '');
if (phoneValue.length !== 10) {
phoneInput.style.borderColor = '#c94a4a';
const phoneError = document.createElement('small');
phoneError.className = 'error-message';
phoneError.style.color = '#c94a4a';
phoneError.textContent = 'Phone number must contain exactly 10 digits.';
phoneInput.parentElement.appendChild(phoneError);
isValid = false;
}
}
if (isValid) {
const submitBtn = reservationForm.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Reservation Requested!';
submitBtn.style.backgroundColor = '#4a9c6a';
submitBtn.disabled = true;
setTimeout(() => {
reservationForm.reset();
updateAvailableTimes();
submitBtn.textContent = originalText;
submitBtn.style.backgroundColor = '';
submitBtn.disabled = false;
updateAvailableTimes();
}, 3000);
}
}
// ── Intersection Observer with prefers-reduced-motion ──────
function setupIntersectionObserver() {
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const animatedElements = document.querySelectorAll(
'.about-content, .menu-panel, .reservation-form, .location-info'
);
if (prefersReduced) {
animatedElements.forEach((el) => {
el.style.opacity = '1';
el.style.transform = 'none';
});
return;
}
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
},
{ root: null, rootMargin: '0px', threshold: 0.1 }
);
animatedElements.forEach((el) => {
el.style.opacity = '0';
el.style.transform = 'translateY(30px)';
el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
observer.observe(el);
});
}
// Inject .visible class styles
const style = document.createElement('style');
style.textContent = `.visible { opacity: 1 !important; transform: translateY(0) !important; }`;
document.head.appendChild(style);
// ── Auto-scroll on hero "Scroll To Discover" click ───
const heroScroll = document.querySelector('.hero-scroll');
let autoScrollInterval = null;
function startAutoScroll() {
autoScrollInterval = setInterval(() => {
window.scrollBy({ top: 2, behavior: 'instant' });
if (window.scrollY + window.innerHeight >= document.body.scrollHeight) {
stopAutoScroll();
}
}, 15);
}
function stopAutoScroll() {
if (autoScrollInterval) {
clearInterval(autoScrollInterval);
autoScrollInterval = null;
}
}
if (heroScroll) {
heroScroll.style.cursor = 'pointer';
heroScroll.addEventListener('click', () => {
autoScrollInterval ? stopAutoScroll() : startAutoScroll();
});
}
['mousemove', 'touchstart', 'keydown', 'wheel', 'pointerdown'].forEach((event) => {
window.addEventListener(event, stopAutoScroll);
});
// ── Back To Top ──
const backToTopBtn = document.getElementById('backToTop');
if (backToTopBtn) {
window.addEventListener('scroll', () => {
const past = window.scrollY > 300;
backToTopBtn.style.display = past ? 'block' : 'none';
backToTopBtn.classList.toggle('visible', past);
});
backToTopBtn.addEventListener('click', () => {
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
window.scrollTo({ top: 0, behavior: prefersReduced ? 'auto' : 'smooth' });
});
}
// ── Event Listeners ──
window.addEventListener('scroll', handleScroll);
navToggle.addEventListener('click', toggleMobileMenu);
navLinks.forEach((link) => link.addEventListener('click', smoothScroll));
document.querySelectorAll('.nav-cta, .nav-cta-mobile, .hero-buttons a').forEach((link) => {
link.addEventListener('click', smoothScroll);
});
if (reservationForm) {
reservationForm.addEventListener('submit', handleFormSubmit);
}
window.addEventListener('resize', () => {
if (window.innerWidth > 768) closeMobileMenu();
});
// ── Reviews (localStorage) ──
const STORAGE_KEY = 'lighthouse_reviews';
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() {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) return JSON.parse(stored);
localStorage.setItem(STORAGE_KEY, JSON.stringify([]));
return [];
}
function saveReviews(reviews) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(reviews));
}
function renderReviews() {
const grid = document.getElementById('reviews-grid');
if (!grid) return;
const userReviews = getReviews();
const allReviews = [pinnedReview, ...userReviews];
grid.innerHTML = allReviews
.map(
(r) => `
<div class="review-card">
<div class="review-stars">${'★'.repeat(r.rating)}${'☆'.repeat(5 - r.rating)}</div>
<p class="review-text">${r.text}</p>
<div class="review-author">
<div class="review-avatar">${r.name.slice(0, 2).toUpperCase()}</div>
<div>
<span class="review-name">${r.name}</span>
<span class="review-date">${r.date}</span>
</div>
</div>
</div>`
)
.join('');
}
// Star rating widget
let selectedRating = 0;
const starBtns = document.querySelectorAll('#star-input .star-btn');
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', () => {
selectedRating = +btn.dataset.value;
document.getElementById('review-rating').value = selectedRating;
starBtns.forEach((s) => s.classList.toggle('active', +s.dataset.value <= selectedRating));
});
});
// Review validation helpers
function isMeaningfulReview(text) {
const words = text.trim().split(/\s+/);
const randomPattern = /^(.)\1+$|^[a-zA-Z]{1,6}$/;
if (randomPattern.test(text.trim())) return false;
return words.length >= 3;
}
function isValidName(name) {
return /^[A-Za-z\s'\-]{3,30}$/.test(name.trim());
}
const reviewForm = document.getElementById('review-form');
const reviewMsg = document.getElementById('review-msg');
if (reviewForm) {
reviewForm.addEventListener('submit', function (e) {
e.preventDefault();
const name = document.getElementById('review-name').value.trim();
const reviewText = document.getElementById('review-text').value.trim();
reviewMsg.style.display = 'block';
if (!selectedRating) {
reviewMsg.textContent = 'Please select a star rating.';
reviewMsg.style.color = '#c94a4a';
return;
}
if (!isValidName(name)) {
reviewMsg.textContent = 'Name should contain only letters and be 3–30 characters long.';
reviewMsg.style.color = '#c94a4a';
return;
}
if (reviewText.length < 20) {
reviewMsg.textContent = 'Review must contain at least 20 characters.';
reviewMsg.style.color = '#c94a4a';
return;
}
if (!isMeaningfulReview(reviewText)) {
reviewMsg.textContent = 'Please enter a meaningful review.';
reviewMsg.style.color = '#c94a4a';
return;
}
const dateStr = new Date().toLocaleDateString('en-IN', {
day: '2-digit',
month: 'short',
year: 'numeric',
});
const newReview = {
id: Date.now(),
name,
rating: selectedRating,
text: reviewText,
date: dateStr,
};
const reviews = getReviews();
reviews.unshift(newReview);
saveReviews(reviews);
renderReviews();
reviewForm.reset();
selectedRating = 0;
document.getElementById('review-rating').value = 0;
starBtns.forEach((s) => s.classList.remove('active'));
reviewMsg.textContent = 'Review submitted successfully!';
reviewMsg.style.color = '#4a9c6a';
setTimeout(() => {
reviewMsg.style.display = 'none';
}, 3000);
});
}
// ── Veg / Non-Veg Filter ──────────────────────────────
// 1. Your filtering function, contained properly
(function () {
const dietFilterBtns = document.querySelectorAll('.diet-btn');
if (!dietFilterBtns.length) return;
function applyDietFilter(diet) {
const activePanels = document.querySelectorAll('.menu-panel.active');
activePanels.forEach((panel) => {
const items = panel.querySelectorAll('.menu-item');
let visibleCount = 0;
items.forEach((item) => {
const itemDiet = item.dataset.diet || 'all';
const show = diet === 'all' || itemDiet === diet;
item.classList.toggle('diet-hidden', !show);
if (show) visibleCount++;
});
let noResults = panel.querySelector('.diet-no-results');
if (!noResults) {
noResults = document.createElement('p');
noResults.className = 'diet-no-results';
noResults.textContent = 'No items match the selected filter.';
const menuItems = panel.querySelector('.menu-items');
if (menuItems) {
menuItems.appendChild(noResults);
}
}
noResults.classList.toggle('visible', visibleCount === 0);
});
}
dietFilterBtns.forEach((btn) => {
btn.addEventListener('click', () => {
dietFilterBtns.forEach((b) => b.classList.remove('active'));
btn.classList.add('active');
applyDietFilter(btn.dataset.diet);
});
});
document.querySelectorAll('.menu-tab').forEach((tab) => {
tab.addEventListener('click', () => {
const activeDiet = document.querySelector('.diet-btn.active')?.dataset.diet || 'all';
setTimeout(() => applyDietFilter(activeDiet), 50);
});
});
})();
// =============================================
// 3D CARD FLIP ENHANCEMENTS
// =============================================
function handleCardFlip() {
const cards = document.querySelectorAll('.food-card-3d');
const isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
if (isTouch) {
cards.forEach((card) => {
card.addEventListener('click', function (e) {
if (e.target.closest('a') || e.target.closest('button')) return;
this.classList.toggle('flipped');
});
});
}
}
// Reset mobile flip when clicking elsewhere
document.addEventListener('click', function (e) {
if (!e.target.closest('.food-card-3d')) {
document.querySelectorAll('.food-card-3d.flipped').forEach((card) => {
card.classList.remove('flipped');
});
}
});
// ── Initialise ───
document.addEventListener('DOMContentLoaded', function () {
handleScroll();
setupIntersectionObserver();
updateAvailableTimes();
renderReviews();
handleCardFlip();
});
// Mobile flip style
const styleForMobile = `
@media (max-width: 768px) {
.food-card-3d.flipped .food-card-inner {
transform: rotateY(180deg) scale(1.01);
}
}
`;
const mobileStyle = document.createElement('style');
mobileStyle.textContent = styleForMobile;
document.head.appendChild(mobileStyle);