"use strict";

(function () {
    const selectors = {
        regular: "#unit_price",
        sale: "#sale_price",
        percentage: "#discount_percentage",
        discount: "#discount",
        discountType: "#discount_type",
        validation: "#sale_price_validation"
    };

    function normalizedAmount(value) {
        return Number(value.toFixed(8)).toString();
    }

    function updateSalePriceFields(showMessage) {
        const regularInput = document.querySelector(selectors.regular);
        const saleInput = document.querySelector(selectors.sale);
        const percentageInput = document.querySelector(selectors.percentage);
        const discountInput = document.querySelector(selectors.discount);
        const discountTypeInput = document.querySelector(selectors.discountType);
        const validation = document.querySelector(selectors.validation);

        if (!regularInput || !saleInput || !percentageInput || !discountInput || !discountTypeInput) {
            return true;
        }

        const regularPrice = Number(regularInput.value);
        const saleValue = saleInput.value.trim();
        const salePrice = Number(saleValue);
        let message = "";

        discountTypeInput.value = "amount";
        saleInput.max = regularPrice > 0 ? normalizedAmount(regularPrice) : "";

        if (saleValue === "") {
            discountInput.value = "0";
            percentageInput.value = "0";
        } else if (!Number.isFinite(salePrice) || salePrice <= 0) {
            message = saleInput.dataset.positiveMessage || "Sale Price must be greater than zero.";
            discountInput.value = "0";
            percentageInput.value = "0";
        } else if (Number.isFinite(regularPrice) && regularPrice > 0 && salePrice > regularPrice) {
            message = saleInput.dataset.greaterMessage || "Sale Price cannot be greater than Regular Price.";
            discountInput.value = "0";
            percentageInput.value = "0";
        } else if (Number.isFinite(regularPrice) && regularPrice > 0) {
            const discountAmount = Math.max(regularPrice - salePrice, 0);
            discountInput.value = normalizedAmount(discountAmount);
            percentageInput.value = discountAmount > 0
                ? String(Math.round((discountAmount / regularPrice) * 100))
                : "0";
        } else {
            discountInput.value = "0";
            percentageInput.value = "0";
        }

        saleInput.setCustomValidity(message);
        saleInput.classList.toggle("is-invalid", Boolean(message) && showMessage);
        if (validation) {
            validation.textContent = message;
            validation.classList.toggle("d-block", Boolean(message) && showMessage);
        }

        return message === "";
    }

    document.addEventListener("input", function (event) {
        if (event.target.matches(selectors.regular + ", " + selectors.sale)) {
            updateSalePriceFields(true);
        }
    });

    document.addEventListener("change", function (event) {
        if (event.target.matches(selectors.regular + ", " + selectors.sale)) {
            updateSalePriceFields(true);
        }
    });

    document.addEventListener("reset", function (event) {
        if (event.target.matches("#item_form, #product_form")) {
            window.setTimeout(function () {
                updateSalePriceFields(false);
            }, 0);
        }
    });

    document.addEventListener("submit", function (event) {
        if (!event.target.matches("#item_form, #product_form")) {
            return;
        }

        if (!updateSalePriceFields(true)) {
            event.preventDefault();
            event.stopImmediatePropagation();
            const submitButton = event.target.querySelector('[type="submit"]');
            if (submitButton) {
                submitButton.disabled = false;
            }
        }
    }, true);

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", function () {
            updateSalePriceFields(false);
        });
    } else {
        updateSalePriceFields(false);
    }
})();
