$(document).ready(function () {
    const showAlert = ({
        icon = "success",
        title = "Success",
        message = "",
        confirmText = "OK",
        timer = 2000,
    }) => {
        Swal.fire({
            icon: icon,
            title: title,
            text: message,
            confirmButtonText: confirmText,
            confirmButtonColor: "#ED1C24",
            timer: timer,
            timerProgressBar: timer ? true : false,
        });
    };

    // success alert
    const sweetSuccess = (msg, title = "Success") => {
        showAlert({
            icon: "success",
            title: title,
            message: msg,
        });
    };

    // error alert
    const sweetError = (msg, title = "Error") => {
        showAlert({
            icon: "error",
            title: title,
            message: msg,
        });
    };
    // contact form submit start here
    $("#contactForm").on("submit", function (e) {
        e.preventDefault();

        let form = $(this);
        let button = form.find('button[type="submit"]');
        let formData = new FormData(this);

        // reset errors
        $(".error").text("");
        $(".form-control-custom").removeClass("is-invalid");

        // button loading
        button.prop("disabled", true);
        button.find(".loading").removeClass("d-none");
        button.find(".btn-msg").addClass("d-none");

        // disable full form
        form.find("input, select, textarea, button").prop("disabled", true);

        $.ajax({
            url: form.attr("action"),
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,

            success: function (response) {
                // enable form again
                form.find("input, select, textarea, button").prop(
                    "disabled",
                    false,
                );
                button.prop("disabled", false);
                button.find(".loading").addClass("d-none");
                button.find(".btn-msg").removeClass("d-none");
                form[0].reset();
                sweetSuccess(response.message);
            },

            error: function (xhr) {
                // enable form again
                form.find("input, select, textarea, button").prop(
                    "disabled",
                    false,
                );
                button.prop("disabled", false);
                button.find(".loading").addClass("d-none");
                button.find(".btn-msg").removeClass("d-none");
                if (xhr.status === 422) {
                    let errors = xhr.responseJSON.errors;

                    let firstInput = null;

                    $.each(errors, function (key, value) {
                        $("." + key + "_error").text(value[0]);

                        $('[name="' + key + '"]').addClass("is-invalid");

                        if (!firstInput) {
                            firstInput = $('[name="' + key + '"]');
                        }
                    });

                    if (firstInput) {
                        firstInput.focus();
                    }
                }

                if (xhr.status === 500) {
                    const error_text = xhr.responseJSON;
                    sweetError(error_text);
                }
            },
        });
    });

    // land wanted form submit
    $("#landWantedForm").on("submit", function (e) {
        e.preventDefault();

        let form = $(this);
        let formData = new FormData(this);
        let button = form.find('button[type="submit"]');

        $(".error").text("");
        $(".form-control-custom").removeClass("is-invalid");

        // spinner
        button.prop("disabled", true);
        button.find(".loading").removeClass("d-none");
        button.find(".btn-msg").addClass("d-none");

        // disable full form
        form.find("input, select, textarea, button").prop("disabled", true);

        $.ajax({
            url: form.attr("action"),
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,

            success: function (response) {
                // enable form again
                form.find("input, select, textarea, button").prop(
                    "disabled",
                    false,
                );
                button.prop("disabled", false);
                button.find(".loading").addClass("d-none");
                button.find(".btn-msg").removeClass("d-none");

                form[0].reset();
                sweetSuccess(response.message);
            },

            error: function (xhr) {
                // enable form again
                form.find("input, select, textarea, button").prop(
                    "disabled",
                    false,
                );
                button.prop("disabled", false);
                button.find(".loading").addClass("d-none");
                button.find(".btn-msg").removeClass("d-none");

                if (xhr.status === 422) {
                    let errors = xhr.responseJSON.errors;
                    let firstInput = null;

                    $.each(errors, function (key, value) {
                        $("." + key + "_error").text(value[0]);
                        $('[name="' + key + '"]').addClass("is-invalid");

                        if (!firstInput) {
                            firstInput = $('[name="' + key + '"]');
                        }
                    });

                    if (firstInput) {
                        firstInput.focus();
                    }
                }

                if (xhr.status === 500) {
                    const error_text = xhr.responseJSON;
                    sweetError(error_text);
                }
            },
        });
    });

    // remove error when typing
    $(document).on("input change", ".form-control-custom", function () {
        $(this).removeClass("is-invalid");
        let name = $(this).attr("name");
        $("." + name + "_error").text("");
    });
    // contact form submit end here

    /* ─── Navbar scroll behavior ──────────────────────────── */
    const $nav = $("#mainNav");
    const $menu = $("#navbarMain");

    function updateNavbar() {
        const scrollTop = $(window).scrollTop();
        const isMenuOpen = $menu.hasClass("show");

        if (isMenuOpen) {
            $nav.addClass("scrolled").removeClass("transparent");
            return;
        }

        if (scrollTop > 100) {
            $nav.addClass("scrolled").removeClass("transparent");
        } else {
            $nav.removeClass("scrolled").addClass("transparent");
        }
    }

    // Scroll
    $(window).on("scroll", updateNavbar);

    // Menu open
    $menu.on("show.bs.collapse", function () {
        $nav.addClass("scrolled").removeClass("transparent");
    });

    // Menu close
    $menu.on("hidden.bs.collapse", function () {
        updateNavbar();
    });

    // Initial load
    updateNavbar();

    /* ─── Project Filter ──────────────────────────────────── */
    $(document).on("click", ".filter-tab", function () {
        const filter = $(this).data("filter");
        const $items = $("[data-category]");

        // Active tab
        $(".filter-tab").removeClass("active");
        $(this).addClass("active");

        // Filter items
        $items.each(function () {
            const $item = $(this);
            const category = $item.data("category");

            if (filter === "all" || category === filter) {
                $item.stop(true, true).fadeIn(350);
            } else {
                $item.stop(true, true).fadeOut(200);
            }
        });

        // Re-run animation after filter
        setTimeout(dataAosInit, 400);
    });

    /* ─── AOS-like animation observer ─────────────────────── */
    const aosObserver = new IntersectionObserver(
        (entries, observer) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    const delay = entry.target.dataset.delay || 0;

                    setTimeout(() => {
                        entry.target.classList.add("aos-animate");
                    }, delay);

                    observer.unobserve(entry.target);
                }
            });
        },
        {
            threshold: 0.15,
        },
    );

    /* ─── AOS Initialization Function ─────────────────────── */
    function dataAosInit() {
        document.querySelectorAll("[data-aos]").forEach((el) => {
            // Reset animation so it can run again after filter
            el.classList.remove("aos-animate");

            aosObserver.observe(el);
        });
    }

    /* ─── Run on Page Load ───────────────────────────────── */
    document.addEventListener("DOMContentLoaded", function () {
        dataAosInit();
    });
    /* ─── FAQ Accordion ───────────────────────────────────── */
    $(document).on("click", ".faq-question", function () {
        const $item = $(this).closest(".faq-item");
        const isActive = $item.hasClass("active");
        $(".faq-item").removeClass("active");
        if (!isActive) $item.addClass("active");
    });

    /* ─── Count Up Animation ──────────────────────────────── */
    function countUp(el) {
        const target = parseInt(el.dataset.count, 10);
        const duration = 1800;
        const step = target / (duration / 16);
        let current = 0;

        const timer = setInterval(() => {
            current += step;
            if (current >= target) {
                current = target;
                clearInterval(timer);
            }
            el.textContent = Math.floor(current);
        }, 16);
    }

    const countObserver = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    countUp(entry.target);
                    countObserver.unobserve(entry.target);
                }
            });
        },
        { threshold: 0.5 },
    );

    document
        .querySelectorAll("[data-count]")
        .forEach((el) => countObserver.observe(el));

    /* ─── Back to Top ─────────────────────────────────────── */
    const $backToTop = $("#backToTop");

    $(window).on("scroll", function () {
        $(this).scrollTop() > 400
            ? $backToTop.addClass("visible")
            : $backToTop.removeClass("visible");
    });

    $backToTop.on("click", function () {
        $("html, body").animate({ scrollTop: 0 }, 600);
    });

    /* ─── Smooth Anchor Links ─────────────────────────────── */
    $('a[href^="#"]:not([href="#"])').on("click", function (e) {
        const $target = $(this.getAttribute("href"));
        if ($target.length) {
            e.preventDefault();
            $("html, body").animate(
                { scrollTop: $target.offset().top - 80 },
                700,
            );
        }
    });

    /* ─── Active Nav Link ─────────────────────────────────── */
    // const path = window.location.pathname;
    // $("#mainNav .nav-link").each(function () {
    //     const href = $(this).attr("href");
    //     if (href && href !== "/" && path.startsWith(href)) {
    //         $(this).addClass("active");
    //     } else if (href === "/" && path === "/") {
    //         $(this).addClass("active");
    //     }
    // });
});

/* ─── Global CSS injected for spin animation ──────────── */
const style = document.createElement("style");
style.textContent = `
  @keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: none; }
  }
  .spin-icon {
    display: inline-block;
    animation: spin 0.8s linear infinite;
  }
  @keyframes spin {
    from { transform: rotate(0deg); }
    to   { transform: rotate(360deg); }
  }
`;
document.head.appendChild(style);
