// Initialize Owl Carousel and AOS when document is ready
$(document).ready(function() {
    // Initialize AOS (Animate On Scroll)
    AOS.init({
        duration: 800,
        easing: 'ease-in-out',
        once: true,
        offset: 100
    });

    // Initialize Services Carousel
    $('.services-carousel').owlCarousel({
        loop: true,
        margin: 30,
        nav: true,
        dots: true,
        autoplay: true,
        autoplayTimeout: 5000,
        autoplayHoverPause: true,
        smartSpeed: 800,
        responsive: {
            0: {
                items: 1
            },
            768: {
                items: 2
            },
            1024: {
                items: 3
            }
        }
    });

    // Initialize Testimonials Carousel
    $('.testimonials-carousel').owlCarousel({
        loop: true,
        margin: 30,
        nav: false,
        dots: true,
        autoplay: true,
        autoplayTimeout: 6000,
        autoplayHoverPause: true,
        smartSpeed: 800,
        responsive: {
            0: {
                items: 1
            },
            768: {
                items: 2
            },
            1024: {
                items: 3
            }
        }
    });

    // Progress Bar Animation
    function animateProgressBars() {
        const progressBars = document.querySelectorAll('.progress-bar-fill');
        
        progressBars.forEach(bar => {
            const progress = bar.getAttribute('data-progress');
            bar.style.setProperty('--progress-width', progress + '%');
            
            // Check if element is in viewport
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        setTimeout(() => {
                            bar.classList.add('animate');
                        }, 200);
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.1
            });
            
            observer.observe(bar);
        });
    }

    // Initialize progress bars when page loads
    animateProgressBars();

    // Countdown Number Animation
    function animateCountdownNumbers() {
        const countdownNumbers = document.querySelectorAll('.countdown-number');
        
        countdownNumbers.forEach(counter => {
            const target = parseInt(counter.getAttribute('data-target'));
            const increment = target / 100;
            let current = 0;
            
            // Check if element is in viewport
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const updateCounter = () => {
                            if (current < target) {
                                current += increment;
                                if (current > target) {
                                    current = target;
                                }
                                counter.textContent = Math.ceil(current);
                                setTimeout(updateCounter, 20);
                            } else {
                                counter.textContent = target;
                            }
                        };
                        
                        updateCounter();
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.1
            });
            
            observer.observe(counter);
        });
    }

    // Initialize countdown numbers when page loads
    animateCountdownNumbers();

    // Service card click handler
    $('.service-card').on('click', function() {
        // Add your service card click logic here
        console.log('Service card clicked');
    });

    // Card arrow click handler
    $('.card-arrow').on('click', function(e) {
        e.stopPropagation();
        // Add your arrow button click logic here
        console.log('Arrow button clicked');
    });
});

