/**
 * Metro Zoo Template - Custom JavaScript
 * Version: 1.0.0
 *
 * Template-specific interactivity and enhancements
 */

(function() {
    'use strict';

    // =========================================================================
    // ANNOUNCEMENT BAR
    // =========================================================================

    /**
     * Initialize announcement bar with dismiss functionality
     */
    function initAnnouncementBar() {
        const bar = document.querySelector('.zoo-announcement-bar');
        if (!bar) return;

        // Add dismiss button if it doesn't exist
        if (!bar.querySelector('.zoo-announcement-dismiss')) {
            const dismissBtn = document.createElement('button');
            dismissBtn.className = 'zoo-announcement-dismiss';
            dismissBtn.setAttribute('aria-label', 'Dismiss announcement');
            dismissBtn.innerHTML = '<i class="fas fa-times"></i>';
            bar.querySelector('.container').appendChild(dismissBtn);

            dismissBtn.addEventListener('click', function() {
                bar.style.maxHeight = bar.offsetHeight + 'px';
                bar.offsetHeight; // Force reflow
                bar.style.maxHeight = '0';
                bar.style.padding = '0';
                bar.style.overflow = 'hidden';
                bar.style.transition = 'all 0.3s ease';

                setTimeout(function() {
                    bar.remove();
                }, 300);

                // Remember dismissal for this session
                sessionStorage.setItem('zoo-announcement-dismissed', 'true');
            });
        }

        // Check if already dismissed this session
        if (sessionStorage.getItem('zoo-announcement-dismissed') === 'true') {
            bar.remove();
        }
    }

    // =========================================================================
    // SCROLL EFFECTS
    // =========================================================================

    /**
     * Add scroll-based navbar styling
     */
    function initScrollEffects() {
        const navbar = document.querySelector('.zoo-navbar');
        if (!navbar) return;

        let lastScroll = 0;
        const scrollThreshold = 100;

        function handleScroll() {
            const currentScroll = window.pageYOffset;

            // Add/remove scrolled class for styling
            if (currentScroll > scrollThreshold) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }

            lastScroll = currentScroll;
        }

        // Throttle scroll handler for performance
        let ticking = false;
        window.addEventListener('scroll', function() {
            if (!ticking) {
                window.requestAnimationFrame(function() {
                    handleScroll();
                    ticking = false;
                });
                ticking = true;
            }
        }, { passive: true });

        // Initial check
        handleScroll();
    }

    // =========================================================================
    // SMOOTH SCROLL
    // =========================================================================

    /**
     * Enable smooth scrolling for anchor links
     */
    function initSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
            anchor.addEventListener('click', function(e) {
                const targetId = this.getAttribute('href');

                // Skip if it's just "#" or if target doesn't exist
                if (targetId === '#' || targetId.length <= 1) return;

                const target = document.querySelector(targetId);
                if (!target) return;

                e.preventDefault();

                // Calculate offset for sticky navbar
                const navbar = document.querySelector('.zoo-navbar');
                const navbarHeight = navbar ? navbar.offsetHeight : 0;
                const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navbarHeight - 20;

                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });

                // Update URL without jumping
                history.pushState(null, '', targetId);

                // Focus target for accessibility
                target.setAttribute('tabindex', '-1');
                target.focus({ preventScroll: true });
            });
        });
    }

    // =========================================================================
    // ANIMATE ON SCROLL
    // =========================================================================

    /**
     * Simple animate-on-scroll implementation
     */
    function initAnimateOnScroll() {
        // Check for reduced motion preference
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            return;
        }

        const animatedElements = document.querySelectorAll(
            '.zoo-animal-card, .zoo-event-card, .zoo-quick-link-card, .zoo-stat'
        );

        if (!animatedElements.length) return;

        // Add initial state
        animatedElements.forEach(function(el) {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        });

        const observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        });

        animatedElements.forEach(function(el) {
            observer.observe(el);
        });
    }

    // =========================================================================
    // NEWSLETTER FORM
    // =========================================================================

    /**
     * Handle newsletter form submission
     */
    function initNewsletterForm() {
        const form = document.querySelector('.zoo-newsletter-form');
        if (!form) return;

        form.addEventListener('submit', function(e) {
            e.preventDefault();

            const email = form.querySelector('input[type="email"]').value;
            const button = form.querySelector('button[type="submit"]');
            const originalText = button.innerHTML;

            // Simulate submission (replace with actual API call)
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Subscribing...';

            setTimeout(function() {
                button.innerHTML = '<i class="fas fa-check"></i> Subscribed!';
                button.classList.add('success');
                form.querySelector('input[type="email"]').value = '';

                // Reset button after delay
                setTimeout(function() {
                    button.disabled = false;
                    button.innerHTML = originalText;
                    button.classList.remove('success');
                }, 3000);
            }, 1500);
        });
    }

    // =========================================================================
    // SCHEDULE HIGHLIGHTING
    // =========================================================================

    /**
     * Highlight current/upcoming schedule items based on time
     */
    function initScheduleHighlight() {
        const scheduleItems = document.querySelectorAll('.zoo-schedule-item');
        if (!scheduleItems.length) return;

        const now = new Date();
        const currentHours = now.getHours();
        const currentMinutes = now.getMinutes();
        const currentTotalMinutes = currentHours * 60 + currentMinutes;

        let nextEventFound = false;

        scheduleItems.forEach(function(item) {
            const timeEl = item.querySelector('.time');
            if (!timeEl) return;

            // Parse time (e.g., "10:00 AM")
            const timeText = timeEl.textContent.trim();
            const match = timeText.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);

            if (!match) return;

            let hours = parseInt(match[1], 10);
            const minutes = parseInt(match[2], 10);
            const period = match[3].toUpperCase();

            // Convert to 24-hour format
            if (period === 'PM' && hours !== 12) {
                hours += 12;
            } else if (period === 'AM' && hours === 12) {
                hours = 0;
            }

            const eventTotalMinutes = hours * 60 + minutes;

            // Mark past events
            if (eventTotalMinutes < currentTotalMinutes - 30) {
                item.classList.add('past');
            }
            // Mark next upcoming event
            else if (!nextEventFound && eventTotalMinutes >= currentTotalMinutes) {
                item.classList.add('upcoming');
                nextEventFound = true;
            }
        });
    }

    // =========================================================================
    // ACCESSIBILITY ENHANCEMENTS
    // =========================================================================

    /**
     * Enhance keyboard navigation and focus management
     */
    function initAccessibilityEnhancements() {
        // Add focus-visible polyfill behavior
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Tab') {
                document.body.classList.add('keyboard-nav');
            }
        });

        document.addEventListener('mousedown', function() {
            document.body.classList.remove('keyboard-nav');
        });

        // Ensure all interactive elements are properly focusable
        document.querySelectorAll('.zoo-quick-link-card, .zoo-animal-link').forEach(function(el) {
            if (!el.getAttribute('tabindex')) {
                el.setAttribute('tabindex', '0');
            }
        });
    }

    // =========================================================================
    // INITIALIZATION
    // =========================================================================

    /**
     * Initialize all template functionality
     */
    function init() {
        initAnnouncementBar();
        initScrollEffects();
        initSmoothScroll();
        initAnimateOnScroll();
        initNewsletterForm();
        initScheduleHighlight();
        initAccessibilityEnhancements();
    }

    // Run on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
