I am currently developing a Chrome extension similar to "OneTab" and "Better OneTab". I want you to understand the source code of the extension and help me modify it. Here is the code:

"""manifest.json
{
  "manifest_version": 3,
  "name": "Bookshelf",
  "version": "0.9",
  "description": "Store and manage your open tabs in a well-arranged bookshelf to save memory.",
  "permissions": [
    "tabs",
    "storage",
    "contextMenus"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_icon": {
      "16": "icons/icon16.png",
      "32": "icons/icon32.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    },
    "default_title": "Bookshelf"
  },
  "icons": {
    "16": "icons/icon16.png",
    "32": "icons/icon32.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "homepage_url": "https://your-extension-homepage.com"
}
"""

"""background.js
// Function to generate a unique ID
function generateUUID() {
  return crypto.randomUUID();
}

// Open extension page when its icon is clicked
chrome.action.onClicked.addListener(() => {
  chrome.tabs.create({ url: 'tabs.html' });
});

// Create context menu items when the extension is installed or updated
chrome.runtime.onInstalled.addListener(() => {
  // Menu items
  chrome.contextMenus.create({
    id: 'savePagesOnLeft',
    title: 'Save pages on the left',
    contexts: ['action']
  });

  chrome.contextMenus.create({
    id: 'savePagesOnRight',
    title: 'Save pages on the right',
    contexts: ['action']
  });

  chrome.contextMenus.create({
    id: 'saveOnlyThisPage',
    title: 'Save only this page',
    contexts: ['action']
  });

  chrome.contextMenus.create({
    id: 'saveAllPages',
    title: 'Save all pages',
    contexts: ['action']
  });

  chrome.contextMenus.create({
    id: 'saveAllPagesExceptThis',
    title: 'Save all pages except this',
    contexts: ['action']
  });
});

// Listen for clicks on context menu items
chrome.contextMenus.onClicked.addListener((info, currentTab) => {
  if (info.menuItemId === 'savePagesOnLeft') {
    savePagesOnLeft(currentTab);
  } else if (info.menuItemId === 'savePagesOnRight') {
    savePagesOnRight(currentTab);
  } else if (info.menuItemId === 'saveOnlyThisPage') {
    saveOnlyThisPage(currentTab);
  } else if (info.menuItemId === 'saveAllPages') {
    saveAllPages(currentTab);
  } else if (info.menuItemId === 'saveAllPagesExceptThis') {
    saveAllPagesExceptThis(currentTab);
  }
});

// Function to save pages on the left
function savePagesOnLeft(currentTab) {
  chrome.tabs.query({ currentWindow: true }, (tabs) => {
    savePages(tabs.filter(tab => (tab.index < currentTab.index) && (!tab.pinned) && tab.url.startsWith('http')));
  });
}

// Function to save pages on the right
function savePagesOnRight(currentTab) {
  chrome.tabs.query({ currentWindow: true }, (tabs) => {
    savePages(tabs.filter(tab => (tab.index > currentTab.index) && (!tab.pinned) && tab.url.startsWith('http')));
  });
}

// Function to save only the current page
function saveOnlyThisPage(currentTab) {
  if ((!currentTab.pinned) && currentTab.url.startsWith('http')) {
    savePages([currentTab]);
  }
}

// Function to save all pages
function saveAllPages(currentTab) {
  chrome.tabs.query({ currentWindow: true }, (tabs) => {
    savePages(tabs.filter(tab => (!tab.pinned) && tab.url.startsWith('http')));
  });
}

// Function to save all pages except current
function saveAllPagesExceptThis(currentTab) {
  chrome.tabs.query({ currentWindow: true }, (tabs) => {
    savePages(tabs.filter(tab => (tab.id !== currentTab.id) && (!tab.pinned) && tab.url.startsWith('http')));
  });
}

// Generic function to save pages
function savePages(tabs) {
  // Check if there are any pages to save
  if (tabs.length === 0) {
    console.log('No pages to save');
    return;
  }

  // Map the filtered tabs to get their title and URL for the pages
  const newPages = tabs.map(tab => ({
    id: generateUUID(),
    title: tab.title,
    url: tab.url
  }));

  // Retrieve bookshelf saved data to determine the default book title and save it
  chrome.storage.local.get('bookShelfData', (data) => {
    let bookShelfData = data.bookShelfData || [];

    // Generate default book title as 'Book X'
    let booksTot = bookShelfData.length + 1;
    let defaultBookTitle = 'Book ' + booksTot;

    // Ensure the book title is unique (deprecated)
    /*
    while (bookShelfData.some(book => book.title === defaultBookTitle)) {
      booksTot++;
      defaultBookTitle = 'Book ' + booksTot;
    }
    */

    // Add the new book to the beginning of the array
    const newBook = {
      id: generateUUID(),
      title: defaultBookTitle,
      pages: newPages,
      collapsed: false
    };
    bookShelfData.unshift(newBook);

    // Save the updated bookshelf data to storage
    chrome.storage.local.set({ 'bookShelfData': bookShelfData }, () => {
      console.log(`${newPages.length} page(s) saved under "${defaultBookTitle}"`);

      // Close the saved tabs
      chrome.tabs.remove(tabs.map(tab => tab.id));

      // Send a message to tabs.html to refresh the bookshelf
      chrome.runtime.sendMessage({ action: 'bookShelfUpdated' });
    });
  });
}
"""