// Loan Calculator Functionality
document.addEventListener('DOMContentLoaded', function() {
    // Get slider elements
    const loanAmountSlider = document.getElementById('loanAmountSlider');
    const monthsSlider = document.getElementById('monthsSlider');
    const interestRateSlider = document.getElementById('interestRateSlider');
    
    // Get display elements
    const loanAmountDisplay = document.getElementById('loanAmount');
    const monthsDisplay = document.getElementById('months');
    const interestRateDisplay = document.getElementById('interestRate');
    const payMonthlyDisplay = document.getElementById('payMonthly');
    const totalPayBackDisplay = document.getElementById('totalPayBack');
    
    // Calculate loan values
    function calculateLoan() {
        const principal = parseFloat(loanAmountSlider.value);
        const months = parseInt(monthsSlider.value);
        const annualRate = parseFloat(interestRateSlider.value);
        const monthlyRate = annualRate / 100 / 12;
        
        // Calculate monthly payment using EMI formula
        let monthlyPayment;
        if (monthlyRate === 0) {
            monthlyPayment = principal / months;
        } else {
            monthlyPayment = principal * (monthlyRate * Math.pow(1 + monthlyRate, months)) / (Math.pow(1 + monthlyRate, months) - 1);
        }
        
        const totalPayment = monthlyPayment * months;
        
        // Update displays
        loanAmountDisplay.textContent = principal.toLocaleString('en-IN');
        monthsDisplay.textContent = months;
        interestRateDisplay.textContent = annualRate.toFixed(1);
        payMonthlyDisplay.textContent = Math.round(monthlyPayment).toLocaleString('en-IN');
        totalPayBackDisplay.textContent = Math.round(totalPayment).toLocaleString('en-IN');
        
        // Update month text
        const monthText = months === 1 ? 'Month' : 'Months';
        monthsDisplay.nextElementSibling.textContent = monthText;
    }
    
    // Add event listeners
    loanAmountSlider.addEventListener('input', calculateLoan);
    monthsSlider.addEventListener('input', calculateLoan);
    interestRateSlider.addEventListener('input', calculateLoan);
    
    // Initialize calculation
    calculateLoan();
    
    // Icon box click functionality
    const iconBoxes = document.querySelectorAll('.icon-box');
    iconBoxes.forEach(box => {
        box.addEventListener('click', function() {
            // Remove active class from all boxes
            iconBoxes.forEach(b => b.classList.remove('active'));
            // Add active class to clicked box
            this.classList.add('active');
        });
    });
    
    // Apply loan button functionality
    const applyLoanBtn = document.querySelector('.apply-loan-btn');
    if (applyLoanBtn) {
        applyLoanBtn.addEventListener('click', function() {
            // Create success message
            const successMessage = document.createElement('div');
            successMessage.className = 'success-message';
            successMessage.innerHTML = `
                <div class="success-content">
                    <i class="fas fa-check-circle"></i>
                    <h3>Application Submitted!</h3>
                    <p>Your loan application of ₹${loanAmountDisplay.textContent} has been submitted successfully.</p>
                    <button class="close-success">OK</button>
                </div>
            `;
            
            // Add styles for success message
            const successStyle = document.createElement('style');
            successStyle.textContent = `
                .success-message {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.5);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 3000;
                    animation: fadeIn 0.3s ease;
                }
                
                .success-content {
                    background: white;
                    padding: 40px;
                    border-radius: 12px;
                    text-align: center;
                    max-width: 400px;
                    animation: slideUp 0.3s ease;
                }
                
                .success-content i {
                    font-size: 48px;
                    color: #28a745;
                    margin-bottom: 20px;
                }
                
                .success-content h3 {
                    font-size: 24px;
                    color: #333;
                    margin-bottom: 10px;
                }
                
                .success-content p {
                    font-size: 16px;
                    color: #666;
                    margin-bottom: 20px;
                }
                
                .close-success {
                    background: #007bff;
                    color: white;
                    border: none;
                    padding: 12px 30px;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 16px;
                    font-weight: 500;
                }
                
                .close-success:hover {
                    background: #0056b3;
                }
                
                @keyframes fadeIn {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                
                @keyframes slideUp {
                    from { transform: translateY(50px); opacity: 0; }
                    to { transform: translateY(0); opacity: 1; }
                }
            `;
            
            document.head.appendChild(successStyle);
            document.body.appendChild(successMessage);
            
            // Close functionality
            const closeBtn = successMessage.querySelector('.close-success');
            closeBtn.addEventListener('click', function() {
                document.body.removeChild(successMessage);
                document.head.removeChild(successStyle);
            });
            
            // Auto close after 5 seconds
            setTimeout(() => {
                if (document.body.contains(successMessage)) {
                    document.body.removeChild(successMessage);
                    document.head.removeChild(successStyle);
                }
            }, 5000);
        });
    }
});

// Slider functionality
let currentSlideIndex = 1;
let slideInterval;

// Initialize slider
document.addEventListener('DOMContentLoaded', function() {
    showSlide(currentSlideIndex);
    startAutoSlide();
});

// Change slide function
function changeSlide(direction) {
    const slides = document.getElementsByClassName('slide');
    const dots = document.getElementsByClassName('dot');
    
    // Hide current slide
    slides[currentSlideIndex - 1].classList.remove('active');
    dots[currentSlideIndex - 1].classList.remove('active');
    
    // Update slide index
    currentSlideIndex += direction;
    
    // Wrap around if needed
    if (currentSlideIndex > slides.length) {
        currentSlideIndex = 1;
    } else if (currentSlideIndex < 1) {
        currentSlideIndex = slides.length;
    }
    
    // Show new slide
    slides[currentSlideIndex - 1].classList.add('active');
    dots[currentSlideIndex - 1].classList.add('active');
    
    // Reset auto slide timer
    resetAutoSlide();
}

// Go to specific slide
function currentSlide(n) {
    const slides = document.getElementsByClassName('slide');
    const dots = document.getElementsByClassName('dot');
    
    // Hide current slide
    slides[currentSlideIndex - 1].classList.remove('active');
    dots[currentSlideIndex - 1].classList.remove('active');
    
    // Set new slide index
    currentSlideIndex = n;
    
    // Show new slide
    slides[currentSlideIndex - 1].classList.add('active');
    dots[currentSlideIndex - 1].classList.add('active');
    
    // Reset auto slide timer
    resetAutoSlide();
}

