document.addEventListener('DOMContentLoaded', function() {
	
	// Aus wp_localize_script:
    const ts_amazon_image_nonce = BoxyfyPreisSettings.nonce;
    const ts_amazon_ajax_url    = BoxyfyPreisSettings.ajax_url;
    const ts_post_id            = BoxyfyPreisSettings.post_id;

    // Funktion, um Remove-Events an die Remove-Buttons zu binden
    function addRemoveImageEvent() {
        var removeButtons = document.getElementsByClassName('remove-image-button');
        Array.from(removeButtons).forEach(function(button) {
            button.addEventListener('click', function() {
                var imageId = this.getAttribute('data-image-id');
                var postId  = ts_post_id; // aus dem lokalisierten Script
                var successMessage = document.getElementById('price-success-message');
                var errorMessage   = document.getElementById('price-error-message');
                successMessage.innerHTML = '';
                errorMessage.innerHTML   = '';

                var xhr = new XMLHttpRequest();
                xhr.open('POST', ts_amazon_ajax_url, true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            var parentDiv = button.parentElement;
                            parentDiv.parentElement.removeChild(parentDiv);
                            successMessage.innerHTML = 'Bild erfolgreich entfernt.';
                        } else {
                            errorMessage.innerHTML = response.data.message;
                        }
                    }
                };
                xhr.send(
                    'action=boxyfy_remove_amazon_image' +
                    '&image_id=' + encodeURIComponent(imageId) +
                    '&post_id=' + postId +
                    '&nonce=' + ts_amazon_image_nonce
                );
            });
        });
    }

    // Klick-Event für den "Daten jetzt abrufen"-Button
    document.getElementById('fetch-amazon-data').addEventListener('click', function() {
        var asin         = document.getElementById('tsprodukt_asin_price').value;
        var fetchImages  = document.getElementById('tsprodukt_fetch_images').checked ? 1 : 0;
        var successMessage = document.getElementById('price-success-message');
        var errorMessage   = document.getElementById('price-error-message');
        var currentPrice   = document.getElementById('current-price');
        successMessage.innerHTML = '';
        errorMessage.innerHTML   = '';

        if (asin) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', ts_amazon_ajax_url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        successMessage.innerHTML = 'Amazon-Daten erfolgreich abgerufen und gespeichert.';
                        var newHtml = '<strong>Aktueller Preis:</strong> ' + response.data.price;
                        if (response.data.savingBasis && response.data.savingBasis !== 'N/A') {
                            newHtml += '<br><strong>UVP:</strong> ' + response.data.savingBasis;
                        }
                        currentPrice.innerHTML = newHtml;
                        document.getElementById('tsprodukt_asin_price').value = asin;
                        if (response.data.image_ids && response.data.image_urls) {
                            var imagesGallery = document.getElementById('amazon-images-gallery');
                            imagesGallery.innerHTML = '';
                            response.data.image_ids.forEach(function(image_id, index) {
                                var image_url = response.data.image_urls[index];
                                var div = document.createElement('div');
                                div.className = 'amazon-image-item';
                                div.setAttribute('data-image-id', image_id);
                                div.innerHTML = '<img src="' + image_url + '" width="90" height="90" />' +
                                    '<button type="button" class="remove-image-button" data-image-id="' + image_id + '">X</button>';
                                imagesGallery.appendChild(div);
                            });
                            addRemoveImageEvent();
                        }
                    } else {
                        errorMessage.innerHTML = response.data.message;
                    }
                }
            };
            xhr.send(
                'action=boxyfy_fetch_amazon_data' +
                '&asin=' + encodeURIComponent(asin) +
                '&fetch_images=' + fetchImages +
                '&post_id=' + ts_post_id +
                '&nonce=' + ts_amazon_image_nonce
            );
        } else {
            errorMessage.innerHTML = 'Bitte geben Sie eine ASIN ein.';
        }
    });

    addRemoveImageEvent();
});