document.addEventListener('DOMContentLoaded', function () {
    const logsBody = document.getElementById('logs_body');

    // Loads and renders tracking log entries from Chrome local storage
    function renderLogs() {
        chrome.storage.local.get(['domain', 'tracking_log'], function (storageData) {
            const domain = storageData['domain'] || 'com';
            const trackingLog = storageData['tracking_log'] || [];

            logsBody.innerHTML = '';

            // Render rows in reverse chronological order
            trackingLog.reverse().forEach(function (logEntry, index) {
                const row = document.createElement('tr');

                // Store metadata in data attributes
                row.dataset.index = index;
                row.dataset.itemNumber = logEntry.ebayItemData.itemNumber || '';
                row.dataset.customLabel = logEntry.ebayItemData.customLabel || '';
                row.dataset.statusMessage = logEntry.statusMessage || '';
                row.dataset.entryTime = logEntry.entry_time || '';

                // --- Image cell ---
                const imageCell = document.createElement('td');
                if (logEntry.ebayItemData.photos) {
                    const ebayLink = document.createElement('a');
                    ebayLink.href = 'https://www.ebay.' + domain + '/itm/' + logEntry.ebayItemData.itemNumber;
                    ebayLink.target = '_blank';

                    const img = document.createElement('img');
                    img.src = logEntry.ebayItemData.photos;
                    img.alt = logEntry.ebayItemData.title || 'Item Image';
                    img.width = 50;

                    ebayLink.appendChild(img);
                    imageCell.appendChild(ebayLink);
                } else {
                    imageCell.textContent = 'No Image';
                }
                row.appendChild(imageCell);

                // --- Title cell ---
                const titleCell = document.createElement('td');
                titleCell.textContent = logEntry.ebayItemData.title || 'N/A';
                row.appendChild(titleCell);

                // --- Custom Label / Amazon link cell ---
                const labelCell = document.createElement('td');
                if (logEntry.ebayItemData.customLabel) {
                    let asin = '';
                    try {
                        // Custom label is Base64-encoded — decode it to get the Amazon ASIN
                        asin = atob(logEntry.ebayItemData.customLabel.trim());
                    } catch (e) {
                        console.error('Invalid Base64 string in customLabel:', logEntry.ebayItemData.customLabel);
                        asin = 'Invalid Label';
                    }

                    const amazonLink = document.createElement('a');
                    amazonLink.href = 'https://www.amazon.' + domain + '/dp/' + asin + '/?th=1&psc=1';
                    amazonLink.target = '_blank';
                    amazonLink.textContent = asin;
                    labelCell.appendChild(amazonLink);
                } else {
                    labelCell.textContent = 'N/A';
                }
                row.appendChild(labelCell);

                // --- Status message cell ---
                const statusCell = document.createElement('td');
                statusCell.innerHTML = logEntry.statusMessage || '';
                row.appendChild(statusCell);

                // --- Entry time cell ---
                const timeCell = document.createElement('td');
                timeCell.textContent = logEntry.entry_time || '';
                row.appendChild(timeCell);

                // --- Delete button cell ---
                const deleteCell = document.createElement('td');
                const deleteButton = document.createElement('button');
                deleteButton.textContent = 'Delete';
                deleteButton.dataset.index = index;
                deleteButton.addEventListener('click', handleDelete);
                deleteCell.appendChild(deleteButton);
                row.appendChild(deleteCell);

                logsBody.appendChild(row);
            });
        });
    }

    // Deletes a single log entry by its index in storage
    function handleDelete(event) {
        const index = event.target.dataset.index;
        chrome.storage.local.get('tracking_log', function (storageData) {
            const trackingLog = storageData['tracking_log'] || [];
            trackingLog.splice(index, 1);
            chrome.storage.local.set({ tracking_log: trackingLog }, function () {
                renderLogs();
            });
        });
    }

    // Clears all logs after confirmation
    document.getElementById('clear_logs').addEventListener('click', function () {
        if (confirm('Are you sure you want to clear all logs?')) {
            chrome.storage.local.remove('tracking_log', function () {
                renderLogs();
            });
        }
    });

    // Initial render on page load
    renderLogs();
});



