// ============================================
// Main JavaScript for Mobile Service Management Frontend
// ============================================

// Language dropdown functionality
const dropdownButtons = document.querySelectorAll("[data-dropdown-toggle]");

dropdownButtons.forEach((button) => {
    const menuId = button.getAttribute("data-dropdown-toggle");
    const menu = document.querySelector(`[data-dropdown-menu='${menuId}']`);

    if (menu) {
        // Toggle dropdown on button click
        button.addEventListener("click", function (event) {
            event.stopPropagation();

            // Hide all other dropdowns
            document
                .querySelectorAll("[data-dropdown-menu]")
                .forEach((otherMenu) => {
                    if (otherMenu !== menu) {
                        otherMenu.classList.add("hidden");
                    }
                });

            // Toggle current dropdown
            menu.classList.toggle("hidden");
        });

        // Handle language selection
        const languageLinks = menu.querySelectorAll("a");
        languageLinks.forEach((link) => {
            link.addEventListener("click", function (event) {
                event.preventDefault();
                const langKey = this.getAttribute('data-lang') || this.getAttribute('href').split('/').pop();

                if (langKey) {
                    // Redirect to language change route
                    window.location.href = this.href;
                } else {
                    // Fallback: update button text only
                    const selectedLanguage = this.textContent.trim();
                    const buttonSpan = button.querySelector("span");

                    if (buttonSpan) {
                        buttonSpan.textContent = selectedLanguage;
                    }
                }

                // Close dropdown after selection
                menu.classList.add("hidden");
            });
        });
    }
});

// Close all dropdowns when clicking outside
document.addEventListener("click", function (event) {
    const allMenus = document.querySelectorAll("[data-dropdown-menu]");
    const allButtons = document.querySelectorAll("[data-dropdown-toggle]");

    let clickedInsideDropdown = false;

    // Check if click was inside any dropdown or button
    allMenus.forEach((menu) => {
        if (menu.contains(event.target)) {
            clickedInsideDropdown = true;
        }
    });

    allButtons.forEach((button) => {
        if (button.contains(event.target)) {
            clickedInsideDropdown = true;
        }
    });

    // If click was outside all dropdowns, close them
    if (!clickedInsideDropdown) {
        allMenus.forEach((menu) => {
            menu.classList.add("hidden");
        });
    }
});

// Mobile Menu Toggle
function initMobileMenu() {
    const mobileMenuBtn = document.getElementById("mobileMenuBtn");
    const mobileMenu = document.getElementById("mobileMenu");

    if (mobileMenuBtn && mobileMenu) {
        // Toggle menu visibility
        mobileMenuBtn.addEventListener("click", function (e) {
            e.stopPropagation(); // Prevent closing when clicking the button
            mobileMenu.classList.toggle("hidden");

            // Toggle icon
            const icon = mobileMenuBtn.querySelector("i");
            if (icon.classList.contains("fa-bars")) {
                icon.classList.remove("fa-bars");
                icon.classList.add("fa-times");
            } else {
                icon.classList.remove("fa-times");
                icon.classList.add("fa-bars");
            }
        });

        // Close when clicking outside the menu
        document.addEventListener("click", function (e) {
            if (
                !mobileMenu.contains(e.target) &&
                !mobileMenuBtn.contains(e.target)
            ) {
                if (!mobileMenu.classList.contains("hidden")) {
                    mobileMenu.classList.add("hidden");

                    // Reset icon
                    const icon = mobileMenuBtn.querySelector("i");
                    icon.classList.remove("fa-times");
                    icon.classList.add("fa-bars");
                }
            }
        });
    }
}

// Run on DOM ready
document.addEventListener("DOMContentLoaded", initMobileMenu);

// Back to Top Button
const backToTopBtn = document.getElementById("back-to-top");
if (backToTopBtn) {
    window.addEventListener("scroll", () => {
        if (window.pageYOffset > 300) {
            backToTopBtn.classList.remove("hidden");
        } else {
            backToTopBtn.classList.add("hidden");
        }
    });

    backToTopBtn.addEventListener("click", () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
    });
}

// ============================================
// Home page scripts
// ============================================