"""tabs.html
<!DOCTYPE html>
<html>
<head>
    <title>Bookshelf</title>
    <script src="tabs.js" defer></script>
    <link rel="stylesheet" href="tabs.css">
</head>
<body>
    <!-- Main Header -->
    <header id="mainHeader">
        <div id="mainHeaderLeft">
            <a href="#" id="homePageLink">Bookshelf</a>
        </div>
        <div id="mainHeaderCenter">
            <input type="text" id="searchBar" placeholder="Search pages...">
        </div>
        <div id="mainHeaderRight">
            <!-- Theme Selector -->
            <select id="themeSelector" title="Select theme">
                <option value="">Light Theme 1</option>
                <option value="lightTheme2">Light Theme 2</option>
                <option value="darkTheme1">Dark Theme 1</option>
                <option value="darkTheme2">Dark Theme 2</option>
                <option value="darkTheme3">Dark Theme 3</option>
            </select>
            <!-- Settings Button -->
            <button id="settingsPageButton" title="Go to settings page">
                <img src="icons/gear_icon.png" alt="Go to settings page">
            </button>
        </div>
    </header>

    <!-- Main Body -->
    <div id="mainBody">
        <!-- Main Page -->
        <div id="mainPage">
            <p id="resultMessage">Loading your bookshelf...</p>
            <div id="bookShelf"></div>
        </div>

        <!-- Settings Page -->
        <div id="settingsPage" style="display: none;">
            <h2>Settings</h2>
            <p>Customize your Bookshelf settings here.</p>
        </div>
    </div>
</body>
</html>
"""

