// ===================================
// PUSHPVATIKA FLORIST — SITE SCRIPTS
// ===================================
// Note: the following functions are referenced from inline `onclick`
// attributes in the HTML and must stay in the global scope:
//   changeSlide, goToSlide, moveTestimonial, currentTestimonial,
//   openGalleryLightbox, closeGalleryLightbox, scrollToTop
// `showNotification` is also called from the inline script on contact.html.

// ===================================
// MOTION PREFERENCES
// ===================================
var reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');

function prefersReducedMotion() {
    return reducedMotionQuery.matches;
}

// ===================================
// SINGLE rAF-THROTTLED SCROLL HANDLER
// ===================================
// One passive listener drives every scroll-dependent effect on the page.
// DOM lookups are hoisted so nothing queries the document per scroll event.
var scrollProgressEl = null;
var navbarEl = null;
var scrollFramePending = false;

function updateOnScroll() {
    scrollFramePending = false;

    var scrollY = window.pageYOffset;

    if (scrollProgressEl) {
        var scrollableHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        var scrolled = scrollableHeight > 0 ? (scrollY / scrollableHeight) * 100 : 0;
        scrollProgressEl.style.width = scrolled + '%';
    }

    if (navbarEl) {
        if (scrollY > 100) {
            navbarEl.classList.add('scrolled');
            navbarEl.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        } else {
            navbarEl.classList.remove('scrolled');
            navbarEl.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
        }
    }
}

function requestScrollUpdate() {
    if (!scrollFramePending) {
        scrollFramePending = true;
        window.requestAnimationFrame(updateOnScroll);
    }
}

window.addEventListener('scroll', requestScrollUpdate, { passive: true });

function initScrollEffects() {
    scrollProgressEl = document.getElementById('scrollProgress');
    navbarEl = document.querySelector('.navbar');
    updateOnScroll();
}

// ===================================
// REVEAL ON SCROLL ANIMATIONS
// ===================================
function initScrollReveal() {
    var revealElements = document.querySelectorAll('.reveal, .reveal-left, .reveal-right, .reveal-scale');
    if (revealElements.length === 0) {
        return;
    }

    if (prefersReducedMotion()) {
        revealElements.forEach(function (element) {
            element.classList.add('active');
        });
        return;
    }

    var revealObserver = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
                entry.target.classList.add('active');
                revealObserver.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.15,
        rootMargin: '0px 0px -50px 0px'
    });

    revealElements.forEach(function (element) {
        revealObserver.observe(element);
    });
}

// ===================================
// PAGE BOOTSTRAP
// ===================================
document.addEventListener('DOMContentLoaded', function () {
    // Defensive: if a legacy full-screen loader overlay is still in the markup,
    // make sure it can never sit on top of the page.
    removeLegacyPageLoader();

    initScrollEffects();
    initializeNavigation();
    highlightActiveNav();
    initScrollReveal();

    // Smooth scrolling for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(function (anchor) {
        anchor.addEventListener('click', function (e) {
            var href = this.getAttribute('href');
            if (!href || href === '#') {
                return;
            }
            var target = document.querySelector(href);
            if (target) {
                e.preventDefault();
                target.scrollIntoView({
                    behavior: prefersReducedMotion() ? 'auto' : 'smooth',
                    block: 'start'
                });
            }
        });
    });
});

// The page-loader overlay has been removed from the CSS and the markup.
// This guard exists purely so a cached/stale page can never be left blank.
function removeLegacyPageLoader() {
    var loaders = document.querySelectorAll('.page-loader, #pageLoader');
    loaders.forEach(function (loader) {
        loader.remove();
    });
}

// ===================================
// NAVIGATION
// ===================================
function initializeNavigation() {
    var menuToggle = document.querySelector('.menu-toggle');
    var navMenu = document.querySelector('.nav-menu');

    if (!menuToggle || !navMenu) {
        return;
    }

    function setMenuState(isOpen) {
        navMenu.classList.toggle('active', isOpen);
        menuToggle.classList.toggle('active', isOpen);
        menuToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    }

    // Expose the closed state to assistive tech from the start.
    setMenuState(navMenu.classList.contains('active'));

    menuToggle.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        setMenuState(!navMenu.classList.contains('active'));
    });

    // Close menu when clicking outside
    document.addEventListener('click', function (event) {
        if (!navMenu.classList.contains('active')) {
            return;
        }
        if (!navMenu.contains(event.target) && !menuToggle.contains(event.target)) {
            setMenuState(false);
        }
    });

    // Close menu when clicking on a link
    navMenu.querySelectorAll('a').forEach(function (link) {
        link.addEventListener('click', function () {
            setMenuState(false);
        });
    });
}