// Show slide function (for initialization)
function showSlide(n) {
    const slides = document.getElementsByClassName('slide');
    const dots = document.getElementsByClassName('dot');
    
    if (n > slides.length) {
        currentSlideIndex = 1;
    }
    if (n < 1) {
        currentSlideIndex = slides.length;
    }
    
    // Hide all slides
    for (let i = 0; i < slides.length; i++) {
        slides[i].classList.remove('active');
    }
    
    // Remove active from all dots
    for (let i = 0; i < dots.length; i++) {
        dots[i].classList.remove('active');
    }
    
    // Show current slide and activate dot
    slides[currentSlideIndex - 1].classList.add('active');
    dots[currentSlideIndex - 1].classList.add('active');
}

// Auto slide functionality
function startAutoSlide() {
    slideInterval = setInterval(function() {
        changeSlide(1);
    }, 5000); // Change slide every 5 seconds
}

// Reset auto slide timer
function resetAutoSlide() {
    clearInterval(slideInterval);
    startAutoSlide();
}

// Pause auto slide on hover
document.querySelector('.banner-slider').addEventListener('mouseenter', function() {
    clearInterval(slideInterval);
});

document.querySelector('.banner-slider').addEventListener('mouseleave', function() {
    startAutoSlide();
});

// Keyboard navigation
document.addEventListener('keydown', function(e) {
    if (e.key === 'ArrowLeft') {
        changeSlide(-1);
    } else if (e.key === 'ArrowRight') {
        changeSlide(1);
    }
});

// Touch/swipe support for mobile
let touchStartX = 0;
let touchEndX = 0;

document.querySelector('.banner-slider').addEventListener('touchstart', function(e) {
    touchStartX = e.changedTouches[0].screenX;
});

document.querySelector('.banner-slider').addEventListener('touchend', function(e) {
    touchEndX = e.changedTouches[0].screenX;
    handleSwipe();
});

function handleSwipe() {
    const swipeThreshold = 50;
    const diff = touchStartX - touchEndX;
    
    if (Math.abs(diff) > swipeThreshold) {
        if (diff > 0) {
            // Swipe left - go to next slide
            changeSlide(1);
        } else {
            // Swipe right - go to previous slide
            changeSlide(-1);
        }
    }
}

// Search functionality (placeholder)
document.querySelector('.search-icon').addEventListener('click', function() {
    const searchModal = document.createElement('div');
    searchModal.className = 'search-modal';
    searchModal.innerHTML = `
        <div class="search-modal-content">
            <span class="close-search">&times;</span>
            <input type="text" placeholder="Search..." class="search-input">
            <button class="search-btn">Search</button>
        </div>
    `;
    
    document.body.appendChild(searchModal);
    
    // Add styles for search modal
    const style = document.createElement('style');
    style.textContent = `
        .search-modal {
            display: block;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s;
        }
        
        .search-modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 30px;
            border-radius: 8px;
            width: 80%;
            max-width: 500px;
            position: relative;
            animation: slideIn 0.3s;
        }
        
        .close-search {
            position: absolute;
            right: 15px;
            top: 15px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #666;
        }
        
        .close-search:hover {
            color: #333;
        }
        
        .search-input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            margin-bottom: 15px;
        }
        
        .search-btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .search-btn:hover {
            background: #0056b3;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    `;
    document.head.appendChild(style);
    
    // Close modal functionality
    const closeBtn = searchModal.querySelector('.close-search');
    closeBtn.addEventListener('click', function() {
        document.body.removeChild(searchModal);
        document.head.removeChild(style);
    });
    
    // Close modal on outside click
    searchModal.addEventListener('click', function(e) {
        if (e.target === searchModal) {
            document.body.removeChild(searchModal);
            document.head.removeChild(style);
        }
    });
    
    // Focus on input
    searchModal.querySelector('.search-input').focus();
});

// Smooth scroll for navigation links
document.querySelectorAll('.main-nav a').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        e.preventDefault();
        const targetId = this.getAttribute('href');
        if (targetId === '#') {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        } else {
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        }
    });
});

// Header scroll effect
window.addEventListener('scroll', function() {
    const header = document.querySelector('header');
    if (window.scrollY > 100) {
        header.style.boxShadow = '0 4px 15px rgba(0,0,0,0.1)';
    } else {
        header.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';
    }
});
