window.plantshop_wc_effect = function (data) {
    const tab = data.tab;
    let url = new URL(location.href);
    url.searchParams.set("tab", tab);
    history.pushState({}, null, url.toString());

    const _wp_http_ref = document.querySelector(`[name='_wp_http_referer']`);
    url = new URL(`https://localhost${_wp_http_ref.value}`);
    url.searchParams.set("tab", tab);
    _wp_http_ref.value = url.toString().replace("https://localhost", "");
}

jQuery(function ($) {

    // Media uploader for company logo
    let mediaFrame = null;
    $(document).on('click', '.plantshop-wc-media-select', function (e) {
        e.preventDefault();
        const $wrap = $(this).closest('.plantshop-wc-media-field');
        const $input = $wrap.find('.plantshop-wc-media-input');
        const $preview = $wrap.find('.plantshop-wc-media-preview');

        if (!mediaFrame) {
            mediaFrame = wp.media({
                title: 'Select logo',
                button: {text: 'Use this logo'},
                multiple: false
            });
        }
        mediaFrame.off('select');
        mediaFrame.on('select', function () {
            const attachment = mediaFrame.state().get('selection').first().toJSON();
            $input.val(attachment.id);
            const url = attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;
            $preview.html('<img src="' + url + '" style="max-height:80px; max-width:240px; height:auto; width:auto;" />');
            $wrap.find('.plantshop-wc-media-remove').prop('disabled', false);
        });
        mediaFrame.open();
    });

    $(document).on('click', '.plantshop-wc-media-remove', function (e) {
        e.preventDefault();
        const $wrap = $(this).closest('.plantshop-wc-media-field');
        $wrap.find('.plantshop-wc-media-input').val('');
        $wrap.find('.plantshop-wc-media-preview').html('<em>No logo selected.</em>');
        $(this).prop('disabled', true);
    });

});