jQuery(function ($) {
    const i18n = typeof IAPC_ADMIN !== "undefined" ? IAPC_ADMIN : {};

    function iapcToggleProductImageRemove($input) {
        const target = $input.attr("id");
        const $removeBtn = $('.iapc-remove-product-image[data-target="' + target + '"]');
        const previewId = $removeBtn.data("preview");
        const $preview = previewId ? $("#" + previewId) : $();

        if ($input.val()) {
            $removeBtn.removeClass("is-inactive");
            if ($preview.length) {
                $preview.attr("src", $input.val()).show();
            }
        } else {
            $removeBtn.addClass("is-inactive");
            if ($preview.length) {
                $preview.attr("src", "").hide();
            }
        }
    }

    $(".iapc-product-image-input").each(function () {
        iapcToggleProductImageRemove($(this));
    });

    $(".iapc-upload-product-image").on("click", function (e) {
        e.preventDefault();

        const target = $(this).data("target");

        const frame = wp.media({
            title: i18n.selectProductImage || "Select product image",
            button: {
                text: i18n.useThisImage || "Use this image",
            },
            multiple: false,
        });

        frame.on("select", function () {
            const attachment = frame.state().get("selection").first().toJSON();
            const $input = $("#" + target);

            $input.val(attachment.url);
            iapcToggleProductImageRemove($input);

            if (window.iapcPrintAreaEditor && typeof window.iapcPrintAreaEditor.refreshFromImageField === "function") {
                window.iapcPrintAreaEditor.refreshFromImageField(target, attachment.url);
            }
        });

        frame.open();
    });

    $(".iapc-remove-product-image").on("click", function (e) {
        e.preventDefault();

        const target = $(this).data("target");
        const $input = $("#" + target);

        $input.val("");
        iapcToggleProductImageRemove($input);

        if (window.iapcPrintAreaEditor && typeof window.iapcPrintAreaEditor.refreshFromImageField === "function") {
            window.iapcPrintAreaEditor.refreshFromImageField(target, "");
        }
    });
});