// Highlight active navigation link
function highlightActiveNav() {
    // Get the current path (works for both clean URLs and .html URLs)
    var currentPath = window.location.pathname;

    // Remove trailing slash if present (except for root)
    if (currentPath.length > 1 && currentPath.endsWith('/')) {
        currentPath = currentPath.slice(0, -1);
    }

    // Remove .html extension if present for backward compatibility
    if (currentPath.endsWith('.html')) {
        currentPath = currentPath.replace('.html', '');
    }

    if (currentPath === '' || currentPath === '/') {
        currentPath = '/';
    }

    document.querySelectorAll('.nav-menu a').forEach(function (link) {
        var linkHref = link.getAttribute('href');
        if (!linkHref) {
            return;
        }

        if (linkHref.endsWith('.html')) {
            linkHref = linkHref.replace('.html', '');
        }

        if (linkHref === 'index' || linkHref === '/index') {
            linkHref = '/';
        }

        if (linkHref === currentPath) {
            link.classList.add('active');
        }
    });
}

// ===================================
// NOTIFICATIONS
// ===================================
var notificationStylesInjected = false;

function injectNotificationStyles() {
    if (notificationStylesInjected) {
        return;
    }
    notificationStylesInjected = true;

    var style = document.createElement('style');
    style.textContent =
        '@keyframes slideIn{from{transform:translateX(400px);opacity:0}to{transform:translateX(0);opacity:1}}' +
        '@keyframes slideOut{from{transform:translateX(0);opacity:1}to{transform:translateX(400px);opacity:0}}';
    document.head.appendChild(style);
}

// Show notification message. `message` is treated as plain text, never markup.
function showNotification(message, type) {
    type = type === 'error' ? 'error' : 'success';
    injectNotificationStyles();

    var notification = document.createElement('div');
    notification.className = 'notification notification-' + type;

    var box = document.createElement('div');
    box.setAttribute('role', type === 'error' ? 'alert' : 'status');
    box.style.cssText = [
        'position:fixed',
        'top:20px',
        'right:20px',
        'background:' + (type === 'success' ? '#4CAF50' : '#f44336'),
        'color:white',
        'padding:1rem 1.5rem',
        'border-radius:8px',
        'box-shadow:0 4px 12px rgba(0,0,0,0.15)',
        'z-index:10000',
        'max-width:400px',
        'animation:slideIn 0.3s ease'
    ].join(';');

    var heading = document.createElement('strong');
    heading.textContent = type === 'success' ? 'Success!' : 'Error!';
    box.appendChild(heading);
    box.appendChild(document.createElement('br'));
    box.appendChild(document.createTextNode(String(message)));

    notification.appendChild(box);
    document.body.appendChild(notification);

    setTimeout(function () {
        box.style.animation = 'slideOut 0.3s ease';
        setTimeout(function () {
            notification.remove();
        }, 300);
    }, 5000);

    return notification;
}

// ===================================
// LEGACY FADE-IN ON SCROLL
// ===================================
var legacyAnimationObserver = new IntersectionObserver(function (entries) {
    entries.forEach(function (entry) {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
            legacyAnimationObserver.unobserve(entry.target);
        }
    });
}, {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
});

window.addEventListener('load', function () {
    if (prefersReducedMotion()) {
        return;
    }

    document.querySelectorAll('.service-card, .gallery-item, .contact-item, .testimonial-card').forEach(function (el) {
        // Only apply if element doesn't already use a reveal class
        if (!el.classList.contains('reveal') &&
            !el.classList.contains('reveal-left') &&
            !el.classList.contains('reveal-right') &&
            !el.classList.contains('reveal-scale')) {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            legacyAnimationObserver.observe(el);
        }
    });
});

// ===================================
// STAT COUNTER ANIMATION
// ===================================
function animateStatCounter(statItem) {
    var numberElement = statItem.querySelector('.stat-number');
    if (!numberElement || numberElement.dataset.animated) {
        return;
    }

    var target = parseInt(numberElement.dataset.target, 10);
    if (isNaN(target)) {
        return;
    }

    var finalText = target.toLocaleString() + (target >= 1000 ? '+' : '');

    // No timers when the visitor has asked for reduced motion.
    if (prefersReducedMotion()) {
        numberElement.textContent = finalText;
        numberElement.dataset.animated = 'true';
        return;
    }

    var duration = 2000;
    var steps = 60;
    var increment = target / steps;
    var current = 0;
    var step = 0;

    var timer = setInterval(function () {
        step++;
        current = Math.min(current + increment, target);

        if (step >= steps || current >= target) {
            numberElement.textContent = finalText;
            clearInterval(timer);
            numberElement.dataset.animated = 'true';
        } else {
            numberElement.textContent = Math.floor(current).toLocaleString();
        }
    }, duration / steps);
}