"""tabs.js
// Function to generate a unique ID
function generateUUID() {
    return crypto.randomUUID();
}

// Event listener for the DOM loaded
document.addEventListener('DOMContentLoaded', async () => {
    const homePageLink = document.getElementById('homePageLink');
    const searchBar = document.getElementById('searchBar');
    const themeSelector = document.getElementById('themeSelector');
    const settingsPageButton = document.getElementById('settingsPageButton');
    const mainPage = document.getElementById('mainPage');
    const settingsPage = document.getElementById('settingsPage');
    let bookShelfData = [];
    let bookShelfDataUpdated = false;
    let loadingBookShelfData = false;
    let pagesToMove = [];
    let bookIdOfMovingPages = '';

    // Get saved theme
    chrome.storage.local.get('themeSelected', (data) => {
        if (!data.themeSelected) data.themeSelected = '';

        document.body.className = data.themeSelected;

        themeSelector.value = data.themeSelected;  // Change select based on saved theme
    });

    // Get bookshelf saved data and display it
    await LoadBookShelfDataFromStorage();
    displayBookShelf();

    // Create a timer that check if there are bookshelf data to save
    let intervalId = setInterval(() => {
        if (bookShelfDataUpdated && !loadingBookShelfData) {
            chrome.storage.local.set({ 'bookShelfData': bookShelfData }, () => {
                // Check for errors
                if (chrome.runtime.lastError) {
                    console.error('Error setting storage:', chrome.runtime.lastError);

                    // TODO: Handle the error accordingly
                }
            });

            bookShelfDataUpdated = false;
        }
    }, 2000);

    // Event listener for messages from background.js
    chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
        if (message.action === 'bookShelfUpdated') {
            // Get new bookshelf data and repaint the DOM
            await LoadBookShelfDataFromStorage();
            displayBookShelf();
        }
    });

    // Event listener for the homepage link
    homePageLink.addEventListener('click', (event) => {
        event.preventDefault(); // Prevent default link behavior

        // Show the search bar
        searchBar.style.display = 'block';

        // Show main page and hide settings page
        mainPage.style.display = 'block';
        settingsPage.style.display = 'none';
    });

    // Event listener for the search bar
    searchBar.addEventListener('input', () => {
        // TODO: disable or enable (by settings) to move pages when filtering
        //    if(!settings.canMoveWhileFiltering) {
        //        pagesToMove = [];
        //        bookIdOfMovingPages = '';
        //    }

        // Repaint the DOM
        displayBookShelf();
    });

    // Event listener for the theme selector button
    themeSelector.addEventListener('change', function() {
        document.body.className = this.value;

        chrome.storage.local.set({ 'themeSelected': this.value });  // Save theme
    });

    // Event listener for the settings page button
    settingsPageButton.addEventListener('click', (event) => {
        event.preventDefault(); // Prevent default link behavior

        // Hide the search bar
        searchBar.style.display = 'none';

        // Hide main page and show settings page
        mainPage.style.display = 'none';
        settingsPage.style.display = 'block';
    });

    // Function to get bookshelf saved data from storage
    async function LoadBookShelfDataFromStorage() {
        loadingBookShelfData = true;
        const data = await chrome.storage.local.get('bookShelfData');
        bookShelfData = data.bookShelfData || [];
        loadingBookShelfData = false;
    }

    // Function to set bookshelf data to storage
    async function saveBookShelfDataToStorage() {
        bookShelfDataUpdated = true;  // bookshelf data has changed
    }

    // Get book element from ID
    function getBookElementById(bookId) {
        return document.querySelector(`.bookContainer[data-book-id="${bookId}"]`);
    }

    // Function to display bookshelf data on the main page
    function displayBookShelf() {
        const fragment = document.createDocumentFragment();  // Create fragment to minimizes the number of reflows and repaints
        const currentSearchQuery = searchBar.value.trim().toLowerCase();  // Get current filtering query
        const areThereAnyPagesToMove = (pagesToMove.length !== 0) && (bookShelfData.findIndex(book => book.id === bookIdOfMovingPages) !== -1);

        // Function to create the book checkbox
        function createBookCheckbox(bookId) {
            const bookCheckbox = document.createElement('input');
            bookCheckbox.type = 'checkbox';
            bookCheckbox.className = 'bookCheckbox';
            bookCheckbox.title = 'Select/Deselect All Pages in this Book';

            // Toggle all checkboxes in a book
            bookCheckbox.addEventListener('change', () => {
                const pageCheckboxes = getBookElementById(bookId).getAllPageCheckbox();

                pageCheckboxes.forEach((checkbox) => {
                    checkbox.checked = bookCheckbox.checked;
                });
            });

            return bookCheckbox;
        }

        // Function to create the book title
        function createBookTitle(bookTitle) {
            const bookTitleElem = document.createElement('h2');
            bookTitleElem.textContent = bookTitle;
            bookTitleElem.className = 'bookTitle';
            bookTitleElem.contentEditable = false;

            return bookTitleElem;
        }

        // Function to create the edit book title button
        function createEditBookTitleButton(bookId) {
            const editBookTitleButton = document.createElement('button');
            editBookTitleButton.textContent = 'Edit title';
            editBookTitleButton.title = 'Edit book title';
            editBookTitleButton.className = 'editBookTitleButton';
            editBookTitleButton.dataset.mode = 'edit';

            // Toggle between edit and save modes for the book title
            editBookTitleButton.addEventListener('click', () => {
                // Find the book index
                const bookIndex = bookShelfData.findIndex(book => book.id === bookId);
                if (bookIndex === -1) return;

                // Get HTML element
                const bookTitle = getBookElementById(bookId).getBookTitle();

                if (editBookTitleButton.dataset.mode === 'edit') {
                    // Switch to edit mode
                    bookTitle.contentEditable = true;
                    bookTitle.focus();

                    // Move cursor to the end of the text using Range and Selection APIs
                    if ((typeof window.getSelection != "undefined") && (typeof document.createRange != "undefined")) {
                        const range = document.createRange();
                        range.selectNodeContents(bookTitle);
                        range.collapse(false); // Collapse the range to the end

                        const selection = window.getSelection();
                        selection.removeAllRanges();
                        selection.addRange(range);
                    }

                    // Change button to 'Save'
                    editBookTitleButton.textContent = 'Save title';
                    editBookTitleButton.title = 'Save book title';
                    editBookTitleButton.dataset.mode = 'save';

                    // Handle Enter key to save
                    bookTitle.onkeypress = function(e) {
                        if (e.key === 'Enter') {
                            e.preventDefault(); // Prevent newline
                            editBookTitleButton.click(); // Save on Enter key
                        }
                    };
                } else {
                    // Switch to view mode (save changes)
                    const newTitle = bookTitle.textContent.trim();

                    if (newTitle === '') {
                        alert('Book title cannot be empty.');
                        bookTitle.focus();
                        return;
                    }

                    // Update the book title
                    bookShelfData[bookIndex].title = newTitle;

                    // Save the updated page books to storage
                    saveBookShelfDataToStorage();

                    // Disable contentEditable
                    bookTitle.contentEditable = false;

                    // Reset the edit button
                    editBookTitleButton.textContent = 'Edit title';
                    editBookTitleButton.title = 'Edit book title';
                    editBookTitleButton.dataset.mode = 'edit';

                    // Remove keypress handler
                    bookTitle.onkeypress = null;
                }
            });

            return editBookTitleButton;
        }

        // Function to create the restore book button
        function createRestoreBookButton(bookId) {
            const restoreBookButton = document.createElement('button');
            restoreBookButton.textContent = 'Restore';
            restoreBookButton.title = 'Restore this book';
            restoreBookButton.className = 'restoreBookButton';

            // Restore book pages
            restoreBookButton.addEventListener('click', () => {
                // Find the book by ID
                const book = bookShelfData.find(book => book.id === bookId);
                if (!book) return;

                // Restore pages
                book.pages.forEach(page => {
                    chrome.tabs.create({ url: page.url });
                });
            });

            return restoreBookButton;
        }

        // Function to create the remove book button
        function createRemoveBookButton(bookId) {
            const removeBookButton = document.createElement('button');
            removeBookButton.textContent = 'Remove';
            removeBookButton.title = 'Remove this book';
            removeBookButton.className = 'removeBookButton';

            removeBookButton.addEventListener('click', () => {
                removeBook(bookId);
            });

            return removeBookButton;
        }

        // Function to create a book header
        function createBookHeader(book) {
            const bookHeader = document.createElement('div');
            bookHeader.className = 'bookHeader';

            // Create children elements
            const bookCheckbox = createBookCheckbox(book.id);
            const bookTitle = createBookTitle(book.title);
            const editBookTitleButton = createEditBookTitleButton(book.id);
            const restoreBookButton = createRestoreBookButton(book.id);
            const removeBookButton = createRemoveBookButton(book.id);

            // Append elements to the header container in the desired order
            bookHeader.appendChild(bookCheckbox);
            bookHeader.appendChild(bookTitle);
            bookHeader.appendChild(editBookTitleButton);
            bookHeader.appendChild(restoreBookButton);
            bookHeader.appendChild(removeBookButton);

            // Create functions to retrieve nested elements
            bookHeader.getBookCheckbox = function() {return bookCheckbox;}
            bookHeader.getBookTitle = function() {return bookTitle;}

            // Add event listener
            bookHeader.addEventListener('click', (event) => {
                // Toggle book collapse/expand state
                if ((event.target === bookHeader) || ((event.target === bookTitle) && (editBookTitleButton.dataset.mode === 'edit'))) {
                    const bookId = book.id;

                    // Find the book index
                    const bookIndex = bookShelfData.findIndex(book => book.id === bookId);
                    if (bookIndex === -1) return;

                    // Get HTML elements
                    const bookContainer = getBookElementById(bookId);
                    const pagesList = bookContainer.getPagesList();
                    const bookFooter = bookContainer.getBookFooter();

                    // Toggle the display style
                    if (bookShelfData[bookIndex].collapsed) {
                        pagesList.style.display = 'grid';
                        bookFooter.style.display = 'flex';
                    } else {
                        pagesList.style.display = 'none';
                        bookFooter.style.display = 'none';
                    }
                    bookShelfData[bookIndex].collapsed ^= true;  // toggle value

                    // Save the updated bookShelfData
                    saveBookShelfDataToStorage();
                }
            });

            return bookHeader;
        }

        // Function to create the page checkbox
        function createPageCheckbox(bookId) {
            const pageCheckbox = document.createElement('input');
            pageCheckbox.type = 'checkbox';
            pageCheckbox.className = 'pageCheckbox';

            // Update the book checkbox state based on individual checkboxes
            pageCheckbox.addEventListener('change', () => {
                const bookContainer = getBookElementById(bookId);
                const bookCheckbox = bookContainer.getBookCheckbox();
                const pageCheckboxes = bookContainer.getAllPageCheckbox();

                const allChecked = Array.from(pageCheckboxes).every(checkbox => checkbox.checked);
                const anyChecked = Array.from(pageCheckboxes).some(checkbox => checkbox.checked);

                bookCheckbox.checked = allChecked;
                bookCheckbox.indeterminate = !allChecked && anyChecked;
            });

            return pageCheckbox;
        }

        // Function to create the page link
        function createPageLink(page) {
            const pageLink = document.createElement('a');
            pageLink.className = 'pageLink';
            pageLink.href = page.url;
            pageLink.textContent = page.title;
            pageLink.target = '_blank';

            return pageLink;
        }

        // Function to create the remove page button
        function createRemovePageButton(bookId, pageId) {
            const removePageButton = document.createElement('button');
            removePageButton.textContent = 'X';
            removePageButton.title = 'Remove this page';
            removePageButton.className = 'removePageButton';

            removePageButton.addEventListener('click', () => {
                // Find the book index
                const bookIndex = bookShelfData.findIndex(book => book.id === bookId);
                if (bookIndex === -1) return;

                // Find the page index
                const pageIndex = bookShelfData[bookIndex].pages.findIndex(page => page.id === pageId);
                if (pageIndex === -1) return;

                // Get HTML element
                const pagesList = getBookElementById(bookId).getPagesList();

                // Assert data compatibility
                if (!(pagesList.getAllPagesListItem().length === bookShelfData[bookIndex].pages.length)) {
                    console.assert(false, `Assert error when removing ${pageId} page in ${bookId} book`);
                    return;
                }

                // Remove page
                pagesList.removeChild(pagesList.children[pageIndex]);
                bookShelfData[bookIndex].pages.splice(pageIndex, 1);

                // Remove the book if no pages are left
                if (bookShelfData[bookIndex].pages.length === 0) {
                    removeBook(bookId);
                    return;
                }

                // Update pages count
                updatePageCount(bookId);

                // Save the updated bookShelfData
                saveBookShelfDataToStorage();
            });

            return removePageButton;
        }

        // Function to create a container for the page info and controls
        function createPageContainer(page, bookId, pageId) {
            const pageContainer = document.createElement('div');
            pageContainer.className = 'pageContainer';
            pageContainer.dataset.pageId = pageId;

            // Create children elements
            const pageCheckbox = createPageCheckbox(bookId);
            const pageLink = createPageLink(page);
            const removePageButton = createRemovePageButton(bookId, pageId);

            // Append elements to the container in the desired order
            pageContainer.appendChild(pageCheckbox);
            pageContainer.appendChild(pageLink);
            pageContainer.appendChild(removePageButton);

            // Create functions to retrieve nested elements
            pageContainer.getPageCheckbox = function() {return pageCheckbox;}

            return pageContainer;
        }

        // Function to create the "Move here" button
        function createMoveHereButton(bookId, pageId) {
            const moveHereButton = document.createElement('button');
            moveHereButton.textContent = 'Move here';
            moveHereButton.className = 'moveHereButton';
            moveHereButton.style.display = areThereAnyPagesToMove ? 'block' : 'none';

            // Move buffered pages inside a book
            moveHereButton.addEventListener('click', () => {
                if ((pagesToMove.length === 0) || (bookShelfData.findIndex(book => book.id === bookIdOfMovingPages) === -1)) return;

                // Find the book index
                let bookIndex = bookShelfData.findIndex(book => book.id === bookId);
                if (bookIndex === -1) return;

                // Find the page index
                let pageIndex = bookShelfData[bookIndex].pages.findIndex(page => page.id === pageId);
                if (pageIndex < 0) pageIndex = bookShelfData[bookIndex].pages.length;

                // Check if the pages we are moving have the same ID as those in the book
                let bookIds = new Set();
                let pageToAdd = JSON.parse(JSON.stringify(pagesToMove));  // Make a deep copy (NOTE: can be slow)
                do {
                    // Get book pages IDs
                    bookIds = new Set(bookShelfData[bookIndex].pages.map(page => page.id));

                    // Check for duplicated IDs
                    pageToAdd.forEach(page => {
                        if (bookIds.has(page.id)) {
                            page.id = generateUUID();  // generate new ID
                        }
                    });
                } while(pageToAdd.some(page => bookIds.has(page.id)));

                // Add pages
                bookShelfData[bookIndex].pages.splice(pageIndex, 0, ...pageToAdd);

                // Remove pages from previous book
                bookIndex = bookShelfData.findIndex(book => book.id === bookIdOfMovingPages);
                bookIds = new Set(pagesToMove.map(page => page.id));
                bookShelfData[bookIndex].pages = bookShelfData[bookIndex].pages.filter(page => !bookIds.has(page.id));

                // Remove the book if no pages are left
                if (bookShelfData[bookIndex].pages.length === 0) {
                    removeBook(bookIdOfMovingPages);
                }
                else {
                    // Update pages count
                    updatePageCount(bookIdOfMovingPages);
                }

                // Update pages count
                updatePageCount(bookId);

                // Clear the array and the book ID
                pagesToMove = [];
                bookIdOfMovingPages = '';

                // Save the updated bookShelfData
                saveBookShelfDataToStorage();

                // Repaint the DOM
                displayBookShelf();
            });

            return moveHereButton;
        }

        // Function to create a page list item
        function createPagesListItem(page, bookId, pageId) {
            const pagesListItem = document.createElement('li');
            pagesListItem.className = 'pagesListItem';
            pagesListItem.style.display = page.title.toLowerCase().includes(currentSearchQuery) ? 'grid' : 'none';

            // Create children elements
            const moveHereButton = createMoveHereButton(bookId, pageId);
            const pageContainer = createPageContainer(page, bookId, pageId);

            // Append elements to the item in the desired order
            pagesListItem.appendChild(moveHereButton);
            pagesListItem.appendChild(pageContainer);

            // Create functions to retrieve nested elements
            pagesListItem.getPageCheckbox = function() {return pageContainer.getPageCheckbox();}

            return pagesListItem;
        }

        // Function to create a pages list
        function createPagesList(book) {
            const pagesList = document.createElement('ul');
            pagesList.className = 'pagesList';
            pagesList.style.display = book.collapsed ? 'none' : 'grid';

            // Append elements to the pages list in the desired order
            book.pages.forEach((page) => {
                pagesList.appendChild(createPagesListItem(page, book.id, page.id));
            });

            // Create functions to retrieve nested elements
            pagesList.getAllPagesListItem = function() {return [...pagesList.children];}
            pagesList.getAllPageCheckbox = function() {
               const allPageCheckbox = [];
               pagesList.getAllPagesListItem().forEach(item => {
                   allPageCheckbox.push(item.getPageCheckbox());
               });

               return allPageCheckbox;
            };

            return pagesList;
        }

        // Function to create a move selected pages button
        function createMoveSelectedPagesButton(bookId) {
            const moveSelectedPagesButton = document.createElement('button');
            moveSelectedPagesButton.textContent = 'Move Selected Pages';
            moveSelectedPagesButton.className = 'moveSelectedPagesButton';
            moveSelectedPagesButton.disabled = areThereAnyPagesToMove && (bookIdOfMovingPages != bookId);
            moveSelectedPagesButton.style.textDecoration = moveSelectedPagesButton.disabled ? 'line-through' : 'none';

            // Add selected pages to a buffer
            moveSelectedPagesButton.addEventListener('click', () => {
                // Enable to move pages
                if (pagesToMove.length === 0) {
                    // Find the book by ID
                    const book = bookShelfData.find(book => book.id === bookId);
                    if (!book) return;

                    // Get HTML element
                    const pageCheckboxes = getBookElementById(bookId).getAllPageCheckbox();

                    // Assert data compatibility
                    if (!(pageCheckboxes.length === book.pages.length)) {
                        console.assert(false, `Assert error when moving selected pages in ${bookId} book`);
                        return;
                    }

                    // Collect the pages to move
                    pagesToMove = [];
                    pageCheckboxes.forEach((checkbox, checkboxIndex) => {
                        if (checkbox.checked) {
                            pagesToMove.push(book.pages[checkboxIndex]);
                        }
                    });

                    if (pagesToMove.length === 0) {
                        alert('Please select at least one page to move.');
                        return;
                    }

                    // Saves the book ID of the book where the pages to be moved were taken
                    bookIdOfMovingPages = bookId;

                    // Disable all the others moving buttons
                    var buttons = document.getElementsByClassName('moveSelectedPagesButton');
                    for (var i = 0; i < buttons.length; i++) {
                        if (buttons[i] !== moveSelectedPagesButton) {
                            buttons[i].disabled = true;
                            buttons[i].style.textDecoration = 'line-through';
                        }
                    }

                    // Remove bottom border from all the pages
                    var items = document.getElementsByClassName('pagesListItem');
                    for (var i = 0; i < items.length; i++) {
                        items[i].style.borderBottomWidth = '0px';
                    }

                    // Show all "Move here" buttons
                    var buttons = document.getElementsByClassName('moveHereButton');
                    for (var i = 0; i < buttons.length; i++) {
                        buttons[i].style.display = 'block';
                    }
                }
                // Disable to move pages
                else {
                    // Clear the array and the book ID
                    pagesToMove = [];
                    bookIdOfMovingPages = '';

                    // Enable all the others buttons
                    var buttons = document.getElementsByClassName('moveSelectedPagesButton');
                    for (var i = 0; i < buttons.length; i++) {
                        if (buttons[i] !== moveSelectedPagesButton) {
                            buttons[i].disabled = false;
                            buttons[i].style.textDecoration = 'none';
                        }
                    }

                    // Add bottom border in all the pages
                    var items = document.getElementsByClassName('pagesListItem');
                    for (var i = 0; i < items.length; i++) {
                        items[i].style.borderBottomWidth = '1px';
                    }

                    // Hide all "Move here" buttons
                    var buttons = document.getElementsByClassName('moveHereButton');
                    for (var i = 0; i < buttons.length; i++) {
                        buttons[i].style.display = 'none';
                    }
                }
            });

            return moveSelectedPagesButton;
        }

        // Function to create a restore selected pages button
        function createRestoreSelectedPagesButton(bookId) {
            const restoreSelectedPagesButton = document.createElement('button');
            restoreSelectedPagesButton.textContent = 'Restore Selected Pages';
            restoreSelectedPagesButton.className = 'restoreSelectedPagesButton';

            // Restore selected pages from a book
            restoreSelectedPagesButton.addEventListener('click', () => {
                // Find the book by ID
                const book = bookShelfData.find(book => book.id === bookId);
                if (!book) return;

                // Get HTML elements
                const pageCheckboxes = getBookElementById(bookId).getAllPageCheckbox();

                // Assert data compatibility
                if (!(pageCheckboxes.length === book.pages.length)) {
                    console.assert(false, `Assert error when restoring selected pages in ${bookId} book`);
                    return;
                }

                // Collect the pages to restore
                const pagesToRestore = [];
                pageCheckboxes.forEach((checkbox, checkboxIndex) => {
                    if (checkbox.checked) {
                        pagesToRestore.push(book.pages[checkboxIndex]);
                    }
                });

                if (pagesToRestore.length === 0) {
                    alert('Please select at least one page to restore.');
                    return;
                }

                // Confirm restoration
                if (!confirm(`Are you sure you want to restore ${pagesToRestore.length} selected page(s)?`)) {
                    return;
                }

                // Restore the selected pages by creating new pages in the browser
                pagesToRestore.forEach(page => {
                    chrome.tabs.create({ url: page.url });
                });
            });

            return restoreSelectedPagesButton;
        }

        // Function to create a remove selected pages button
        function createRemoveSelectedPagesButton(bookId) {
            const removeSelectedPagesButton = document.createElement('button');
            removeSelectedPagesButton.textContent = 'Remove Selected Pages';
            removeSelectedPagesButton.className = 'removeSelectedPagesButton';

            // Remove selected pages from a book
            removeSelectedPagesButton.addEventListener('click', () => {
                // Find the book index
                const bookIndex = bookShelfData.findIndex(book => book.id === bookId);
                if (bookIndex === -1) return;

                // Get HTML elements
                const bookContainer = getBookElementById(bookId);
                const pagesList = bookContainer.getPagesList();
                const pageCheckboxes = pagesList.getAllPageCheckbox();

                // Assert data compatibility
                if (!(pageCheckboxes.length === bookShelfData[bookIndex].pages.length)) {
                    console.assert(false, `Assert error when removing selected pages in ${bookId} book`);
                    return;
                }

                // Collect the indices of pages to remove
                const indicesToRemove = [];
                pageCheckboxes.forEach((checkbox, checkboxIndex) => {
                    if (checkbox.checked) {
                        indicesToRemove.push(checkboxIndex);
                    }
                });

                if (indicesToRemove.length === 0) {
                    alert('Please select at least one page to remove.');
                    return;
                }

                // Confirm to remove the pages
                if (!confirm('Are you sure you want to remove the selected pages?')) {
                    return;
                }

                // Remove pages starting from the highest index to avoid index shifting
                indicesToRemove.sort((a, b) => b - a).forEach((pageIndex) => {
                    pagesList.removeChild(pagesList.children[pageIndex]);
                    bookShelfData[bookIndex].pages.splice(pageIndex, 1);
                });

                // Remove the book if no pages are left
                if (bookShelfData[bookIndex].pages.length === 0) {
                    removeBook(bookId);
                    return;
                }

                // Update pages count
                updatePageCount(bookId);

                // Save the updated bookShelfData
                saveBookShelfDataToStorage();
            });

            return removeSelectedPagesButton;
        }

        // Function to create a pages count
        function createPagesCount(bookPagesLength) {
            const pagesCount = document.createElement('h2');
            pagesCount.textContent = `${bookPagesLength} Page${bookPagesLength !== 1 ? 's' : ''}`;
            pagesCount.className = 'pagesCount';

            return pagesCount;
        }

        // Function to create a book footer
        function createBookFooter(book) {
            // Function to create a book footer
            const bookFooter = document.createElement('div');
            bookFooter.className = 'bookFooter';
            bookFooter.style.display = book.collapsed ? 'none' : 'flex';

            // Create children elements
            const moveSelectedPagesButton = createMoveSelectedPagesButton(book.id);
            const restoreSelectedPagesButton = createRestoreSelectedPagesButton(book.id);
            const removeSelectedPagesButton = createRemoveSelectedPagesButton(book.id);
            const pagesCount = createPagesCount(book.pages.length);

            // Append elements to the footer in the desired order
            bookFooter.appendChild(moveSelectedPagesButton);
            bookFooter.appendChild(restoreSelectedPagesButton);
            bookFooter.appendChild(removeSelectedPagesButton);
            bookFooter.appendChild(pagesCount);

            // Create functions to retrieve nested elements
            bookFooter.getPagesCount = function() {return pagesCount;}

            return bookFooter;
        }

        // Function to create a container for the book info and controls
        function createBookContainer(book) {
            const bookContainer = document.createElement('div');
            bookContainer.className = 'bookContainer';
            bookContainer.dataset.bookId = book.id;

            // Create children elements
            const bookHeader = createBookHeader(book);
            const pagesList = createPagesList(book);
            const moveHereButton = createMoveHereButton(book.id, '');
            const bookFooter = createBookFooter(book);

            // Append elements to the container in the desired order
            bookContainer.appendChild(bookHeader);
            bookContainer.appendChild(pagesList);
            bookContainer.appendChild(moveHereButton);
            bookContainer.appendChild(bookFooter);

            // Create functions to retrieve nested elements
            bookContainer.getBookCheckbox = function() {return bookHeader.getBookCheckbox();}
            bookContainer.getBookTitle = function() {return bookHeader.getBookTitle();}
            bookContainer.getPagesList = function() {return pagesList;}
            bookContainer.getAllPageCheckbox = function() {return pagesList.getAllPageCheckbox();}
            bookContainer.getAllPagesListItem = function() {return pagesList.getAllPagesListItem();}
            bookContainer.getBookFooter = function() {return bookFooter;}
            bookContainer.getPagesCount = function() {return bookFooter.getPagesCount();}

            // Show or hide the book based on whether any pages are visible
            bookContainer.style.display = Object.values(bookContainer.getAllPagesListItem()).some(item => item.style.display === 'grid') ? 'grid': 'none';

            return bookContainer;
        }

        // Create the elements based on the data
        bookShelfData.forEach((book) => {
            fragment.appendChild(createBookContainer(book));
        });

        // Clear existing content and append the fragment to display the data
        const bookShelf = document.getElementById('bookShelf');
        bookShelf.innerHTML = '';
        bookShelf.appendChild(fragment);

        // Display a message if no pages match
        displayResultMessage();
    }

    // Function to update pages count
    function updatePageCount(bookId) {
        // Get book
        const book = bookShelfData.find(book => book.id === bookId);
        if (!book) return;

        // Get HTML elements
        const pagesCount = getBookElementById(bookId).getPagesCount();

        // Change text
        pagesCount.textContent = `${book.pages.length} Page${book.pages.length !== 1 ? 's' : ''}`;
    }

    // Function to remove an entire page book
    function removeBook(bookId) {
        // Find the book index
        const bookIndex = bookShelfData.findIndex(book => book.id === bookId);
        if (bookIndex === -1) return;

        // Get HTML element
        const bookContainer = getBookElementById(bookId);
        if (!bookContainer) return;

        // Remove the book
        bookContainer.parentElement.removeChild(bookContainer);
        bookShelfData.splice(bookIndex, 1);

        // Display a message if there are no pages
        displayResultMessage();

        // Save the updated bookShelfData
        saveBookShelfDataToStorage();
    }

    // Display a message if there are no pages visible in the page
    function displayResultMessage() {
        // Get HTML elements
        const resultMessage = document.getElementById('resultMessage');
        const bookContainers = document.getElementsByClassName('bookContainer');

        // Check if any book is visible
        const anyBooksVisible = Object.values(bookContainers).some(book => book.style.display === 'grid');

        // Check if there are books to visualize
        if (bookShelfData.length === 0) {
            resultMessage.style.display = 'block';
            resultMessage.textContent = 'No pages saved. Try adding some.';
        }
        // Check if any book is visible
        else if (!anyBooksVisible) {
            resultMessage.style.display = 'block';
            resultMessage.textContent = 'No pages match your search.';
        }
        else {
            resultMessage.style.display = 'none';
            resultMessage.textContent = '';
        }
    }
});
"""

