(async function scrollToCommentsAndExpandReplies() {

    function getCommentSection() {

        return document.querySelector('ytd-comments#comments');

    }


    function getTotalComments() {

        let totalCommentsElement = document.querySelector('h2#count yt-formatted-string');

        return totalCommentsElement ? totalCommentsElement.innerText.trim() : "Unknown";

    }


    async function scrollSmoothlyToComments() {

        return new Promise((resolve) => {

            let scrollInterval = setInterval(() => {

                let commentSection = getCommentSection();

                if (commentSection && commentSection.getBoundingClientRect().top < window.innerHeight) {

                    clearInterval(scrollInterval);

                    resolve();

                } else {

                    window.scrollBy(0, 30);

                }

            }, 150);

        });

    }


    async function waitForCommentsToLoad() {

        return new Promise(resolve => {

            let checkInterval = setInterval(() => {

                if (document.querySelectorAll('ytd-comment-thread-renderer').length > 0) {

                    clearInterval(checkInterval);

                    resolve();

                }

            }, 500);

        });

    }


    function getCommentThreads() {

        return [...document.querySelectorAll('ytd-comment-thread-renderer')];

    }


    async function smoothScrollToElement(element) {

        return new Promise((resolve) => {

            let scrollInterval = setInterval(() => {

                let rect = element.getBoundingClientRect();

                if (rect.top < window.innerHeight / 2 && rect.bottom > 0) {

                    clearInterval(scrollInterval);

                    resolve();

                } else {

                    window.scrollBy(0, 30);

                }

            }, 100);

        });

    }


    async function scrollToEndOfThread(threadElement) {

        return new Promise((resolve) => {

            let scrollInterval = setInterval(() => {

                let rect = threadElement.getBoundingClientRect();

                if (rect.bottom < window.innerHeight) {

                    clearInterval(scrollInterval);

                    resolve();

                } else {

                    window.scrollBy(0, 30);

                }

            }, 100);

        });

    }


    async function expandRepliesForThread(threadElement) {

        const replySelector = 'ytd-button-renderer#more-replies button';

        const showMoreSelector = 'ytd-comment-replies-renderer ytd-button-renderer#more-replies button:not([disabled])';

        const ytNewShowMoreSelector = 'yt-button-shape button[aria-label="Show more replies"]';


        async function clickButtonUntilExpanded(selector) {

            let button;

            while ((button = threadElement.querySelector(selector)) && button.offsetParent !== null) {

                button.scrollIntoView({ behavior: "smooth", block: "center" });

                await new Promise(resolve => setTimeout(resolve, 500)); // Ensures click registers

                button.click();

                console.log(`✅ Clicked "${button.innerText || "Show More Replies"}"`);


                await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for replies to load

                await scrollToEndOfThread(threadElement);

            }

        }


        await clickButtonUntilExpanded(replySelector);

        await clickButtonUntilExpanded(showMoreSelector);

        await clickButtonUntilExpanded(ytNewShowMoreSelector);

        console.log("✅ All replies expanded for this thread.");

    }


    function highlightThread(threadElement) {

        document.querySelectorAll('.green-highlight').forEach(el => {

            el.style.outline = "";

            el.style.boxShadow = "";

            el.classList.remove("green-highlight");

        });


        threadElement.classList.add("green-highlight");

        threadElement.style.outline = "3px solid #00ff00";

        threadElement.style.boxShadow = "0px 0px 10px 3px rgba(0, 255, 0, 0.8)";

    }


    function showPopup(message) {

        let popup = document.getElementById("custom-popup");

        if (!popup) {

            popup = document.createElement("div");

            popup.id = "custom-popup";

            popup.style.position = "fixed";

            popup.style.top = "20px";

            popup.style.left = "50%";

            popup.style.transform = "translateX(-50%)";

            popup.style.background = "#00cc00";

            popup.style.color = "#ffffff";

            popup.style.padding = "15px";

            popup.style.fontSize = "18px";

            popup.style.borderRadius = "5px";

            popup.style.boxShadow = "0 0 10px rgba(0,0,0,0.2)";

            popup.style.zIndex = "9999";

            document.body.appendChild(popup);

        }

        popup.innerText = message;

        setTimeout(() => popup.remove(), 5000);

    }


    async function slowlyScrollDown() {

        return new Promise((resolve) => {

            let scrollInterval = setInterval(() => {

                window.scrollBy(0, 2); // **Smooth scrolling down at 2px per second**

                if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {

                    clearInterval(scrollInterval);

                    resolve();

                }

            }, 1000);

        });

    }


    function generateRandomReply() {

        const replies = [

            "Great comment!",

            "I agree with you.",

            "Interesting point.",

            "Nice perspective.",

            "Thanks for sharing.",

            "I like your view.",

            "Well said.",

            "Good insight.",

            "I appreciate your input.",

            "That's a good point."

        ];

        return replies[Math.floor(Math.random() * replies.length)];

    }


    async function processCommentThread(threadElement) {

        highlightThread(threadElement);

        await smoothScrollToElement(threadElement);

        await expandRepliesForThread(threadElement);


        // Check the number of replies

        let replyCount = 0;

        const replyElements = threadElement.querySelectorAll("ytd-button-renderer#more-replies span.yt-core-attributed-string");

        if (replyElements.length > 0) {

            const replyText = replyElements[0].textContent.trim();

            const match = replyText.match(/\d+/);

            replyCount = match ? parseInt(match[0], 10) : 0;

        }


        console.log(`✅ Current Comment Reply Count: ${replyCount} replies`);


        const replyButtons = Array.from(threadElement.querySelectorAll('button[aria-label="Reply"]'));

        const commentBoxes = Array.from(threadElement.querySelectorAll('div#contenteditable-root[aria-label="Add a reply..."]'));

        const submitButtons = Array.from(threadElement.querySelectorAll('ytd-button-renderer#submit-button button[aria-label="Reply"]'));


        // Open comment boxes for single comments and replies

        for (let i = 0; i < Math.min(replyCount + 1, replyButtons.length); i++) {

            if (replyButtons[i]) {

                replyButtons[i].click();

                await new Promise(resolve => setTimeout(resolve, 200)); // Wait for box to open

            }


            if (commentBoxes[i]) {

                const randomReply = generateRandomReply();

                commentBoxes[i].innerText = randomReply; // Add comment

                commentBoxes[i].dispatchEvent(new Event('input', { bubbles: true }));

                commentBoxes[i].style.outline = "3px solid #00ff00";

                commentBoxes[i].style.boxShadow = "0px 0px 10px 3px rgba(0, 255, 0, 0.8)";

            }


            if (submitButtons[i] && !submitButtons[i].disabled) {

                submitButtons[i].click();

                await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for the reply to be submitted

            }


            // Clear the comment box for the next iteration

            if (commentBoxes[i]) {

                commentBoxes[i].innerText = ''; // Clear the comment box

            }

        }

    }


    console.log("📜 Scrolling to the comment section...");

    await scrollSmoothlyToComments();

    await waitForCommentsToLoad();


    let totalComments = getTotalComments();

    showPopup(`📢 YouTube\nTotal Comments: ${totalComments}\nProcessing all comment threads...`);


    let processedThreads = new Set();


    while (true) {

        let commentThreads = getCommentThreads();

        let newThreads = commentThreads.filter(thread => !processedThreads.has(thread));


        if (newThreads.length === 0) {

            console.log("✅ No new comment threads found. Stopping...");

            break;

        }


        for (let thread of newThreads) {

            await processCommentThread(thread);

            processedThreads.add(thread);

            showPopup(`✅ Processed ${processedThreads.size} threads.`);

        }


        console.log("🔽 Scrolling down slowly to load more comments...");

        await slowlyScrollDown();

    }


    console.log("✅ Finished processing all threads.");

    showPopup("✅ Done! All comment threads processed.");

})();

Comments