/**
 * Frontend JavaScript for Coming Soon Pro
 * Handles menu toggle and countdown functionality
 */

document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    // ========================
    // MENU TOGGLE FUNCTIONALITY
    // ========================
    const menuToggle = document.querySelector('.mdxcsp-menu-toggle');
    const menu = document.getElementById('mdxcsp-dropdown-menu');

    if (menuToggle && menu) {
        // Ensure menu starts closed
        menu.setAttribute('aria-hidden', 'true');
        menuToggle.setAttribute('aria-expanded', 'false');

        const openMenu = () => {
            menu.classList.add('is-open');
            menu.setAttribute('aria-hidden', 'false');
            menuToggle.setAttribute('aria-expanded', 'true');
        };

        const closeMenu = () => {
            menu.classList.remove('is-open');
            menu.setAttribute('aria-hidden', 'true');
            menuToggle.setAttribute('aria-expanded', 'false');
        };

        const toggleMenu = () => {
            const isHidden = menu.getAttribute('aria-hidden') === 'true';
            if (isHidden) {
                openMenu();
            } else {
                closeMenu();
            }
        };

        // Toggle on click (works for clicks on the image or text inside)
        menuToggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            toggleMenu();
        });

        // Close on outside click (treat clicks on the toggle OR its children as inside)
        document.addEventListener('click', function(e) {
            if (
                menu.getAttribute('aria-hidden') === 'false' &&
                !menu.contains(e.target) &&
                !menuToggle.contains(e.target)
            ) {
                closeMenu();
            }
        });

        // Close on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && menu.getAttribute('aria-hidden') === 'false') {
                closeMenu();
                menuToggle.focus();
            }
        });
    }

    // ========================
    // COUNTDOWN FUNCTIONALITY
    // ========================
    const counters = document.querySelectorAll('.mdxcsp-counter');

    counters.forEach(function(counter) {
        const daysEl = counter.querySelector('.days');
        const hoursEl = counter.querySelector('.hours');
        const minutesEl = counter.querySelector('.minutes');
        const secondsEl = counter.querySelector('.seconds');

        const iso = counter.getAttribute('data-target-date') || '';
        let targetTime = Date.parse(iso);

        // Fallback if date parsing fails
        if (isNaN(targetTime)) {
            targetTime = Date.now() + (10 * 24 * 60 * 60 * 1000); // fallback: +10 days
        }

        const pad = function(n) {
            return String(n).padStart(2, '0');
        };

        const render = function() {
            const now = Date.now();
            let diff = Math.max(0, Math.floor((targetTime - now) / 1000));

            const days = Math.floor(diff / (24 * 3600));
            diff -= days * 24 * 3600;

            const hours = Math.floor(diff / 3600);
            diff -= hours * 3600;

            const minutes = Math.floor(diff / 60);
            const seconds = diff - minutes * 60;

            if (daysEl) daysEl.textContent = pad(days);
            if (hoursEl) hoursEl.textContent = pad(hours);
            if (minutesEl) minutesEl.textContent = pad(minutes);
            if (secondsEl) secondsEl.textContent = pad(seconds);

            if (targetTime - now <= 0) {
                counter.classList.add('mdxcsp-counter-complete');
                return false;
            }
            return true;
        };

        let running = render();

        if (running) {
            let timer;
            const tick = function() {
                running = render();
                if (running) {
                    const delay = 1000 - (Date.now() % 1000) + 10;
                    timer = setTimeout(tick, delay);
                }
            };
            timer = setTimeout(tick, 1000);

            // Clean up timers when page unloads
            window.addEventListener('beforeunload', function() {
                if (timer) {
                    clearTimeout(timer);
                }
            });

            // Optimize for background tabs
            document.addEventListener('visibilitychange', function() {
                if (!document.hidden) {
                    render();
                }
            });
        }
    });

    // ========================
    // ADDITIONAL ENHANCEMENTS
    // ========================

    // Smooth scrolling for anchor links
    document.addEventListener('click', function(e) {
        const link = e.target.closest('a[href^="#"]');
        if (link && link.getAttribute('href') !== '#') {
            e.preventDefault();
            const target = document.querySelector(link.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        }
    });

    // Add loading state to social links
    const socialLinks = document.querySelectorAll('.mdxcsp-footer-right a, .social');
    socialLinks.forEach(function(link) {
        link.addEventListener('click', function(e) {
            if (this.getAttribute('href') && this.getAttribute('href') !== '#') {
                this.classList.add('mdxcsp-loading');
                setTimeout(() => {
                    this.classList.remove('mdxcsp-loading');
                }, 2000);
            }
        });
    });
});