// Initialize counters with animation
if (document.querySelector(".counter")) {
    document.addEventListener("DOMContentLoaded", () => {
        const counters = document.querySelectorAll(".counter");
        counters.forEach((counter, index) => {
            const target = +counter.getAttribute("data-target");
            counter.textContent = "0";

            setTimeout(() => {
                let current = 0;
                const increment = target / 50;
                const timer = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        counter.textContent = target;
                        clearInterval(timer);
                    } else {
                        counter.textContent = Math.floor(current);
                    }
                }, 40);
            }, index * 200);
        });
    });
}

// Initialize Testimonial Swiper sliders
if (document.querySelector(".testimonial-slider")) {
    const testimonialSwiper = new Swiper(".testimonial-slider", {
        slidesPerView: 1,
        loop: true,
        autoplay: true,
        speed: 500,
        ...(document.documentElement.dir === "rtl" ? { rtl: true } : {}),
        roundLengths: true,
        spaceBetween: 20,
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 20,
            },
            1024: {
                slidesPerView: 2,
                spaceBetween: 20,
            },
            1440: {
                slidesPerView: 3,
                spaceBetween: 20,
            },
        },
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
    });
}

// ============================================
// Service page scripts
// ============================================

// Service filtering functionality
if (document.querySelector(".service-filter") && document.querySelector(".service-item")) {
    document.addEventListener("DOMContentLoaded", function () {
        const filterButtons = document.querySelectorAll(".service-filter");
        const serviceItems = document.querySelectorAll(".service-item");

        if (filterButtons.length > 0 && serviceItems.length > 0) {
            filterButtons.forEach((button) => {
                button.addEventListener("click", function () {
                    const category = this.getAttribute("data-category");

                    // Remove active class from all buttons
                    filterButtons.forEach((btn) => btn.classList.remove("active"));

                    // Add active class to clicked button
                    this.classList.add("active");

                    // Filter service items
                    serviceItems.forEach((item) => {
                        if (category === "all" ||item.getAttribute("data-category") === category) {
                            item.style.display = "block";
                            item.classList.add("animate-fade-in");
                        } else {
                            item.style.display = "none";
                        }
                    });
                });
            });
        }
    });
}

// ============================================
// Service Details page scripts
// ============================================

// Initialize service Swiper slider
if (document.querySelector(".service-slider")) {
    const serviceSwiper = new Swiper(".service-slider", {
        slidesPerView: 1,
        loop: true,
        autoplay: true,
        speed: 500,
        ...(document.documentElement.dir === "rtl" ? { rtl: true } : {}),
        roundLengths: true,
        spaceBetween: 20,
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 20,
            },
            1024: {
                slidesPerView: 2,
                spaceBetween: 20,
            },
            1440: {
                slidesPerView: 3,
                spaceBetween: 20,
            },
        },
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
    });
}

// Star Rating Functionality
if (document.querySelector("#star-rating")) {
    document.addEventListener("DOMContentLoaded", function () {
        const starRating = document.getElementById("star-rating");
        if (starRating) {
            const stars = starRating.querySelectorAll("i");
            let selectedRating = 0;
            const ratingInput = document.getElementById("rating-value");

            ratingInput.value = selectedRating;

            $('#rating-value').val(selectedRating);
            stars.forEach((star, index) => {
                star.addEventListener("mouseover", () => {
                    highlightStars(index + 1);
                });

                star.addEventListener("click", () => {
                    selectedRating = index + 1;
                    highlightStars(selectedRating);

                    ratingInput.value = selectedRating;
                });
            });

            starRating.addEventListener("mouseleave", () => {
                highlightStars(selectedRating);
            });

            function highlightStars(rating) {
                stars.forEach((star, index) => {
                    if (index < rating) {
                        star.classList.remove("text-gray-300");
                        star.classList.add("text-yellow-400");
                    } else {
                        star.classList.remove("text-yellow-400");
                        star.classList.add("text-gray-300");
                    }
                });
            }
        }
    });
}

// ============================================
// FAQ page scripts
// ============================================

