/* ============================================ */
/* SASTHO KANON - COMPLETE JAVASCRIPT */
/* ============================================ */

// ============================================ */
// 1. AOS ANIMATION INITIALIZATION
// ============================================ */
AOS.init({
    duration: 800,
    once: true,
    easing: 'ease-in-out',
    offset: 80
});

// ============================================ */
// 2. NAVBAR SCROLL EFFECT
// ============================================ */
$(window).scroll(function() {
    // Add shadow on scroll
    $('#navbar').toggleClass('scrolled', $(this).scrollTop() > 50);
    
    // Active nav link based on scroll position
    $('section').each(function() {
        if ($(window).scrollTop() + 100 >= $(this).offset().top) {
            $('.nav-link').removeClass('active');
            $('.nav-link[href="#' + $(this).attr('id') + '"]').addClass('active');
        }
    });
});

// ============================================ */
// 3. SMOOTH SCROLL
// ============================================ */
$('a[href^="#"]').click(function(e) {
    e.preventDefault();
    var target = $(this.getAttribute('href'));
    if (target.length) {
        $('html, body').animate({
            scrollTop: target.offset().top - 70
        }, 800);
    }
});

// Close mobile menu on link click
$('.navbar-nav a, .login-nav a').click(function() {
    $('.navbar-collapse').collapse('hide');
});

// ============================================ */
// 4. CONTACT FORM SUBMISSION
// ============================================ */
$('#leadForm').on('submit', function(e) {
    e.preventDefault();
    
    var form = $(this);
    var btn = form.find('button[type="submit"]');
    var originalText = btn.html();
    var resultDiv = $('#leadResult');
    
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Sending...');
    resultDiv.html('');
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: form.serialize() + '&ajax=lead',
        dataType: 'json',
        timeout: 10000,
        success: function(response) {
            if (response.success) {
                resultDiv.html(
                    '<div class="alert alert-success alert-dismissible fade show">' +
                    '<i class="fas fa-check-circle"></i> ✅ Submitted successfully!' +
                    '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
                    '</div>'
                );
                form[0].reset();
                setTimeout(function() {
                    resultDiv.find('.alert').fadeOut(500);
                }, 5000);
            }
        },
        error: function() {},
        complete: function() {
            btn.prop('disabled', false).html(originalText);
        }
    });
});

// ============================================ */
// 5. PHONE NUMBER VALIDATION
// ============================================ */
$('input[name="phone"]').on('input', function() {
    var phone = $(this).val();
    if (phone.length > 0 && !/^01[3-9][0-9]{8}$/.test(phone)) {
        $(this).addClass('is-invalid');
    } else {
        $(this).removeClass('is-invalid');
    }
});

// ============================================ */
// 6. BACK TO TOP BUTTON
// ============================================ */
function initBackToTop() {
    if ($('#backToTop').length === 0) {
        $('body').append(
            '<a href="#" id="backToTop" style="display:none;position:fixed;bottom:100px;left:25px;width:40px;height:40px;' +
            'background:#2d6a4f;color:#fff;border-radius:50%;text-align:center;line-height:40px;z-index:998;' +
            'box-shadow:0 3px 15px rgba(0,0,0,.2);text-decoration:none;transition:all .3s">' +
            '<i class="fas fa-arrow-up"></i></a>'
        );
    }
}

initBackToTop();

$(window).scroll(function() {
    if ($(this).scrollTop() > 500) {
        $('#backToTop').fadeIn(300);
    } else {
        $('#backToTop').fadeOut(300);
    }
});

$('#backToTop').click(function(e) {
    e.preventDefault();
    $('html, body').animate({ scrollTop: 0 }, 600);
});

// ============================================ */
// 7. SHARE BUTTON FUNCTIONALITY
// ============================================ */
function toggleShareMenu(btn) {
    // Close all other open menus
    document.querySelectorAll('.share-menu.show').forEach(function(menu) {
        if (menu !== btn.nextElementSibling) {
            menu.classList.remove('show');
        }
    });
    // Toggle current menu
    btn.nextElementSibling.classList.toggle('show');
}

function copyShareLink(url, el) {
    var text = decodeURIComponent(url);
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(function() {
            var icon = el.querySelector('i');
            if (icon) {
                var originalClass = icon.className;
                icon.className = 'fas fa-check';
                setTimeout(function() {
                    icon.className = originalClass;
                }, 1500);
            }
        }).catch(function() {
            alert('Link: ' + text);
        });
    } else {
        // Fallback
        var input = document.createElement('input');
        input.value = text;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        alert('Link copied!');
    }
}

// Close share menu when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('.share-wrap')) {
        document.querySelectorAll('.share-menu.show').forEach(function(menu) {
            menu.classList.remove('show');
        });
    }
});

// ============================================ */
// 8. PAYMENT METHOD SELECTION
// ============================================ */
function selectPay(el) {
    document.querySelectorAll('.pay-opt').forEach(function(p) {
        p.classList.remove('selected');
    });
    el.classList.add('selected');
    var radio = el.querySelector('input[type="radio"]');
    if (radio) radio.checked = true;
}

