jQuery(document).ready(function ($) {
    const initialNumberOfItems = 3; // Change this to 6 for rendering 6 posts initially
    $('#load_more_rss').on('click', function (e) {
        e.preventDefault();
        const $this = $(this);
        const offset = $this.data('offset');
		const attributes = rssFeedAttr;
        $.ajax({
            url: artcloudAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'artcloud_load_more_rss',
                offset: offset,
                attributes: attributes, // Send the entire attributes array
                numberOfItems: initialNumberOfItems // Send initial item count for server-side logic
            },
            beforeSend: function () {
                $this.text('Ladataan...');
            },
            success: function (response) {
                const items = response;
                const $container = $('.container'); // Define $container here
                const $newItemsRow = $('#artcloud-rss-feed');

				items.forEach(item => {
					const itemDate = new Date(item.pubDate);
					const options = {
						timeZone: 'Europe/Helsinki',
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit',
						second: '2-digit',
						hour12: false
					};
					const formatter = new Intl.DateTimeFormat('en-US', options);
					const eetDateTime = formatter.format(itemDate);

					const $artcloudItem = $('<div class="artcloud-item col-4" style="backgroundcolor:' + attributes.backgroundColor + '"></div>');

					const $artcloudPostImg = $('<div class="artcloud-postImg"></div>');
					const $img = $('<img decoding="async" width="100%" height="252px" alt="">');
					$img.attr('src', item.enclosure['link']);
					$artcloudPostImg.append($img);

					const $artcloudContent = $('<div class="artcloud-content"></div>');
					$artcloudContent.append('<h6 style="color:' + attributes.textColor + '">' + formatDateTime(eetDateTime) + '</h6>');
					$artcloudContent.append('<a href="' + item.link + '"><h3 style="color:' + attributes.textColor + '">' + item.title.substring(0, 75) + '</h3></a>');
					$artcloudContent.append('<p>' + item.description.substring(0, 175) + '</p>');

					$artcloudItem.append($artcloudPostImg).append($artcloudContent);
					$newItemsRow.append($artcloudItem);
				});

				function formatDateTime(dateTimeString) {
					// Split date and time parts
					const [datePart, timePart] = dateTimeString.split(', ');
					// Reformat date to dd.mm.yyyy
					const [month, day, year] = datePart.split('/');
					const formattedDate = `${day.padStart(2, '0')}.${month.padStart(2, '0')}.${year}`;
					// Reformat time to hh:mm:ss
					const [hour, minute, second] = timePart.split(':');
					const formattedTime = `${hour.padStart(2, '0')}:${minute}:${second}`;
					// Combine formatted date, time, and time zone abbreviation
					return `${formattedDate} ${formattedTime} EET`;
				}

                // Check if new items are already appended
                $container.append($newItemsRow);
                if (items.length < initialNumberOfItems) {
                    $this.hide(); // Hide the "Load More" button if no more items
                }
                $this.data('offset', offset + initialNumberOfItems);
                $this.text('Näytä lisää');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('AJAX error:', textStatus, errorThrown);
                // alert('Failed to load more items.');
            }
        });
    });
});