"""tabs.css
@import url('https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400;700&family=Lora:wght@400;700&display=swap');

:root {
    /* --- Background Colors --- */
    --color-background: #EEE7DD;
    --color-header-bg: #C5B299;
    --color-page-bg: #F0E3D1;
    --color-book-bg: #C3B29D;

    /* --- Text Colors --- */
    --color-text-primary: #3B302A;
    --color-text-secondary: #5C4F44;
    --color-text-accent: #8B7A6A;
    --color-text-light: #EEE7DD;

    /* --- Button Colors --- */
    --color-button-primary: #7B5E4A;
    --color-button-primary-hover: #9B7355;
    --color-button-remove: #A0522D;
    --color-button-remove-hover: #8B4513;
    --color-button-restore: #2E8B57;
    --color-button-restore-hover: #3CB371;

    /* --- Move Here Button Colors --- */
    --color-moveHere-bg: #B4A391;
    --color-moveHere-hover-bg: #CABBA7;

    /* --- Border Colors --- */
    --color-border-header: #A99988;
    --color-border-page: #D4C6B2;
    --color-border-search: #B3A292;

    /* --- Other Colors --- */
    --color-shadow: rgba(0, 0, 0, 0.1);
}

.lightTheme2 {
    /* --- Background Colors --- */
    --color-background: #f9f6f2;
    --color-header-bg: #DAD2C6;
    --color-page-bg: #F5F0E9;
    --color-book-bg: #EDE6D6;

    /* --- Text Colors --- */
    --color-text-primary: #333333;
    --color-text-secondary: #4A3F35;
    --color-text-accent: #7A6A5E;
    --color-text-light: #f9f6f2;

    /* --- Button Colors --- */
    --color-button-primary: #6B4F4F;
    --color-button-primary-hover: #8C6E6E;
    --color-button-remove: #A0522D;
    --color-button-remove-hover: #8B4513;
    --color-button-restore: #2E8B57;
    --color-button-restore-hover: #3CB371;

    /* --- Move Here Button Colors --- */
    --color-moveHere-bg: #C1B7A4;
    --color-moveHere-hover-bg: #D1C4B7;

    /* --- Border Colors --- */
    --color-border-header: #BFAFA1;
    --color-border-page: #E0DCCF;
    --color-border-search: #A89F91;

    /* --- Other Colors --- */
    --color-shadow: rgba(0, 0, 0, 0.1);
}

.darkTheme1 {
    /* --- Background Colors --- */
    --color-background: #5B4E41;
    --color-header-bg: #3E362E;
    --color-page-bg: #4A4238;
    --color-book-bg: #41372D;

    /* --- Text Colors --- */
    --color-text-primary: #F5F1EB;
    --color-text-secondary: #D6C8B8;
    --color-text-accent: #BFAD9A;
    --color-text-light: #BAA68C;

    /* --- Button Colors --- */
    --color-button-primary: #70584A;
    --color-button-primary-hover: #8A6B58;
    --color-button-remove: #7A513E;
    --color-button-remove-hover: #6A4734;
    --color-button-restore: #3A6B4A;
    --color-button-restore-hover: #48855D;

    /* --- Move Here Button Colors --- */
    --color-moveHere-bg: #6F6255;
    --color-moveHere-hover-bg: #837465;

    /* --- Border Colors --- */
    --color-border-header: #66584A;
    --color-border-page: #7A6A5A;
    --color-border-search: #5F5143;

    /* --- Other Colors --- */
    --color-shadow: rgba(0, 0, 0, 0.3);
}

.darkTheme2 {
    /* --- Background Colors --- */
    --color-background: #2e2e2e;
    --color-header-bg: #3a3a3a;
    --color-page-bg: #454545;
    --color-book-bg: #404040;

    /* --- Text Colors --- */
    --color-text-primary: #e0e0e0;
    --color-text-secondary: #cccccc;
    --color-text-accent: #dedede;
    --color-text-light: #3a3a3a;

    /* --- Button Colors --- */
    --color-button-primary: #7BAED9;
    --color-button-primary-hover: #9CC3E4;
    --color-button-remove: #e68a3e;
    --color-button-remove-hover: #e88833;
    --color-button-restore: #77c084;
    --color-button-restore-hover: #94d5a1;

    /* --- Move Here Button Colors --- */
    --color-moveHere-bg: #616161;
    --color-moveHere-hover-bg: #737373;

    /* --- Border Colors --- */
    --color-border-header: #555555;
    --color-border-page: #6a6a6a;
    --color-border-search: #888888;

    /* --- Other Colors --- */
    --color-shadow: rgba(0, 0, 0, 0.4);
}

.darkTheme3 {
    /* --- Background Colors --- */
    --color-background: #1e1e1e;
    --color-header-bg: #2c2c2c;
    --color-page-bg: #3a3a3a;
    --color-book-bg: #333333;

    /* --- Text Colors --- */
    --color-text-primary: #f9f6f2;
    --color-text-secondary: #d4d4d4;
    --color-text-accent: #e0e0e0;
    --color-text-light: #333333;

    /* --- Button Colors --- */
    --color-button-primary: #5A9BD4;
    --color-button-primary-hover: #7BB0E0;
    --color-button-remove: #d2691e;
    --color-button-remove-hover: #e57300;
    --color-button-restore: #66bb6a;
    --color-button-restore-hover: #81c784;

    /* --- Move Here Button Colors --- */
    --color-moveHere-bg: #4f4f4f;
    --color-moveHere-hover-bg: #5f5f5f;

    /* --- Border Colors --- */
    --color-border-header: #444444;
    --color-border-page: #595959;
    --color-border-search: #777777;

    /* --- Other Colors --- */
    --color-shadow: rgba(0, 0, 0, 0.5);
}

body {
    font-family: 'Merriweather', serif;
    background-color: var(--color-background);
    color: var(--color-text-primary);
    margin: 0;
    padding: 0;
}

h2 {
    font-family: 'Lora', serif;
    color: var(--color-text-secondary);
}

button {
    background-color: var(--color-button-primary);
    padding: 8px 16px;
    color: var(--color-text-light);
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    margin: 0px 5px;
    transition: background-color 0.3s ease, color 0.3s ease;
}

button:hover {
    background-color: var(--color-button-primary-hover);
}

input[type="checkbox"] {
    background-color: var(--color-background);
    cursor: pointer;
}

#resultMessage {
    text-align: center;
    margin-top: 20px;
    color: var(--color-text-accent);
}

#mainHeader {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: var(--color-header-bg);
    padding: 15px 40px;
    border-bottom: 1px solid var(--color-border-header);
    box-shadow: 0 2px 4px var(--color-shadow);
}

#mainHeaderLeft, #mainHeaderCenter, #mainHeaderRight {
    flex: 1;
    display: flex;
    align-items: center;
}

#mainHeaderCenter {
    justify-content: center;
}

#mainHeaderRight {
    justify-content: flex-end;
}

#homePageLink {
    font-size: 28px;
    font-weight: 700;
    text-decoration: none;
    color: var(--color-text-secondary);
}

#homePageLink:hover {
    text-decoration: underline;
}

#searchBar {
    width: 100%;
    max-width: 400px;
    padding: 10px 14px;
    font-size: 16px;
    border: 2px solid var(--color-border-search);
    border-radius: 4px;
    background-color: var(--color-background);
    color: var(--color-text-primary);
}

#searchBar:focus {
    outline: none !important;
    border: 3px solid var(--color-button-primary);
    padding: 9px 13px;
}

#searchBar::placeholder {
    color: var(--color-text-accent);
    opacity: 1;
}

#themeSelector {
    padding: 8px 16px;
    font-size: 14px;
    border: 1px solid var(--color-border-search);
    border-radius: 4px;
    background-color: var(--color-button-primary);
    color: var(--color-text-light);
    appearance: none;
    cursor: pointer;
    text-align-last: center;
}

#themeSelector:hover {
    background-color: var(--color-button-primary-hover);
}

#themeSelector:focus {
    outline: none;
}

#settingsPageButton {
    background-color: transparent;
    border: none;
    padding: 0;
    cursor: pointer;
    margin-left: 10px;
}

#settingsPageButton:hover {
    opacity: 0.8;
}

#settingsPageButton img {
    width: 36px;
    height: 36px;
}

#mainBody {
    max-width: 1000px;
    margin: 90px auto 20px;
    padding: 20px;
}

#mainPage, #settingsPage {
    width: 100%;
}

#bookShelf {
    display: grid;
}

.pagesList {
    display: grid;
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.pagesListItem {
    display: grid;
    background-color: var(--color-page-bg);
    border-bottom: 1px solid var(--color-border-page);
}

.pagesListItem:last-child {
    border-bottom: none;
}

.pageContainer {
    display: flex;
    align-items: center;
    padding: 10px 15px;
}

.pageLink {
    text-decoration: none;
    color: var(--color-text-secondary);
    font-size: 16px;
    flex-grow: 1;
}

.pageLink:hover {
    text-decoration: underline;
}

.moveHereButton {
    display: block;
    background-color: var(--color-moveHere-bg);
    color: var(--color-text-accent);
    padding: 0;
    margin: 0;
    border: 1px dashed var(--color-text-accent);
    border-radius: 0;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.moveHereButton:hover {
    background-color: var(--color-moveHere-hover-bg);
}

.pageCheckbox {
    margin-right: 10px;
}

.bookContainer {
    display: grid;
    margin-bottom: 20px;
    border: 1px solid var(--color-border-page);
    border-radius: 8px;
    overflow: hidden;
    background-color: var(--color-page-bg);
}

.bookHeader, .bookFooter {
    display: flex;
    align-items: center;
    background-color: var(--color-book-bg);
    padding: 10px 15px;
}

.bookHeader {
    cursor: pointer;
}

.bookCheckbox {
    margin-right: 10px;
}

.bookTitle, .pagesCount {
    flex-grow: 1;
    margin: 0;
    padding: 0;
}

.bookTitle[contenteditable="true"] {
    outline: 2px solid var(--color-button-primary);
    background-color: var(--color-background);
    padding: 2px;
    border-radius: 4px;
}

.pagesCount {
    display: flex;
    justify-content: flex-end;
    margin-right: 5px;
    color: var(--color-text-accent);
}

.removeBookButton, .removePageButton, .removeSelectedPagesButton {
    background-color: var(--color-button-remove);
}

.removeBookButton:hover, .removePageButton:hover, .removeSelectedPagesButton:hover {
    background-color: var(--color-button-remove-hover);
}

.restoreBookButton, .restoreSelectedPagesButton {
    background-color: var(--color-button-restore);
}

.restoreBookButton:hover, .restoreSelectedPagesButton:hover {
    background-color: var(--color-button-restore-hover);
}
"""