function initStatCounters() {
    var statItems = document.querySelectorAll('.stat-item');
    if (statItems.length === 0) {
        return;
    }

    var statObserver = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
                animateStatCounter(entry.target);
                statObserver.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.5
    });

    statItems.forEach(function (item) {
        statObserver.observe(item);
    });
}

document.addEventListener('DOMContentLoaded', initStatCounters);

// ===================================
// TESTIMONIALS CAROUSEL
// ===================================
var currentTestimonialIndex = 0;
var testimonialAutoPlay = null;
var testimonialInteracted = false;

function setTestimonial(newIndex) {
    var testimonials = document.querySelectorAll('.testimonial-card');
    var dots = document.querySelectorAll('.testimonial-dots .dot');

    if (testimonials.length === 0) {
        return;
    }

    if (newIndex >= testimonials.length) {
        newIndex = 0;
    } else if (newIndex < 0) {
        newIndex = testimonials.length - 1;
    }

    if (testimonials[currentTestimonialIndex]) {
        testimonials[currentTestimonialIndex].classList.remove('active');
    }
    if (dots[currentTestimonialIndex]) {
        dots[currentTestimonialIndex].classList.remove('active');
    }

    currentTestimonialIndex = newIndex;

    testimonials[currentTestimonialIndex].classList.add('active');
    if (dots[currentTestimonialIndex]) {
        dots[currentTestimonialIndex].classList.add('active');
    }
}

function stopTestimonialAutoPlay() {
    testimonialInteracted = true;
    if (testimonialAutoPlay !== null) {
        clearInterval(testimonialAutoPlay);
        testimonialAutoPlay = null;
    }
}

function startTestimonialAutoPlay() {
    if (testimonialInteracted || prefersReducedMotion() || testimonialAutoPlay !== null) {
        return;
    }
    if (document.querySelectorAll('.testimonial-card').length < 2) {
        return;
    }
    testimonialAutoPlay = setInterval(function () {
        setTestimonial(currentTestimonialIndex + 1);
    }, 5000);
}

// Global — called from inline onclick in index.html
function moveTestimonial(direction) {
    stopTestimonialAutoPlay();
    setTestimonial(currentTestimonialIndex + direction);
}

// Global — called from inline onclick in index.html
function currentTestimonial(index) {
    stopTestimonialAutoPlay();
    setTestimonial(index);
}

document.addEventListener('DOMContentLoaded', function () {
    var carousel = document.querySelector('.testimonials-carousel');
    if (!carousel) {
        return;
    }

    startTestimonialAutoPlay();

    carousel.addEventListener('mouseenter', function () {
        if (testimonialAutoPlay !== null) {
            clearInterval(testimonialAutoPlay);
            testimonialAutoPlay = null;
        }
    });

    carousel.addEventListener('mouseleave', function () {
        startTestimonialAutoPlay();
    });
});

// ===================================
// GALLERY LIGHTBOX
// ===================================
// Global — called from inline onclick in index.html
function openGalleryLightbox(category) {
    var lightbox = document.getElementById('gallery-lightbox');
    if (lightbox) {
        lightbox.dataset.category = category || '';
        lightbox.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

// Global — called from inline onclick in index.html
function closeGalleryLightbox() {
    var lightbox = document.getElementById('gallery-lightbox');
    if (lightbox) {
        lightbox.classList.remove('active');
        document.body.style.overflow = '';
    }
}

document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
        closeGalleryLightbox();
    }
});

document.addEventListener('DOMContentLoaded', function () {
    var lightbox = document.getElementById('gallery-lightbox');
    if (lightbox) {
        lightbox.addEventListener('click', function (e) {
            if (e.target === lightbox) {
                closeGalleryLightbox();
            }
        });
    }
});

// ===================================
// HERO SLIDER
// ===================================
var currentSlideIndex = 0;
var sliderAutoPlay = null;
var sliderInteracted = false;
var SLIDER_INTERVAL_MS = 8000;

function setSlide(newIndex) {
    var slides = document.querySelectorAll('.hero-slide');
    var indicators = document.querySelectorAll('.slider-indicators .indicator');

    if (slides.length === 0) {
        return;
    }

    if (newIndex >= slides.length) {
        newIndex = 0;
    } else if (newIndex < 0) {
        newIndex = slides.length - 1;
    }

    if (slides[currentSlideIndex]) {
        slides[currentSlideIndex].classList.remove('active');
    }
    if (indicators[currentSlideIndex]) {
        indicators[currentSlideIndex].classList.remove('active');
    }

    currentSlideIndex = newIndex;

    slides[currentSlideIndex].classList.add('active');
    if (indicators[currentSlideIndex]) {
        indicators[currentSlideIndex].classList.add('active');
    }
}