// FAQ Accordion
if (document.querySelector(".faq-question")) {
    document.querySelectorAll(".faq-question").forEach((question) => {
        question.addEventListener("click", () => {
            const answer = question.nextElementSibling;
            const icon = question.querySelector("i");
            const isCurrentlyOpen = !answer.classList.contains("hidden");

            // Close all FAQ answers
            document.querySelectorAll(".faq-answer").forEach((faqAnswer) => {
                faqAnswer.classList.add("hidden");
            });

            // Reset all icons to plus
            document.querySelectorAll(".faq-question i").forEach((faqIcon) => {
                faqIcon.classList.remove("fa-minus");
                faqIcon.classList.add("fa-plus");
            });

            // If the clicked FAQ wasn't open, open it
            if (isCurrentlyOpen) {
                answer.classList.add("hidden");
                icon.classList.add("fa-plus");
            } else {
                answer.classList.remove("hidden");
                icon.classList.remove("fa-plus");
                icon.classList.add("fa-minus");
            }
        });
    });
}

// ============================================
// About page scripts
// ============================================

// Initialize Team Swiper sliders
if (document.querySelector(".team-slider")) {
    const teamSwiper = new Swiper(".team-slider", {
        slidesPerView: 1,
        loop: true,
        autoplay: true,
        speed: 500,
        ...(document.documentElement.dir === "rtl" ? { rtl: true } : {}),
        roundLengths: true,
        spaceBetween: 20,
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 20,
            },
            1024: {
                slidesPerView: 2,
                spaceBetween: 20,
            },
            1440: {
                slidesPerView: 3,
                spaceBetween: 20,
            },
        },
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
    });
}

// ============================================
// Booking page scripts
// ============================================

let currentStep = 1;
const totalSteps = 3;

// Go to next step
function nextStep(step) {
    if (!validateStep(currentStep)) {
        return;
    }

    document.getElementById(`step-${currentStep}-content`).classList.remove("active");
    document.getElementById(`step-${step}-content`).classList.add("active");

    if (currentStep < step) {
        document.getElementById(`step-${currentStep}-circle`).classList.remove("step-active");
        document.getElementById(`step-${currentStep}-circle`).classList.add("step-completed");

        document.getElementById(`step-${step}-circle`).classList.remove("bg-gray-200", "text-gray-600");
        document.getElementById(`step-${step}-circle`).classList.add("step-active");
    }

    currentStep = step;
    updateProgressBar();

    if (step === 3) {
        updateSummary();
    }

    document.getElementById("booking-form").scrollIntoView({ behavior: "smooth", block: "start" });
}

// Go to previous step
function prevStep(step) {
    document.getElementById(`step-${currentStep}-content`).classList.remove("active");
    document.getElementById(`step-${step}-content`).classList.add("active");

    document.getElementById(`step-${currentStep}-circle`).classList.remove("step-active");
    document.getElementById(`step-${currentStep}-circle`).classList.add("bg-gray-200", "text-gray-600");

    document.getElementById(`step-${step}-circle`).classList.remove("bg-gray-200", "text-gray-600", "step-completed");
    document.getElementById(`step-${step}-circle`).classList.add("step-active");

    currentStep = step;
    updateProgressBar();

    document.getElementById("booking-form").scrollIntoView({ behavior: "smooth", block: "start" });
}

// Update progress bar based on current step
function updateProgressBar() {
    let progressPercentage = 0;
    if (currentStep === 1) progressPercentage = 0;
    else if (currentStep === 2) progressPercentage = 50;
    else if (currentStep === 3) progressPercentage = 100;

    const progressBar = document.getElementById("progress-bar");
    if (!progressBar) {
        console.warn("Progress bar element not found!");
        return;
    }

    progressBar.style.width = `${progressPercentage}%`;

    if (progressPercentage > 0) {
        progressBar.style.transition = "width 0.5s cubic-bezier(0.33, 1, 0.68, 1)";
        setTimeout(() => {
            progressBar.style.transition = "width 0.3s ease";
        }, 500);
    }
}

