// Main JavaScript for Oldage Home

document.addEventListener('DOMContentLoaded', function() {
    const pageTransitionKey = 'oldageHomePageTransition';
    let pageTransitionLayer = document.getElementById('pageTransitionLayer');

    if (!pageTransitionLayer) {
        pageTransitionLayer = document.createElement('div');
        pageTransitionLayer.id = 'pageTransitionLayer';
        pageTransitionLayer.className = 'page-transition-layer';
        pageTransitionLayer.innerHTML = '<div class="page-transition-layer__brand"><span></span><strong>Oldage Home</strong></div>';
        document.body.appendChild(pageTransitionLayer);
    }

    function revealPageTransition() {
        if (!pageTransitionLayer) return;
        if (sessionStorage.getItem(pageTransitionKey) !== 'active') return;
        sessionStorage.removeItem(pageTransitionKey);
        pageTransitionLayer.classList.add('is-active');
        document.body.classList.add('page-is-transitioning');
        window.requestAnimationFrame(function() {
            window.requestAnimationFrame(function() {
                pageTransitionLayer.classList.add('is-revealing');
            });
        });
        window.setTimeout(function() {
            pageTransitionLayer.classList.remove('is-active', 'is-revealing');
            document.body.classList.remove('page-is-transitioning');
        }, 390);
    }

    function shouldAnimateNavigation(link) {
        if (!link) return false;
        const href = link.getAttribute('href');
        if (!href || href.startsWith('#') || href.startsWith('javascript:')) return false;
        if (link.hasAttribute('download') || link.getAttribute('target') === '_blank') return false;
        if (href.startsWith('mailto:') || href.startsWith('tel:')) return false;
        const url = new URL(href, window.location.href);
        if (url.origin !== window.location.origin) return false;
        if (url.pathname === window.location.pathname && url.search === window.location.search && url.hash) return false;
        return /\.(php|html?)$/i.test(url.pathname) || !url.pathname.split('/').pop().includes('.');
    }

    function navigateWithTransition(url) {
        if (!pageTransitionLayer) {
            window.location.href = url;
            return;
        }
        sessionStorage.setItem(pageTransitionKey, 'active');
        document.body.classList.add('page-is-transitioning');
        pageTransitionLayer.classList.remove('is-revealing');
        pageTransitionLayer.classList.add('is-active');
        window.setTimeout(function() {
            window.location.href = url;
        }, 190);
    }

    revealPageTransition();

    document.querySelectorAll('a[href]').forEach(function(link) {
        if (!shouldAnimateNavigation(link)) return;
        link.addEventListener('click', function(e) {
            if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
            const targetUrl = new URL(link.getAttribute('href'), window.location.href);
            e.preventDefault();
            navigateWithTransition(targetUrl.href);
        });
    });
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href && href.startsWith('#')) {
                e.preventDefault();
                const target = document.querySelector(href);
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth' });
                }
            }
        });
    });

    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!form.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    });

    const galleryItems = document.querySelectorAll('.gallery-item img');
    galleryItems.forEach(img => {
        img.addEventListener('click', function() {
            const modal = document.createElement('div');
            modal.style.position = 'fixed';
            modal.style.top = '0';
            modal.style.left = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.backgroundColor = 'rgba(0,0,0,0.8)';
            modal.style.display = 'flex';
            modal.style.alignItems = 'center';
            modal.style.justifyContent = 'center';
            modal.style.zIndex = '9999';
            modal.style.cursor = 'pointer';

            const imgClone = this.cloneNode();
            imgClone.style.maxWidth = '90%';
            imgClone.style.maxHeight = '90%';
            modal.appendChild(imgClone);
            modal.addEventListener('click', function() { document.body.removeChild(modal); });
            document.body.appendChild(modal);
        });
    });

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

    const animateElements = document.querySelectorAll('.card, .facility-item, .staff-card');
    animateElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });

    const testimonials = document.querySelectorAll('.testimonial-card');
    if (testimonials.length > 1) {
        let currentTestimonial = 0;
        setInterval(() => {
            testimonials.forEach((t, index) => {
                t.style.display = index === currentTestimonial ? 'block' : 'none';
            });
            currentTestimonial = (currentTestimonial + 1) % testimonials.length;
        }, 5000);
    }

    const mobileLinks = document.querySelectorAll('[data-app-link]');
    const currentPath = window.location.pathname.split('/').pop() || 'index.php';
    mobileLinks.forEach(link => {
        const target = link.getAttribute('data-app-link');
        if (target === currentPath) {
            link.classList.add('is-active');
        }
    });

    const navbarCollapse = document.getElementById('navbarNav');
    if (navbarCollapse) {
        navbarCollapse.addEventListener('show.bs.collapse', function() {
            document.body.classList.add('nav-menu-open');
        });

        navbarCollapse.addEventListener('hidden.bs.collapse', function() {
            document.body.classList.remove('nav-menu-open');
        });
    }
    const navPanelClose = document.getElementById('navPanelClose');
    const navCollapseLinks = document.querySelectorAll('#navbarNav .nav-link, #navbarNav .dropdown-item');
    navCollapseLinks.forEach(link => {
        link.addEventListener('click', () => {
            if (window.innerWidth < 992 && navbarCollapse && navbarCollapse.classList.contains('show')) {
                const collapse = bootstrap.Collapse.getInstance(navbarCollapse) || new bootstrap.Collapse(navbarCollapse, { toggle: false });
                collapse.hide();
            }
        });
    });


    if (navPanelClose) {
        navPanelClose.addEventListener('click', function() {
            if (navbarCollapse && navbarCollapse.classList.contains('show')) {
                const collapse = bootstrap.Collapse.getInstance(navbarCollapse) || new bootstrap.Collapse(navbarCollapse, { toggle: false });
                collapse.hide();
            }
        });
    }

    document.addEventListener('click', function(e) {
        if (window.innerWidth >= 992 || !navbarCollapse || !navbarCollapse.classList.contains('show')) return;
        const toggler = document.querySelector('.navbar-toggler');
        const clickedInsideMenu = navbarCollapse.contains(e.target);
        const clickedToggler = toggler && toggler.contains(e.target);
        if (!clickedInsideMenu && !clickedToggler) {
            const collapse = bootstrap.Collapse.getInstance(navbarCollapse) || new bootstrap.Collapse(navbarCollapse, { toggle: false });
            collapse.hide();
        }
    });

    const floatingSocials = document.getElementById('floatingSocials');
    const floatingSocialsToggle = document.getElementById('floatingSocialsToggle');
    const floatingSocialsPanel = document.getElementById('floatingSocialsPanel');

    function openFloatingSocials() {
        if (!floatingSocials || !floatingSocialsPanel || !floatingSocialsToggle) return;
        floatingSocials.classList.add('is-open');
        floatingSocialsPanel.setAttribute('aria-hidden', 'false');
        floatingSocialsToggle.setAttribute('aria-expanded', 'true');
    }

    function closeFloatingSocials() {
        if (!floatingSocials || !floatingSocialsPanel || !floatingSocialsToggle) return;
        floatingSocials.classList.remove('is-open');
        floatingSocialsPanel.setAttribute('aria-hidden', 'true');
        floatingSocialsToggle.setAttribute('aria-expanded', 'false');
    }

    if (floatingSocialsToggle) {
        floatingSocialsToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            if (floatingSocials && floatingSocials.classList.contains('is-open')) {
                closeFloatingSocials();
            } else {
                openFloatingSocials();
            }
        });
    }

    if (floatingSocialsPanel) {
        floatingSocialsPanel.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    }

    document.addEventListener('click', function(e) {
        if (!floatingSocials) return;
        if (!floatingSocials.contains(e.target)) {
            closeFloatingSocials();
        }
    });
    const chatbotPrompt = document.getElementById('chatbotPrompt');
    const chatbotPromptClose = document.getElementById('chatbotPromptClose');
    const chatbotPromptAction = document.getElementById('chatbotPromptAction');
    const chatbotToggle = document.getElementById('chatbotToggle');
    const chatbotPanel = document.getElementById('chatbotPanel');
    const chatbotClose = document.getElementById('chatbotClose');
    const chatbotForm = document.getElementById('chatbotForm');
    const chatbotInput = document.getElementById('chatbotInput');
    const chatbotMessages = document.getElementById('chatbotMessages');
    const chatbotSuggestions = document.querySelectorAll('[data-chatbot-question]');

    const chatbotReplies = [
        { keywords: ['service', 'services', 'care'], reply: 'We offer medical care, personal care, nutrition support, recreational activities, transportation, companionship, and more. You can view them on the Services page.' },
        { keywords: ['book', 'booking', 'appointment'], reply: 'To book a service, log in to your account, open Book Services, choose a service, select a date and time, and complete the payment step.' },
        { keywords: ['admission', 'apply', 'resident'], reply: 'You can apply from the Admission page. Fill in the resident and contact details, and our team will review the request and contact you.' },
        { keywords: ['contact', 'phone', 'email', 'address'], reply: 'You can contact Oldage Home at (555) 123-4567, info@oldagehome.com, or from the Contact page form.' },
        { keywords: ['login', 'register', 'account', 'profile'], reply: 'You can register from the Register page, log in from the Login page, and edit your profile after signing in.' },
        { keywords: ['payment', 'card'], reply: 'The website is currently in demo payment mode, so you can use test-looking card details to complete bookings.' }
    ];

    function addChatMessage(text, type) {
        if (!chatbotMessages) return;
        const message = document.createElement('div');
        message.className = 'chatbot-message chatbot-message--' + type;
        message.textContent = text;
        chatbotMessages.appendChild(message);
        chatbotMessages.scrollTop = chatbotMessages.scrollHeight;
    }

    function getChatReply(question) {
        const normalized = question.toLowerCase();
        const match = chatbotReplies.find(item => item.keywords.some(keyword => normalized.includes(keyword)));
        return match ? match.reply : 'I can help with services, booking, admission, contact details, login, and payment questions. Please try asking in a short sentence.';
    }

    function hideChatbotPrompt() {
        if (!chatbotPrompt) return;
        chatbotPrompt.classList.add('is-hidden');
    }
    function openChatbot() {
        if (!chatbotPanel) return;
        chatbotPanel.classList.add('is-open');
        chatbotPanel.setAttribute('aria-hidden', 'false');
        if (chatbotInput) chatbotInput.focus();
    }

    function closeChatbot() {
        if (!chatbotPanel) return;
        chatbotPanel.classList.remove('is-open');
        chatbotPanel.setAttribute('aria-hidden', 'true');
    }

    if (chatbotToggle) {
        chatbotToggle.addEventListener('click', function() {
            if (chatbotPanel && chatbotPanel.classList.contains('is-open')) {
                closeChatbot();
            } else {
                openChatbot();
            }
        });
    }

    if (chatbotPromptClose) {
        chatbotPromptClose.addEventListener('click', function() {
            hideChatbotPrompt();
        });
    }

    if (chatbotPromptAction) {
        chatbotPromptAction.addEventListener('click', function() {
            openChatbot();
        });
    }

    if (chatbotPrompt) {
        window.setTimeout(function() {
            chatbotPrompt.classList.add('is-visible');
        }, 700);
    }
    if (chatbotClose) {
        chatbotClose.addEventListener('click', closeChatbot);
    }

    if (chatbotForm) {
        chatbotForm.addEventListener('submit', function(e) {
            e.preventDefault();
            if (!chatbotInput) return;
            const question = chatbotInput.value.trim();
            if (!question) return;
            addChatMessage(question, 'user');
            chatbotInput.value = '';
            setTimeout(() => { addChatMessage(getChatReply(question), 'bot'); }, 300);
        });
    }

    chatbotSuggestions.forEach(button => {
        button.addEventListener('click', function() {
            const question = this.getAttribute('data-chatbot-question');
            addChatMessage(question, 'user');
            setTimeout(() => { addChatMessage(getChatReply(question), 'bot'); }, 250);
            openChatbot();
        });
    });
});
