// ==UserScript==
// @name         Sesemanhua Image Downloader
// @namespace    https://www.sesemanhua.com/
// @version      0.1
// @description  Download images from sesemanhua chapter pages and rename them based on chapter number or title.
// @match        https://www.sesemanhua.com/*
// @grant        GM_xmlhttpRequest
// @require      https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js
// @require      https://cdn.jsdelivr.net/npm/@cloudflare/workers/client@latest/dist/workers-client.min.js
// ==/UserScript==

(async () => {
    'use strict';

    const style = document.createElement('style');
    style.textContent = `
        .status-bar-item {
            display: flex;
            align-items: center;
            margin-bottom: 0px;
            font-size: 10px;
        }
        .status-bar-item .chapter-title {
            width: 200px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .status-bar-item .progress-bar {
            width: 170px;
            height: 5px;
            border-radius: 1px;
            overflow: hidden;
        }
        .status-bar-item .percentage {
            width: 30px;
            text-align: right;
        }
        .download-all-button {
            font-size: 10px;
            margin: 5px;
            padding: 5px;
            color: white;
            background-color: #336699;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    `;
    document.head.appendChild(style);

    const chapterLinkElements = document.querySelectorAll('.j-chapter-link');
    const chapterNumbers = new Set();
    let maxChapterNumber = 0;
    const downloadingFiles = new Map();

    function createStatusBarContainer() {
        const statusBarContainer = document.createElement('div');
        statusBarContainer.id = 'status-bar-container';
        statusBarContainer.style.position = 'fixed';
        statusBarContainer.style.bottom = '0px';
        statusBarContainer.style.right = '70px';
        statusBarContainer.style.backgroundColor = 'rgba(51, 102, 153, 1)';
        statusBarContainer.style.color = 'white';
        statusBarContainer.style.fontSize = '10px';
        statusBarContainer.style.padding = '5px';
        statusBarContainer.style.borderRadius = '5px';
        statusBarContainer.style.width = '350px';
        statusBarContainer.style.maxHeight = '300px';
        statusBarContainer.style.overflowY = 'auto';
        statusBarContainer.style.display = 'none';
        document.body.appendChild(statusBarContainer);
    }

    function showStatusBar() {
        const statusBarContainer = document.getElementById('status-bar-container');
        statusBarContainer.style.display = 'block';
    }

    function hideStatusBar() {
        const statusBarContainer = document.getElementById('status-bar-container');
        if (statusBarContainer.children.length === 0) {
            statusBarContainer.style.display = 'none';
        }
    }

    function addStatusBarEntry(chapterTitle) {
        showStatusBar();
        const statusBarContainer = document.getElementById('status-bar-container');
        const statusBarItem = document.createElement('div');
        statusBarItem.className = 'status-bar-item';
        statusBarItem.innerHTML = `
            <span class="chapter-title">${chapterTitle}</span>
            <progress class="progress-bar" value="0" max="100"></progress>
            <span class="percentage">0%</span>
        `;
        statusBarContainer.appendChild(statusBarItem);
        return statusBarItem.querySelector('.progress-bar');
    }

    function removeStatusBarEntry(chapterTitle) {
        const statusBarContainer = document.getElementById('status-bar-container');
        const statusItems = statusBarContainer.children;
        for (let i = 0; i < statusItems.length; i++) {
            if (statusItems[i].querySelector('span').textContent === chapterTitle) {
                statusBarContainer.removeChild(statusItems[i]);
                break;
            }
        }
        hideStatusBar();
    }

    function updateOverallProgress(progressBar, downloadedImages, totalImages) {
        const percentage = Math.round((downloadedImages / totalImages) * 100);
        progressBar.value = percentage;
        const statusBarItem = progressBar.closest('.status-bar-item');
        statusBarItem.querySelector('.percentage').textContent = `${percentage}%`;
    }

    // Calculate maxChapterNumber based on chapter titles
    chapterLinkElements.forEach(linkElement => {
        const chapterTitle = linkElement.textContent.trim();
        const chapterNumberMatch = chapterTitle.match(/第(\d+)话/);

        if (chapterNumberMatch) {
            const chapterNumber = parseInt(chapterNumberMatch[1]);
            maxChapterNumber = Math.max(maxChapterNumber, chapterNumber);
        }
    });

    // Handle downloads and button creation for each chapter
    chapterLinkElements.forEach(linkElement => {
        const chapterTitle = linkElement.textContent.trim();
        const chapterUrl = linkElement.getAttribute('href');

        const chapterNumberMatch = chapterTitle.match(/第(\d+)话/);
        let chapterIdentifier;
        if (chapterNumberMatch) {
            chapterIdentifier = chapterNumberMatch[1];
        } else if (chapterTitle.includes('最终话')) {
            chapterIdentifier = (maxChapterNumber + 1).toString();
        } else {
            chapterIdentifier = chapterTitle;
        }

        const isNoNumber = !chapterNumberMatch && !chapterTitle.includes('最终话');
        const isDuplicate = chapterNumbers.has(chapterIdentifier);

        if (!isNoNumber && !isDuplicate) {
            chapterNumbers.add(chapterIdentifier);
        }

        const downloadButton = document.createElement('button');
        downloadButton.className = 'download-button';
        downloadButton.innerText = 'Download';
        downloadButton.style.cssText = `
            font-size: 8px;
            position: absolute;
            padding: 2px;
            color: white;
            z-index: 10;
            cursor: pointer;
            opacity: 0.9;
            border-radius: 5px;
            border: 1px solid ${isNoNumber ? '#bbbbbb' : (isDuplicate ? '#336699' : '#f92672')};
            background-color: ${isNoNumber ? '#bbbbbb' : (isDuplicate ? '#ea465a' : '#336699')};
        `;

        downloadButton.addEventListener('click', async function() {
            await triggerDownload(chapterTitle, chapterUrl, chapterIdentifier);
        });

        linkElement.parentNode.appendChild(downloadButton);
    });

    function createDownloadAllButtons() {
        const comicTitle = document.querySelector('div.comic-handles.clearfix');
        const redDownloadAllButton = document.createElement('button');
        const blueDownloadAllButton = document.createElement('button');

        redDownloadAllButton.className = 'download-all-button';
        redDownloadAllButton.style.backgroundColor = '#f92672'; // Red color
        redDownloadAllButton.textContent = 'Download All Red';
        redDownloadAllButton.addEventListener('click', () => {
            // Simulate clicking all red download buttons
            chapterLinkElements.forEach(linkElement => {
                const downloadButton = linkElement.querySelector('.download-button');
                if (downloadButton && downloadButton.style.backgroundColor === 'rgb(234, 70, 90)') {
                    downloadButton.click();
                }
            });
        });

        blueDownloadAllButton.className = 'download-all-button';
        blueDownloadAllButton.style.backgroundColor = '#336699'; // Blue color
        blueDownloadAllButton.textContent = 'Download All Blue';
        blueDownloadAllButton.addEventListener('click', () => {
            // Simulate clicking all blue download buttons
            chapterLinkElements.forEach(linkElement => {
                const downloadButton = linkElement.querySelector('.download-button');
                if (downloadButton && downloadButton.style.backgroundColor === 'rgb(51, 102, 153)') {
                    downloadButton.click();
                }
            });
        });

        if (comicTitle) {
            comicTitle.appendChild(redDownloadAllButton);
            comicTitle.appendChild(blueDownloadAllButton);
        }
    }

    async function packChapterImages(chapterUrl, chapterIdentifier, zip) {
        const response = await fetch(chapterUrl);
        if (!response.ok) {
            throw new Error(`Could not fetch chapter page: ${response.statusText}`);
        }
        const html = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, "text/html");
        const images = doc.querySelectorAll('.rd-article__pic .lazy-read');

        for (const [index, img] of images.entries()) {
            const originalSrc = img.getAttribute('data-original');
            const dataIndex = img.parentElement.getAttribute('data-index') || index;

            try {
                const proxyUrl = `https://addroute.maestro1four1.workers.dev/?url=${encodeURIComponent(originalSrc)}`;
                const imageResponse = await fetch(proxyUrl);

                if (!imageResponse.ok || !imageResponse.body) {
                    throw new Error(`Failed to fetch ${originalSrc}: ${imageResponse.statusText}`);
                }

                const imageData = await imageResponse.blob();
                zip.file(`${chapterIdentifier}_${dataIndex}.jpg`, imageData);
            } catch (error) {
                console.error(`Failed to download ${originalSrc}: ${error}`);
            }
        }
    }

    async function triggerDownload(chapterTitle, chapterUrl, chapterIdentifier) {
        const downloadFilename = `${chapterIdentifier}.zip`;
        if (downloadingFiles.has(downloadFilename)) {
            console.log(`Already downloading ${downloadFilename}`);
            return;
        }

        const progressBar = addStatusBarEntry(chapterTitle);
        downloadingFiles.set(downloadFilename, { progressBar, downloadedImages: 0 });

        try {
            const zip = new JSZip();
            await packChapterImages(chapterUrl, chapterIdentifier, zip);
            const content = await zip.generateAsync({ type: "blob" });
            saveAs(content, downloadFilename);
        } catch (error) {
            console.error(`Error fetching images for ${chapterTitle}: ${error}`);
        } finally {
            removeStatusBarEntry(chapterTitle);
            downloadingFiles.delete(downloadFilename);
        }
    }

    function handleBeforeUnload(event) {
        event.preventDefault();
        return (event.returnValue = "Downloads are in progress. Are you sure you want to leave?");
    }

    createStatusBarContainer();
    createDownloadAllButtons();
})();

The download all for both and red buttons are not working.  Can you give me a possible solution to fix it?