/* ==========================================================================
   SJ Finance Interactive JavaScript
   Handles Navbar, Modals, EMI Calculator, SVG Chart, and Contact Forms
   ========================================================================== */

document.addEventListener("DOMContentLoaded", function() {

    /* ==========================================
       1. Mobile Menu / Hamburger Toggle
       ========================================== */
    const hamburger = document.getElementById("hamburger");
    const navMenu = document.getElementById("navMenu");
    const navLinks = document.querySelectorAll(".nav-link");

    if (hamburger && navMenu) {
        hamburger.addEventListener("click", () => {
            hamburger.classList.toggle("active");
            navMenu.classList.toggle("active");
        });

        // Close menu when clicking a link
        navLinks.forEach(link => {
            link.addEventListener("click", () => {
                hamburger.classList.remove("active");
                navMenu.classList.remove("active");
                
                // Set active class on clicked link
                navLinks.forEach(l => l.classList.remove("active"));
                link.classList.add("active");
            });
        });
    }

    /* ==========================================
       2. Modal Systems Control (Apply & Partner)
       ========================================== */
    const openModalBtns = document.querySelectorAll(".open-modal-btn");
    const closeModalTriggers = document.querySelectorAll(".modal-close-trigger");
    const modals = document.querySelectorAll(".modal");

    // Open Modal
    openModalBtns.forEach(btn => {
        btn.addEventListener("click", function() {
            const modalId = this.getAttribute("data-modal");
            const modal = document.getElementById(modalId);
            
            if (modal) {
                // If a specific loan type was clicked, preset it in the modal dropdown
                const loanType = this.getAttribute("data-loan-type");
                if (loanType) {
                    const selectElement = modal.querySelector("select");
                    if (selectElement) {
                        selectElement.value = loanType;
                    }
                }
                
                modal.classList.add("active");
                document.body.style.overflow = "hidden"; // Prevent background scroll
            }
        });
    });

    // Close Modal
    closeModalTriggers.forEach(trigger => {
        trigger.addEventListener("click", function() {
            const modal = this.closest(".modal");
            if (modal) {
                modal.classList.remove("active");
                document.body.style.overflow = ""; // Restore scroll
            }
        });
    });

    // Close Modal on Esc key
    document.addEventListener("keydown", function(e) {
        if (e.key === "Escape") {
            modals.forEach(modal => {
                if (modal.classList.contains("active")) {
                    modal.classList.remove("active");
                    document.body.style.overflow = "";
                }
            });
        }
    });


    /* ==========================================
       3. EMI Calculator Logic
       ========================================== */
    // Input elements
    const loanAmountInput = document.getElementById("loanAmountInput");
    const loanAmountSlider = document.getElementById("loanAmountSlider");
    const interestRateInput = document.getElementById("interestRateInput");
    const interestRateSlider = document.getElementById("interestRateSlider");
    const loanTenureInput = document.getElementById("loanTenureInput");
    const loanTenureSlider = document.getElementById("loanTenureSlider");
    
    // Tenure Toggle button elements
    const tenureYearsBtn = document.getElementById("tenureYears");
    const tenureMonthsBtn = document.getElementById("tenureMonths");
    const tenureUnitText = document.getElementById("tenureUnitText");
    
    // Output Elements
    const monthlyEmiVal = document.getElementById("monthlyEmi");
    const totalPrincipalVal = document.getElementById("totalPrincipalVal");
    const totalInterestVal = document.getElementById("totalInterestVal");
    const totalPayableVal = document.getElementById("totalPayableVal");
    
    // SVG Donut Chart elements
    const chartProgress = document.getElementById("chartProgress");
    const chartTotalVal = document.getElementById("chartTotalVal");
    const principalPercentage = document.getElementById("principalPercentage");
    const interestPercentage = document.getElementById("interestPercentage");

    let isYearlyTenure = true; // State for tenure unit

    // Run calculator on initial load
    if (loanAmountInput) {
        calculateEmi();
    }

    // Connect slider with inputs and trigger calculations
    setupSliderSync(loanAmountSlider, loanAmountInput);
    setupSliderSync(interestRateSlider, interestRateInput);
    setupSliderSync(loanTenureSlider, loanTenureInput);

    // Tenure unit toggling listeners
    if (tenureYearsBtn && tenureMonthsBtn) {
        tenureYearsBtn.addEventListener("click", () => {
            if (!isYearlyTenure) {
                isYearlyTenure = true;
                tenureYearsBtn.classList.add("active");
                tenureMonthsBtn.classList.remove("active");
                tenureUnitText.innerText = "वर्ष (Yrs)";
                
                // Convert tenure value from months to years
                let months = parseInt(loanTenureInput.value) || 12;
                let years = Math.max(1, Math.round(months / 12));
                
                // Adjust Slider Limits for Years
                updateSliderLimits(loanTenureSlider, 1, 30, years);
                loanTenureInput.value = years;
                
                calculateEmi();
            }
        });

        tenureMonthsBtn.addEventListener("click", () => {
            if (isYearlyTenure) {
                isYearlyTenure = false;
                tenureMonthsBtn.classList.add("active");
                tenureYearsBtn.classList.remove("active");
                tenureUnitText.innerText = "महीने (Mths)";
                
                // Convert tenure value from years to months
                let years = parseInt(loanTenureInput.value) || 5;
                let months = Math.min(360, years * 12);
                
                // Adjust Slider Limits for Months
                updateSliderLimits(loanTenureSlider, 12, 360, months, 12);
                loanTenureInput.value = months;
                
                calculateEmi();
            }
        });
    }

    // Helper to sync slider with number input field
    function setupSliderSync(slider, input) {
        if (!slider || !input) return;
        
        slider.addEventListener("input", function() {
            input.value = this.value;
            calculateEmi();
        });

        input.addEventListener("input", function() {
            let val = parseFloat(this.value);
            let min = parseFloat(this.min);
            let max = parseFloat(this.max);
            
            if (isNaN(val)) return;
            if (val < min) val = min;
            if (val > max) val = max;
            
            slider.value = val;
            calculateEmi();
        });
    }

    // Helper to adjust tenure limits on unit toggle
    function updateSliderLimits(slider, min, max, currentVal, step = 1) {
        slider.min = min;
        slider.max = max;
        slider.step = step;
        slider.value = currentVal;
    }

    // Formatter for Indian Currency Output
    function formatIndianCurrency(num) {
        return new Intl.NumberFormat('en-IN', {
            style: 'currency',
            currency: 'INR',
            maximumFractionDigits: 0
        }).format(num);
    }

    // Formatter specifically for short text display inside Donut chart (Lakhs/Crores)
    function formatShortIndianCurrency(num) {
        if (num >= 10000000) {
            return `₹${(num / 10000000).toFixed(2)} Cr`;
        } else if (num >= 100000) {
            return `₹${(num / 100000).toFixed(2)} L`;
        } else {
            return formatIndianCurrency(num);
        }
    }

    // Core EMI Math function
    function calculateEmi() {
        if (!loanAmountInput || !interestRateInput || !loanTenureInput) return;

        const principal = parseFloat(loanAmountInput.value) || 0;
        const annualRate = parseFloat(interestRateInput.value) || 0;
        const tenureValue = parseFloat(loanTenureInput.value) || 0;

        // Convert tenure to months
        const numberOfMonths = isYearlyTenure ? (tenureValue * 12) : tenureValue;
        
        // Monthly interest rate
        const monthlyRate = (annualRate / 12) / 100;

        let emi = 0;
        let totalPayable = 0;
        let totalInterest = 0;

        if (principal > 0 && numberOfMonths > 0) {
            if (monthlyRate === 0) {
                // Zero percent interest edge-case
                emi = principal / numberOfMonths;
            } else {
                // standard emi formula: P * r * (1+r)^n / ((1+r)^n - 1)
                const base = Math.pow(1 + monthlyRate, numberOfMonths);
                emi = principal * monthlyRate * base / (base - 1);
            }
            totalPayable = emi * numberOfMonths;
            totalInterest = totalPayable - principal;
        }

        // Display results
        monthlyEmiVal.innerText = formatIndianCurrency(emi);
        totalPrincipalVal.innerText = formatIndianCurrency(principal);
        totalInterestVal.innerText = formatIndianCurrency(totalInterest);
        totalPayableVal.innerText = formatIndianCurrency(totalPayable);

        // Update Donut Chart
        updateDonutChart(principal, totalInterest, totalPayable);
    }

    // Handles the SVG stroke alignment and legend text
    function updateDonutChart(principal, interest, total) {
        if (!chartProgress || total === 0) return;

        const principalPercentVal = Math.round((principal / total) * 100) || 0;
        const interestPercentVal = 100 - principalPercentVal;

        principalPercentage.innerText = `${principalPercentVal}%`;
        interestPercentage.innerText = `${interestPercentVal}%`;
        chartTotalVal.innerText = formatShortIndianCurrency(total);

        // SVG donut circumference calculations
        // Circumference = 2 * PI * r = 2 * 3.14159 * 85 = 534
        const circumference = 534;
        
        // The stroke-dashoffset controls how much of the stroke is hidden (starting from full 534).
        // Since the chart progress color represents INTEREST, we show the interest percentage.
        // If interest is 30%, offset will hide 70% of the circle, showing a 30% stroke.
        const offset = circumference * (1 - (interestPercentVal / 100));
        
        chartProgress.style.strokeDashoffset = offset;
    }


    /* ==========================================
       4. Toast Notification System
       ========================================== */
    const toastContainer = document.getElementById("toastContainer");

    function showToast(title, message, type = "success") {
        if (!toastContainer) return;

        const toast = document.createElement("div");
        toast.className = `toast ${type === "success" ? "" : type}`;
        
        const iconClass = type === "success" 
            ? "fa-circle-check" 
            : type === "error" 
            ? "fa-circle-xmark" 
            : "fa-circle-info";

        toast.innerHTML = `
            <i class="fa-solid ${iconClass} toast-icon"></i>
            <div class="toast-details">
                <h4>${title}</h4>
                <p>${message}</p>
            </div>
            <i class="fa-solid fa-xmark toast-close"></i>
        `;

        toastContainer.appendChild(toast);

        // Trigger slide-in animation
        setTimeout(() => {
            toast.classList.add("show");
        }, 10);

        // Auto remove toast after 4s
        const autoCloseTimeout = setTimeout(() => {
            closeToast(toast);
        }, 4000);

        // Manual Close trigger
        const closeBtn = toast.querySelector(".toast-close");
        if (closeBtn) {
            closeBtn.addEventListener("click", () => {
                clearTimeout(autoCloseTimeout);
                closeToast(toast);
            });
        }
    }

    function closeToast(toast) {
        toast.classList.remove("show");
        // Wait for CSS slide transition to finish before removing node from DOM
        toast.addEventListener("transitionend", () => {
            toast.remove();
        });
    }


    /* ==========================================
       5. Form Submission Simulations
       ========================================== */
    const contactForm = document.getElementById("contactForm");
    const modalApplyForm = document.getElementById("modalApplyForm");
    const modalPartnerForm = document.getElementById("modalPartnerForm");

    // Connect standard contact page form
    if (contactForm) {
        setupFormHandler(contactForm, "पूछताछ सबमिट हो गई!", "जानकारी भेजने के लिए धन्यवाद। हमारी टीम 2 घंटे के भीतर आपसे संपर्क करेगी।");
    }

    // Connect floating apply now modal form
    if (modalApplyForm) {
        setupFormHandler(modalApplyForm, "आवेदन प्राप्त हुआ!", "लोन आवेदन के लिए धन्यवाद। हमारा लोन एजेंट जल्दी ही दस्तावेज़ कलेक्शन के लिए कॉल करेगा।", true);
    }

    // Connect become partner modal form
    if (modalPartnerForm) {
        setupFormHandler(modalPartnerForm, "पार्टनर रजिस्ट्रेशन सफल!", "पार्टनर प्रोग्राम में रुचि दिखाने के लिए धन्यवाद। हमारी DSA टीम आपसे जल्द ही संपर्क करेगी।", true);
    }

    // Helper to hook submission triggers
    function setupFormHandler(form, successTitle, successMessage, isModal = false) {
        form.addEventListener("submit", function(e) {
            e.preventDefault();

            const submitBtn = this.querySelector("button[type='submit']");
            const originalBtnHtml = submitBtn.innerHTML;
            
            // Set Loading state on CTA Button
            submitBtn.disabled = true;
            submitBtn.innerHTML = `<span>कृपया प्रतीक्षा करें...</span> <i class="fa-solid fa-spinner fa-spin"></i>`;

            // Simulate Network Request Delay
            setTimeout(() => {
                // Reset Button status
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;

                // Reset Form elements
                form.reset();

                // Close parent modal if applicable
                if (isModal) {
                    const modal = form.closest(".modal");
                    if (modal) {
                        modal.classList.remove("active");
                        document.body.style.overflow = ""; // restore body scroll
                    }
                }

                // Push success notification alert
                showToast(successTitle, successMessage, "success");

            }, 1200);
        });
    }


    /* ==========================================
       6. Scroll reveal animations
       ========================================== */
    // Add scroll animation reveal triggers to sections
    const reveals = document.querySelectorAll(".reveal, .reveal-left, .reveal-right");

    const revealOnScroll = () => {
        const windowHeight = window.innerHeight;
        
        reveals.forEach(element => {
            const elementTop = element.getBoundingClientRect().top;
            const elementVisible = 120; // threshold height

            if (elementTop < windowHeight - elementVisible) {
                element.classList.add("active");
            }
        });
    };

    // Initial check on load
    revealOnScroll();
    
    // Listen to scroll events
    window.addEventListener("scroll", revealOnScroll);

    // Dynamic Header active section link highlighter on scroll
    const sections = document.querySelectorAll("section");
    
    window.addEventListener("scroll", () => {
        let currentSection = "home";
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;
            
            // Adjust threshold to match scroll position
            if (pageYOffset >= (sectionTop - 150)) {
                currentSection = section.getAttribute("id") || currentSection;
            }
        });

        navLinks.forEach(link => {
            link.classList.remove("active");
            const href = link.getAttribute("href");
            if (href === `#${currentSection}`) {
                link.classList.add("active");
            }
        });
    });

    /* ==========================================
       7. Service Documents Toggle Accordion
       ========================================== */
    const docToggles = document.querySelectorAll(".btn-docs-toggle");
    
    docToggles.forEach(btn => {
        btn.addEventListener("click", function() {
            const container = this.closest(".docs-toggle-container");
            const collapseElement = container.querySelector(".docs-list-collapse");
            const icon = this.querySelector("i");
            
            // Toggle active state
            collapseElement.classList.toggle("active");
            this.classList.toggle("active");
            
            if (collapseElement.classList.contains("active")) {
                collapseElement.style.maxHeight = collapseElement.scrollHeight + "px";
                icon.style.transform = "rotate(180deg)";
            } else {
                collapseElement.style.maxHeight = "0";
                icon.style.transform = "rotate(0deg)";
            }
        });
    });

    /* ==========================================
       8. FAQ Accordion Toggle
       ========================================== */
    const faqQuestions = document.querySelectorAll(".faq-question");
    
    faqQuestions.forEach(question => {
        question.addEventListener("click", function() {
            const faqItem = this.closest(".faq-item");
            const faqAnswer = faqItem.querySelector(".faq-answer");
            
            // Check if already active
            const isActive = faqItem.classList.contains("active");
            
            // Close all other FAQs
            document.querySelectorAll(".faq-item").forEach(item => {
                item.classList.remove("active");
                item.querySelector(".faq-answer").style.maxHeight = "0";
            });
            
            // Open clicked FAQ if it wasn't active
            if (!isActive) {
                faqItem.classList.add("active");
                faqAnswer.style.maxHeight = faqAnswer.scrollHeight + "px";
            }
        });
    });

});