// ============================================ */
// 9. AD BANNER HANDLING
// ============================================ */
function updateBannerOffset() {
    var banner = document.getElementById('adBanner');
    if (banner && banner.style.display === 'none') {
        var loginNav = document.querySelector('.navbar-login');
        var heroSection = document.querySelector('.hero-section');
        if (loginNav) loginNav.style.top = '62px';
        if (heroSection) heroSection.style.paddingTop = '200px';
    }
}

// ============================================ */
// 10. DELIVERY CHARGE CALCULATION
// ============================================ */
var deliveryCharges = {};

function updateDelivery(subtotal) {
    var areaSelect = document.getElementById('areaSelect');
    if (!areaSelect) return;
    
    var area = areaSelect.value;
    var fee = deliveryCharges[area] || 110;
    if (subtotal >= 1000) fee = 0;
    
    var feeDisplay = document.getElementById('displayFee');
    var totalDisplay = document.getElementById('displayTotal');
    
    if (feeDisplay) feeDisplay.textContent = '৳' + fee;
    if (totalDisplay) totalDisplay.textContent = '৳' + (subtotal + fee).toLocaleString();
}

// ============================================ */
// 11. CARD HOVER EFFECTS
// ============================================ */
$(document).on('mouseenter', '.doctor-card', function() {
    $(this).find('.doctor-img').css('transform', 'scale(1.05)');
}).on('mouseleave', '.doctor-card', function() {
    $(this).find('.doctor-img').css('transform', 'scale(1)');
});

$(document).on('mouseenter', '.service-card', function() {
    $(this).find('.service-icon').css('transform', 'scale(1.2) rotate(10deg)');
}).on('mouseleave', '.service-card', function() {
    $(this).find('.service-icon').css('transform', 'scale(1) rotate(0deg)');
});

$(document).on('mouseenter', '.product-card', function() {
    $(this).find('.product-img').css('transform', 'scale(1.05)');
}).on('mouseleave', '.product-card', function() {
    $(this).find('.product-img').css('transform', 'scale(1)');
});

// ============================================ */
// 12. WHATSAPP CLICK TRACKING
// ============================================ */
$(document).on('click', 'a[href*="wa.me"]', function() {
    console.log('WhatsApp link clicked: ' + $(this).attr('href'));
});

// ============================================ */
// 13. LAZY LOAD IMAGES
// ============================================ */
$('img[data-src]').each(function() {
    var img = $(this);
    img.attr('src', img.data('src'));
    img.removeAttr('data-src');
});

// ============================================ */
// 14. CART COUNT UPDATE
// ============================================ */
function updateCartCount() {
    if (typeof $.get === 'function') {
        $.get('cart_count.php', function(data) {
            var cartBadge = document.getElementById('cartCount');
            if (cartBadge && data.count !== undefined) {
                cartBadge.textContent = data.count || 0;
            }
        });
    }
}

// ============================================ */
// 15. ORDER EDIT MODAL (for admin orders.php)
// ============================================ */
var orderData = {};

function openEditModal(orderId) {
    var data = orderData[orderId];
    if (!data) return;
    
    var editOrderId = document.getElementById('editOrderId');
    var editOrderInfo = document.getElementById('editOrderInfo');
    var statusSelect = document.getElementById('statusSelect');
    var trackingSection = document.getElementById('trackingSection');
    var trackingInput = document.querySelector('#editModal input[name="tracking_id"]');
    
    if (editOrderId) editOrderId.value = orderId;
    if (editOrderInfo) {
        editOrderInfo.innerHTML = 
            '<strong>Order:</strong> #' + data.order_number + '<br>' +
            '<strong>Customer:</strong> ' + data.customer_name + '<br>' +
            '<strong>Phone:</strong> ' + data.customer_phone + '<br>' +
            '<strong>Status:</strong> ' + data.status + '<br>' +
            '<strong>Courier:</strong> ' + (data.courier || 'N/A') + '<br>' +
            '<strong>Tracking:</strong> ' + (data.tracking_id || 'Not set');
    }
    
    if (statusSelect) statusSelect.value = '';
    if (trackingSection) trackingSection.style.display = 'none';
    if (trackingInput) trackingInput.value = '';
    
    var modalEl = document.getElementById('editModal');
    if (modalEl) {
        var modal = new bootstrap.Modal(modalEl);
        modal.show();
    }
}

function toggleTracking() {
    var statusSelect = document.getElementById('statusSelect');
    var trackingSection = document.getElementById('trackingSection');
    if (statusSelect && trackingSection) {
        trackingSection.style.display = (statusSelect.value === 'shipped') ? 'block' : 'none';
    }
}

// ============================================ */
// 16. SCROLL TO PRODUCT ON SHARED LINK
// ============================================ */
function scrollToProducts() {
    if (window.location.search.indexOf('product_id') !== -1) {
        setTimeout(function() {
            var products = document.getElementById('products');
            if (products) {
                products.scrollIntoView({ behavior: 'smooth' });
            }
        }, 500);
    }
}

