document.addEventListener('DOMContentLoaded', async () => {
    await loadAndRenderCaptchas();

    document.getElementById('exportBtn').addEventListener('click', exportSolutions);

    document.getElementById('importBtn').addEventListener('click', () => {
        document.getElementById('fileInput').click();
    });

    document.getElementById('fileInput').addEventListener('change', async event => {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = async loadEvent => {
                try {
                    const imported = JSON.parse(loadEvent.target.result);
                    const existing = (await chrome.storage.local.get('solvedCaptchas')).solvedCaptchas || {};
                    Object.assign(existing, imported);
                    await chrome.storage.local.set({ solvedCaptchas: existing });
                    location.reload();
                } catch (err) {
                    console.error('Error reading JSON: ', err);
                }
            };
            reader.readAsText(file);
        }
    });

    document.getElementById('clearAllBtn').addEventListener('click', () => {
        if (confirm('Are you sure you want to delete all solutions?')) {
            chrome.storage.local.remove('solvedCaptchas', () => location.reload());
        }
    });
});

async function loadAndRenderCaptchas() {
    const solvedCaptchas = (await chrome.storage.local.get('solvedCaptchas')).solvedCaptchas || {};
    const container = document.getElementById('captchaContainer');

    console.log('solvedCaptchas', solvedCaptchas);

    Object.keys(solvedCaptchas).forEach(challengeKey => {
        const block = document.createElement('div');
        block.className = 'captchaBlock';

        const challengeHeading = document.createElement('h3');
        challengeHeading.textContent = 'Captcha Challenge:';

        const challengeImg = document.createElement('img');
        challengeImg.src = challengeKey;
        challengeImg.alt = 'Captcha Challenge';
        challengeImg.style.maxWidth = '100%';

        const solutionsHeading = document.createElement('h3');
        solutionsHeading.textContent = 'Captcha Solutions:';

        const imageList = document.createElement('div');
        imageList.className = 'imageList';

        solvedCaptchas[challengeKey].forEach((imgSrc, index) => {
            const img = document.createElement('img');
            img.src = imgSrc;
            img.dataset.index = index;
            img.style.width = '100px';
            img.addEventListener('click', () => {
                img.style.border = img.style.border === '2px solid red' ? 'none' : '2px solid red';
            });
            imageList.appendChild(img);
        });

        const deleteAllBtn = document.createElement('button');
        deleteAllBtn.textContent = 'Delete Entire Solution';
        deleteAllBtn.addEventListener('click', () => deleteEntireSolution(challengeKey));

        const deleteSelectedBtn = document.createElement('button');
        deleteSelectedBtn.textContent = 'Delete Selected Images';
        deleteSelectedBtn.addEventListener('click', () => {
            const selectedIndices = [];
            imageList.querySelectorAll('img').forEach(img => {
                if (img.style.border === '2px solid red') {
                    selectedIndices.push(img.dataset.index);
                }
            });
            // Sort descending so splicing doesn't shift remaining indices
            selectedIndices.sort((a, b) => b - a);
            deleteSelectedImages(selectedIndices, challengeKey);
        });

        block.appendChild(challengeHeading);
        block.appendChild(challengeImg);
        block.appendChild(solutionsHeading);
        block.appendChild(imageList);
        block.appendChild(deleteAllBtn);
        block.appendChild(deleteSelectedBtn);
        container.appendChild(block);
    });
}

async function deleteSelectedImages(indices, challengeKey) {
    alert('Deleting selected images', indices);
    chrome.storage.local.get('solvedCaptchas', data => {
        let solvedCaptchas = data.solvedCaptchas;
        indices.forEach(index => {
            solvedCaptchas[challengeKey].splice(index, 1);
        });
        if (solvedCaptchas[challengeKey].length === 0) {
            delete solvedCaptchas[challengeKey];
        }
        chrome.storage.local.set({ solvedCaptchas }, () => location.reload());
    });
}

function deleteSingleImage(challengeKey, index) {
    chrome.storage.local.get('solvedCaptchas', data => {
        let solvedCaptchas = data.solvedCaptchas;
        solvedCaptchas[challengeKey].splice(index, 1);
        if (solvedCaptchas[challengeKey].length === 0) {
            delete solvedCaptchas[challengeKey];
        }
        chrome.storage.local.set({ solvedCaptchas }, () => location.reload());
    });
}

function deleteEntireSolution(challengeKey) {
    chrome.storage.local.get('solvedCaptchas', data => {
        let solvedCaptchas = data.solvedCaptchas;
        delete solvedCaptchas[challengeKey];
        chrome.storage.local.set({ solvedCaptchas }, () => location.reload());
    });
}

function exportSolutions() {
    chrome.storage.local.get('solvedCaptchas', data => {
        const json = JSON.stringify(data.solvedCaptchas, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'solvedCaptchas.json';
        a.click();
    });
}



