/**
 * WooCommerce cart form field sync for customized designs.
 */
(function (global) {
    "use strict";

    global.IAPC = global.IAPC || {};

    var getForm = null;
    var eventsBound = false;

    function setField(name, value) {
        var form = getForm ? getForm() : null;
        var normalized = value || "";

        if (!form) {
            return;
        }

        var campo = form.querySelector('[name="' + name + '"]');

        if (!campo) {
            campo = document.createElement("input");
            campo.type = "hidden";
            campo.name = name;
            form.appendChild(campo);
        }

        campo.value = normalized;
    }

    function bindEvents(syncFn) {
        if (typeof syncFn !== "function" || eventsBound) {
            return;
        }

        eventsBound = true;

        document.addEventListener("pointerdown", function (e) {
            if (e.target.closest(".single_add_to_cart_button")) {
                syncFn();
            }
        }, true);

        document.addEventListener("click", function (e) {
            if (e.target.closest(".single_add_to_cart_button")) {
                syncFn();
            }
        }, true);

        var form = getForm ? getForm() : null;

        if (form) {
            form.addEventListener("submit", function () {
                syncFn();
            }, true);
        }

        if (typeof global.jQuery !== "undefined") {
            global.jQuery(global.document.body).on("adding_to_cart", function () {
                syncFn();
            });
        }
    }

    function init(options) {
        options = options || {};
        getForm = options.getForm || null;

        if (options.sync) {
            bindEvents(options.sync);
        }
    }

    global.IAPC.cartBridge = {
        init: init,
        setField: setField,
        bindEvents: bindEvents
    };
})(window);
