Clear your tracks on Facebook

(function() {
    const SCROLL_PAUSE_MS = 2000;
    const HIGHLIGHT_MS = 1000;
    const MENU_WAIT_MS = 1500; // Time to wait for the menu to appear after clicking action element

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function getActionElements() {
        const mainDiv = document.querySelector('div[role="main"]');
        if (!mainDiv) return [];
        return Array.from(mainDiv.querySelectorAll('[aria-label="Options d’action"]'));
    }

    function findDeleteOptions(menu) {
        const deleteKeywords = ['supprimer', 'delete', 'löschen', 'удалить', '삭제', 'déplacer dans la corbeille'];
        const menuItems = menu.querySelectorAll('[role="menuitem"], [role="button"]');
        const deleteItems = [];  // Initialize an array to store matching items
    
        for (const item of menuItems) {
            const span = item.querySelector('span');
            if (span && deleteKeywords.some(word => span.textContent.toLowerCase().includes(word))) {
                deleteItems.push(item);  // Add the matching item to the array
            }
        }
    
        return deleteItems;  // Return all matching items
    }

    async function highlightElements(elements) {
        if (!elements || elements.length === 0) return;
        
        for (const el of elements) {
            const originalStyle = el.style.cssText;
            el.style.border = '3px solid red';
            el.style.backgroundColor = 'yellow';
            await sleep(HIGHLIGHT_MS);
            el.style.cssText = originalStyle;
        }
    }

    async function handleModal() {
        // Wait for modal to appear (confirm deletion)
        const modal = document.querySelector('[role="dialog"]');
        console.log(modal)
        const deleteOptions = findDeleteOptions(modal);
        await highlightElements(deleteOptions);
        for (const option of deleteOptions) {option.click();}
    }

    async function deleteElement(actionElement) {
        // Click on the action element to open the menu
        actionElement.click();
        console.log('Clicked action element, waiting for menu to appear...');
        

        // Find the menu that appeared after clicking the action element inside the "main" element
        const mainDiv = await document.querySelector('div[role="main"]');
        if (!mainDiv) {
            console.warn('⚠️ Main div not found!');
            return false;
        }

        await sleep(MENU_WAIT_MS); // Wait for the menu to appear

        const menu = await document.querySelector('[role="menu"]');

        if (!menu) {
            console.warn('⚠️ Menu not found after waiting...');
            return false;
        }

        await sleep(MENU_WAIT_MS); // Wait for the menu to appear

        const deleteOptions = findDeleteOptions(menu);
        if (!deleteOptions) {
            console.warn('⚠️ Delete option not found in menu!');
            return false;
        }

        await sleep(MENU_WAIT_MS); // Wait for the menu to appear

        console.log('Found delete option, highlighting...');
        await highlightElements(deleteOptions);
        for (const option of deleteOptions) {option.click();}
        
        console.log('🗑️ Item selected for deletion!');

        await sleep(MENU_WAIT_MS); // Wait for the menu to appear

        // Handle potential modal confirmation
        await handleModal();

        return true; // Successfully deleted
    }

    async function run() {
        while (true) {
            console.log('Looking for action elements to delete...');
            const actionElements = getActionElements();
            console.log(`Found ${actionElements.length} action elements.`);

            if (actionElements.length === 0) {
                console.log('No more items to delete on the current page.');
                // No need to scroll if there are still elements to delete
                window.scrollTo(0, document.body.scrollHeight);
                await sleep(SCROLL_PAUSE_MS); // Wait for new items to load
                continue;
            }

            // Process elements in the current page
            for (const actionElement of actionElements) {
                const success = await deleteElement(actionElement);
                if (!success) {
                    console.warn('❌ Deletion failed, will retry next time...');
                }
                // Wait a bit before continuing to the next item
                await sleep(1000); // Add more time between deletions to avoid issues
            }
        }
    }

    run();
})();