$(document).ready(function () {


    function showAlert(message, type = "danger") {
        const alertDiv = $("#statusAlert");
        alertDiv.removeClass("d-none alert-danger alert-success alert-warning")
            .addClass("alert-" + type)
            .text(message)
            .fadeIn();

        // Hide after 3 seconds
        setTimeout(() => {
            alertDiv.fadeOut();
        }, 3000);
    }

    function updateTracking(status) {
        const steps = $(".step");
        const stepNumbers = steps.map(function () {
            return parseInt($(this).data("step"));
        }).get();
        const maxStep = Math.max(...stepNumbers);

        // If status is invalid or 0, reset
        if (!status || status < stepNumbers[0]) {
            steps.removeClass("active");
            $(".progress-bar").css("width", "0%");
            return;
        }

        // Activate steps
        steps.each(function () {
            const stepVal = parseInt($(this).data("step"));
            $(this).toggleClass("active", stepVal <= status);
        });

        // Calculate proportional progress
        let percent = 0; // initialize
        for (let i = 0; i < stepNumbers.length; i++) {
            const current = stepNumbers[i];
            const next = stepNumbers[i + 1] || maxStep; // last step
            if (status >= current && status <= next) {
                if (next === current) { // last step
                    percent = 100;
                } else {
                    percent = ((i + (status - current) / (next - current)) / (stepNumbers.length - 1)) * 100;
                }
                break;
            }
        }

        $(".progress-bar").css("width", percent + "%");
    }

    // common function
    function fetchStatus(shipmentId) {
        if (!shipmentId) return showAlert("Enter shipment number");

        $.ajax({
            url: "get_shipment_status.php",
            type: "POST",
            data: { id: shipmentId },
            dataType: "json",
            success: function (res) {
                if (res && res.status) {
                    updateTracking(res.status);
                } else {
                    showAlert("Shipment not found");
                    updateTracking(0);
                }
            },
            error: function () {
                showAlert("Error fetching status");
                updateTracking(0);
            }
        });
    }

    // button click
    $("#checkStatus").click(function () {
        const shipmentId = $("#shipmentno").val().trim();
        fetchStatus(shipmentId);
    });

    // auto-run on page load if input has value
    const autoShipmentId = $("#shipmentno").val().trim();
    if (autoShipmentId) {
        fetchStatus(autoShipmentId);
    }



});