$(document).ready(function () {
    document.querySelectorAll(".percentageFormat").forEach((input) => {
        formatInputFieldPercentage(input);

        input.addEventListener("input", (e) => {
            let originalPos = input.selectionStart;

            let oldValue = input.value;
            formatInputFieldPercentage(input);

            // Fix cursor position after formatting
            setTimeout(() => {
                let newLength = input.value.length;
                let oldLength = oldValue.length;

                let diff = newLength - oldLength;
                let newPos = originalPos + diff;

                // Clamp to max length
                if (newPos > input.value.length - 1) {
                    newPos = input.value.length - 1;
                }

                input.setSelectionRange(newPos, newPos);
            }, 0);
        });
    });
});

function formatInputFieldPercentage(input) {
    let raw = input.value.replace(/,/g, "").replace(/%/g, "").replace(/[^\d.]/g, "");

    let parts = raw.split(".");
    if (parts.length > 2) {
        raw = parts[0] + "." + parts[1];
    }

    let [whole, decimal] = raw.split(".");
    whole = whole || "0";
    decimal = decimal ? decimal.slice(0, 2) : "";

    let formatted = formatIndianNumber(whole);
    if (decimal) formatted += "." + decimal;

    input.value = formatted + "%";
}

function formatIndianNumber(numStr) {
    numStr = numStr.replace(/^0+/, "") || "0";
    let lastThree = numStr.slice(-3);
    let otherNumbers = numStr.slice(0, -3);
    if (otherNumbers !== "") {
        lastThree = "," + lastThree;
    }
    return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
}