// ============================================ */
// 17. MOBILE NAVBAR TOGGLE FIX
// ============================================ */
$(document).ready(function() {
    // Force Bootstrap collapse to work on mobile
    $('.navbar-toggler').on('click', function() {
        var target = $($(this).data('bs-target'));
        if (target.length) {
            target.toggleClass('show');
        }
    });
    
    // Close menu when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.navbar').length) {
            $('.navbar-collapse').removeClass('show');
        }
    });
});

// ============================================ */
// 18. PAGE LOADED
// ============================================ */
$(window).on('load', function() {
    console.log('🏥 Homoeopathy Sastho Kanon - Ready');
    
    // Refresh AOS
    setTimeout(function() {
        AOS.refresh();
    }, 500);
    
    // Update cart count
    updateCartCount();
    
    // Scroll to products if shared link
    scrollToProducts();
    
    // Initialize back to top
    initBackToTop();
});
// =========================================================
// SMOOTH SCROLL WITH EASING
// =========================================================
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            const offsetTop = target.offsetTop - 100;
            window.scrollTo({
                top: offsetTop,
                behavior: 'smooth'
            });
        }
    });
});

// =========================================================
// LAZY LOAD IMAGES WITH BLUR-UP
// =========================================================
document.addEventListener('DOMContentLoaded', function() {
    const lazyImages = document.querySelectorAll('img[data-src]');
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.add('loaded');
                    observer.unobserve(img);
                }
            });
        });
        lazyImages.forEach(img => imageObserver.observe(img));
    }
});

// =========================================================
// SMOOTH NAVBAR HIDE/SHOW
// =========================================================
let lastScrollTop = 0;
let navbarTimeout;
window.addEventListener('scroll', function() {
    const navbar = document.getElementById('navbar');
    if (!navbar) return;
    
    clearTimeout(navbarTimeout);
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    
    if (scrollTop > 100) {
        if (scrollTop > lastScrollTop) {
            // Scrolling down - hide navbar
            navbar.style.transform = 'translateY(-100%)';
            navbar.style.transition = 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
        } else {
            // Scrolling up - show navbar
            navbar.style.transform = 'translateY(0)';
        }
    } else {
        navbar.style.transform = 'translateY(0)';
    }
    lastScrollTop = scrollTop;
}, { passive: true });

// =========================================================
// SMOOTH CARD ENTRY ANIMATION (Intersection Observer)
// =========================================================
const animateElements = document.querySelectorAll('.animate-on-scroll');
if ('IntersectionObserver' in window) {
    const animateObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animated');
                animateObserver.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });
    animateElements.forEach(el => animateObserver.observe(el));
}

// =========================================================
// SMOOTH COUNTER ANIMATION
// =========================================================
function animateCounters() {
    document.querySelectorAll('.stat-number[data-count]').forEach(counter => {
        const target = parseInt(counter.getAttribute('data-count'));
        const duration = 2000;
        const startTime = performance.now();
        
        function updateCounter(currentTime) {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3); // Cubic ease-out
            const current = Math.floor(eased * target);
            counter.textContent = current;
            if (progress < 1) {
                requestAnimationFrame(updateCounter);
            } else {
                counter.textContent = target;
            }
        }
        requestAnimationFrame(updateCounter);
    });
}

// =========================================================
// SMOOTH TOAST NOTIFICATIONS (with slide in/out)
// =========================================================
function showToast(message, type = 'success', duration = 3000) {
    const container = document.getElementById('toastContainer') || (() => {
        const c = document.createElement('div');
        c.id = 'toastContainer';
        c.style.cssText = 'position:fixed;bottom:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:10px;max-width:400px;width:100%;';
        document.body.appendChild(c);
        return c;
    })();
    
    const toast = document.createElement('div');
    const colors = {
        success: '#28a745',
        error: '#dc3545',
        warning: '#ffc107',
        info: '#17a2b8'
    };
    toast.style.cssText = `
        background: white;
        border-radius: 12px;
        padding: 15px 20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        border-left: 4px solid ${colors[type] || colors.success};
        display: flex;
        align-items: center;
        gap: 12px;
        animation: slideInRight 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
        transform: translateX(120%);
        opacity: 0;
        font-family: 'Hind Siliguri', sans-serif;
    `;
    
    const icon = type === 'success' ? '✅' : type === 'error' ? '❌' : '⚠️';
    toast.innerHTML = `
        <span style="font-size:1.2rem;">${icon}</span>
        <span style="flex:1;font-size:0.95rem;">${message}</span>
        <button onclick="this.parentElement.remove()" style="background:none;border:none;font-size:1.2rem;cursor:pointer;color:#999;">&times;</button>
    `;
    container.appendChild(toast);
    
    // Trigger animation
    requestAnimationFrame(() => {
        toast.style.transform = 'translateX(0)';
        toast.style.opacity = '1';
    });
    
    // Auto remove
    setTimeout(() => {
        toast.style.transform = 'translateX(120%)';
        toast.style.opacity = '0';
        toast.style.transition = 'all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
        setTimeout(() => toast.remove(), 500);
    }, duration);
}

// Add keyframes for toast animation
const styleSheet = document.createElement('style');
styleSheet.textContent = `
    @keyframes slideInRight {
        from { transform: translateX(120%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
`;
document.head.appendChild(styleSheet);