// Validate inputs for each step
function validateStep(step) {
    let isValid = true;
    document.querySelectorAll("span[id^='error-']").forEach(el => el.innerText = "");

    if (step === 1) {
        const serviceType = document.getElementById("service-type").value;
        const deviceBrand = document.getElementById("device-brand").value;
        const deviceModel = document.getElementById("device-model").value;
        const priority = document.getElementById("priority").value;
        const issueDescription = document.getElementById("issue-description").value;

        if (!serviceType) {
            document.getElementById("error-service-type").innerText = "Please select a service.";
            isValid = false;
        }
        if (!deviceBrand) {
            document.getElementById("error-device-brand").innerText = "Please select a brand.";
            isValid = false;
        }
        if (!deviceModel.trim()) {
            document.getElementById("error-device-model").innerText = "Please enter the model.";
            isValid = false;
        }
        if (!priority) {
            document.getElementById("error-priority").innerText = "Please choose repair urgency.";
            isValid = false;
        }
        if (!issueDescription.trim()) {
            document.getElementById("error-issue-description").innerText = "Please describe the issue.";
            isValid = false;
        }
    } else if (step === 2) {
        const name = document.getElementById("name").value;
        const email = document.getElementById("email").value;
        const phone = document.getElementById("phone").value;

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        const phoneRegex = /^\+\d{1,3}\d{9,13}$/;

        if (!name.trim()) {
            document.getElementById("error-name").innerText = "Name is required.";
            isValid = false;
        }
        if (!emailRegex.test(email)) {
            document.getElementById("error-email").innerText = "Enter a valid email.";
            isValid = false;
        }
        if (!phoneRegex.test(phone)) {
            document.getElementById("error-phone").innerText = "Enter a valid phone number.";
            isValid = false;
        }
    }

    return isValid;
}

// Update summary section with user inputs
function updateSummary() {
    const getValue = (id, fallback = "-") => {
        const el = document.getElementById(id);
        if (!el) return fallback;

        if (el.tagName === "SELECT") {
            const option = el.options[el.selectedIndex];
            return option ? option.text.trim() || fallback : fallback;
        }
        return el.value.trim() || fallback;
    };

    const setText = (id, text) => {
        const el = document.getElementById(id);
        if (el && el.children[1]) {
            el.children[1].textContent = text;
        }
    };

    // Service Summary
    setText("summary-service", getValue("service-type"));
    setText("summary-device", `${getValue("device-brand")} ${getValue("device-model")}`);

    const priority = document.querySelector('input[name="priority"]:checked')?.value || "normal";
    const priorityMap = {
        standard: "Standard (2-3 business days)",
        priority: "Priority (next business day)",
        emergency: "Emergency (same day service)",
    };
    setText("summary-urgency", priorityMap[priority] || priorityMap.normal);

    setText("summary-issue", getValue("issue-description"));

    // Contact Information
    setText("summary-name", getValue("name"));
    setText("summary-email", `${getValue("email")} | ${getValue("phone")}`);
    setText("summary-address", getValue("address"));

    // Estimated Price & Time
    const serviceTypeEl = document.getElementById("service-type");
    if (serviceTypeEl && serviceTypeEl.selectedIndex >= 0) {
        const selected = serviceTypeEl.options[serviceTypeEl.selectedIndex];

        if (selected.value === "0") {
            document.getElementById("other-service")?.classList.remove("hidden");
            document.getElementById("price-time")?.classList.add("hidden");
        } else {
            document.getElementById("other-service")?.classList.add("hidden");
            document.getElementById("price-time")?.classList.remove("hidden");

            document.getElementById("total-price").textContent = selected.dataset.price || 0;
            document.getElementById("total-time").textContent = selected.dataset.time || 0;
        }
    }
}

// Priority selection on class & styling update
const urgencyOptions = document.querySelectorAll(".urgency-option");
if (urgencyOptions.length > 0) {
    urgencyOptions.forEach((option) => {
        const radio = option.querySelector('input[type="radio"]');

        if (radio && radio.checked) {
            option.classList.add("border-black");
        }

        radio.addEventListener("click", function () {
            urgencyOptions.forEach((opt) => {
                opt.classList.remove("border-black");
            });

            option.classList.add("border-black");
        });
    });
}