function startSliderAutoPlay() {
    if (sliderInteracted || prefersReducedMotion() || sliderAutoPlay !== null) {
        return;
    }
    if (document.querySelectorAll('.hero-slide').length < 2) {
        return;
    }
    sliderAutoPlay = setInterval(function () {
        setSlide(currentSlideIndex + 1);
    }, SLIDER_INTERVAL_MS);
}

function pauseSliderAutoPlay() {
    if (sliderAutoPlay !== null) {
        clearInterval(sliderAutoPlay);
        sliderAutoPlay = null;
    }
}

// Once the visitor drives the slider themselves, autoplay never comes back.
function stopSliderAutoPlay() {
    sliderInteracted = true;
    pauseSliderAutoPlay();
}

// Global — called from inline onclick in index.html
function changeSlide(direction) {
    stopSliderAutoPlay();
    setSlide(currentSlideIndex + direction);
}

// Global — called from inline onclick in index.html
function goToSlide(index) {
    var slides = document.querySelectorAll('.hero-slide');
    if (slides.length === 0 || index < 0 || index >= slides.length) {
        return;
    }
    stopSliderAutoPlay();
    setSlide(index);
}

document.addEventListener('DOMContentLoaded', function () {
    var heroSlider = document.querySelector('.hero-slider');
    if (!heroSlider) {
        return;
    }

    startSliderAutoPlay();

    heroSlider.addEventListener('mouseenter', pauseSliderAutoPlay);
    heroSlider.addEventListener('mouseleave', startSliderAutoPlay);

    // Keyboard navigation — must never steal arrow keys from a text field.
    document.addEventListener('keydown', function (e) {
        if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') {
            return;
        }

        var target = e.target;
        if (target && typeof target.closest === 'function' &&
            target.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')) {
            return;
        }

        changeSlide(e.key === 'ArrowLeft' ? -1 : 1);
    });

    // Touch/swipe support
    var touchStartX = 0;

    heroSlider.addEventListener('touchstart', function (e) {
        touchStartX = e.changedTouches[0].screenX;
    }, { passive: true });

    heroSlider.addEventListener('touchend', function (e) {
        var touchEndX = e.changedTouches[0].screenX;
        if (touchEndX < touchStartX - 50) {
            changeSlide(1);
        } else if (touchEndX > touchStartX + 50) {
            changeSlide(-1);
        }
    }, { passive: true });
});

// ===================================
// HERO SCROLL INDICATOR
// ===================================
document.addEventListener('DOMContentLoaded', function () {
    var scrollIndicator = document.querySelector('.hero-scroll-indicator');
    if (scrollIndicator) {
        scrollIndicator.addEventListener('click', function () {
            var nextSection = document.querySelector('.stats-section, .about');
            if (nextSection) {
                nextSection.scrollIntoView({ behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
            }
        });
    }
});

// ===================================
// SMOOTH SCROLL TO TOP
// ===================================
// Global — available to inline onclick handlers
function scrollToTop() {
    window.scrollTo({
        top: 0,
        behavior: prefersReducedMotion() ? 'auto' : 'smooth'
    });
}

// ===================================
// LAZY LOADING IMAGES
// ===================================
document.addEventListener('DOMContentLoaded', function () {
    var lazyImages = document.querySelectorAll('img[data-src]');
    if (lazyImages.length === 0) {
        return;
    }

    var imageObserver = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
                var img = entry.target;
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
                imageObserver.unobserve(img);
            }
        });
    });

    lazyImages.forEach(function (img) {
        imageObserver.observe(img);
    });
});

// ===================================
// ACCESSIBILITY: KEYBOARD NAVIGATION
// ===================================
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.service-card, .gallery-item, .stat-item').forEach(function (element) {
        element.setAttribute('tabindex', '0');

        element.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                element.click();
            }
        });
    });
});

// ===================================
// PRINT CURRENT YEAR IN FOOTER
// ===================================
document.addEventListener('DOMContentLoaded', function () {
    var yearElement = document.querySelector('.current-year');
    if (yearElement) {
        yearElement.textContent = new Date().getFullYear();
    }
});

// ===================================
// GLOBAL EXPORTS
// ===================================
// Vite bundles this file as an ES module, which scopes every top-level
// `function`/`var` declaration to the module instead of `window`. The inline
// `onclick="..."` attributes still baked into the ported markup (and the
// inline contact-page script) reference these by name, so they must be
// attached to `window` explicitly.
window.changeSlide = changeSlide;
window.goToSlide = goToSlide;
window.moveTestimonial = moveTestimonial;
window.currentTestimonial = currentTestimonial;
window.openGalleryLightbox = openGalleryLightbox;
window.closeGalleryLightbox = closeGalleryLightbox;
window.scrollToTop = scrollToTop;
window.showNotification = showNotification;
