jQuery(function($) {


    function ensureModalsExist() {
        if (!$('#crate-result-modal').length) {
            $('body').append('<div id="crate-result-modal" class="hidden" role="dialog" aria-modal="true"><div class="modal-inner"><h2 id="crate-result-title">You got:</h2><div id="crate-result-item"></div><div id="crate-result-meta"></div><button id="crate-close-btn">Close</button></div></div>');
        }
    }

    window.openCrate = function(productId, onResult) {
        ensureModalsExist();

        var $resultModal = $('#crate-result-modal');
        var $resultItem = $('#crate-result-item');
		$('body').addClass('mysterx-processing');
        $.post(MYSTERX.ajax_url, {
            action: 'wc_open_box',
            product_id: productId,
            nonce: MYSTERX.nonce
        }, function(resp) {
			$('body').removeClass('mysterx-processing');
            if (!resp || !resp.success) {
                if (onResult) onResult(null);
                return;
            }
            var winItem = resp.data.item;
			var $countDisplay = $('.mysterx-boxes-left[data-product_id="' + productId + '"]');
			$countDisplay.text(resp.data.box_left_to_open_text);

			if (parseInt(resp.data.box_left_to_open) <= 0) {
				var $targetBtn = $('.open-box-button[data-product_id="' + productId + '"]');
				$targetBtn.fadeOut(400, function() {
					$(this).remove();
				});
			}
			$resultItem.html(`<div class="won-item"><img src="${winItem.image || ''}"><h3>${winItem.title}</h3></div>`);
			$resultModal.removeClass('hidden').fadeIn(400);
			if (onResult) onResult(winItem);
        }, 'json').fail(function() {
            $('body').removeClass('mysterx-processing');
            if (onResult) onResult(null);
        });
    };

    $(document).on('click', '.open-box-button', function(e) {
        e.preventDefault();
        var $btn = $(this);
		if ($btn.hasClass('is-loading')) return;
		$btn.addClass('is-loading').prop('disabled', true)
        if ($btn.data('opening')) return;
        $btn.data('opening', true).prop('disabled', true);
        window.openCrate($btn.data('product_id'), function() {
            $btn.data('opening', false).removeClass('is-loading').prop('disabled', false);
        });
    });

    $(document).on('click', '#crate-close-btn', function() {
        $('#crate-result-modal').fadeOut(300);
    });

	function getProductDataset(productId) {
        var el = document.getElementById('box-data-' + productId);
        if (el) {
            try { return JSON.parse(el.textContent); } catch (e) { console.warn('Invalid JSON for product', productId); }
        }
        return null;
    }

	$(document).on('click', '.view-all-rewards-link', function(e) {
            e.preventDefault();
            var productId = $(this).data('product_id') || $(this).closest('[data-product_id]').data('product_id');
            if (!productId) return alert('Product ID not found');

            var items = getProductDataset(productId);
            if (!items) return alert('Nema konfiguriranih nagrada za ovaj proizvod');

            // render u modal (isti markup koji koristiš)
            var $grid = $('#all-rewards-modal .reward-grid');
            $grid.empty();
            items.forEach(function(it) {
                var img = it.image || (window.WC_CRATES && WC_CRATES.assets_url ? WC_CRATES.assets_url + 'placeholder.png' : '');
                var rarity = it.rarity || (it.weight && it.weight > 50 ? 'common' : 'rare'); // fallback
                var soldOutClass = it.is_sold_out ? ' mysterx-sold-out' : '';
                var soldOutBadge = it.is_sold_out ? '<span class="mysterx-sold-out-badge">Gone</span>' : '';
                $grid.append('<div class="reward ' + rarity + soldOutClass + '">' + soldOutBadge + '<img src="' + img + '" alt="' + (it.title || '') + '"><div>' + (it.title || '') + '</div></div>');
            });
            $('#all-rewards-modal').removeClass('hidden');
        });

        $(document).on('click', '.close-modal, #all-rewards-modal', function(e) {
            if ($(e.target).is('.close-modal, #all-rewards-modal')) {
                $('#all-rewards-modal').addClass('hidden');
            }
        });
});
