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
async 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
  let bookShelfData;
  let selectedShelfId;
  const data = await chrome.storage.local.get(['selectedShelfId', 'bookShelfData']);
  if (!data.bookShelfData) {
    bookShelfData = [{ id: generateUUID(), title: 'Shelf 1', books: [] }];
    selectedShelfId = bookShelfData[0].id;
  }
  else {
    bookShelfData = data.bookShelfData;
    selectedShelfId = data.selectedShelfId || bookShelfData[0].id;
  }

  // Find the shelf
  let shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
  if (!shelf) {
    // Create new shelf ID
    let newShelfId;
    do {
        newShelfId = generateUUID();
    } while(bookShelfData.some(shelf => shelf.id === newShelfId));

    // Create new shelf
    const newShelf = {
      id: newShelfId,
      title: `Shelf ${bookShelfData.length + 1}`,
      books: []
    }

    // Save new shelf and add it at the end of the array
    selectedShelfId = newShelf.id;
    bookShelfData.push(newShelf);

    shelf = newShelf;
  }

  // Create new book ID
  let newBookId;
  do {
    newBookId = generateUUID();
  } while(shelf.books.some(book => book.id === newBookId));

  // Create default book title as 'Book X'
  let defaultBookTitle = `Book ${shelf.books.length + 1}`;

  // Add the new book at the beginning of the array
  const newBook = {
    id: newBookId,
    title: defaultBookTitle,
    pages: newPages,
    collapsed: false
  };
  shelf.books.unshift(newBook);

  // Save the updated bookshelf data to storage
  chrome.storage.local.set({ 'selectedShelfId': selectedShelfId, '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" style="z-index: 100;">
        <div id="mainHeaderLeft">
            <h2 id="selectedShelfTitle">
                <svg id="arrowIcon" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 10 10">
                    <path d="M3 1 L7 5 L3 9" />
                </svg>
                Bookshelf
            </h2>
            <ul id="shelfList" class="close" style="z-index: 50;"></ul>
        </div>
        <div id="mainHeaderCenter">
            <input type="text" id="searchBar" placeholder="Search pages...">
        </div>
        <div id="mainHeaderRight">
            <!-- Theme Toggle Button -->
            <button id="themeToggleButton" title="Toggle Theme" aria-label="Toggle between Light and Dark Theme">
                <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 30 30">
                    <path id="sunIcon" visibility="visible" d="M 14.984375 0.98632812 A 1.0001 1.0001 0 0 0 14 2 L 14 5 A 1.0001 1.0001 0 1 0 16 5 L 16 2 A 1.0001 1.0001 0 0 0 14.984375 0.98632812 z M 5.796875 4.7988281 A 1.0001 1.0001 0 0 0 5.1015625 6.515625 L 7.2226562 8.6367188 A 1.0001 1.0001 0 1 0 8.6367188 7.2226562 L 6.515625 5.1015625 A 1.0001 1.0001 0 0 0 5.796875 4.7988281 z M 24.171875 4.7988281 A 1.0001 1.0001 0 0 0 23.484375 5.1015625 L 21.363281 7.2226562 A 1.0001 1.0001 0 1 0 22.777344 8.6367188 L 24.898438 6.515625 A 1.0001 1.0001 0 0 0 24.171875 4.7988281 z M 15 8 A 7 7 0 0 0 8 15 A 7 7 0 0 0 15 22 A 7 7 0 0 0 22 15 A 7 7 0 0 0 15 8 z M 2 14 A 1.0001 1.0001 0 1 0 2 16 L 5 16 A 1.0001 1.0001 0 1 0 5 14 L 2 14 z M 25 14 A 1.0001 1.0001 0 1 0 25 16 L 28 16 A 1.0001 1.0001 0 1 0 28 14 L 25 14 z M 7.9101562 21.060547 A 1.0001 1.0001 0 0 0 7.2226562 21.363281 L 5.1015625 23.484375 A 1.0001 1.0001 0 1 0 6.515625 24.898438 L 8.6367188 22.777344 A 1.0001 1.0001 0 0 0 7.9101562 21.060547 z M 22.060547 21.060547 A 1.0001 1.0001 0 0 0 21.363281 22.777344 L 23.484375 24.898438 A 1.0001 1.0001 0 1 0 24.898438 23.484375 L 22.777344 21.363281 A 1.0001 1.0001 0 0 0 22.060547 21.060547 z M 14.984375 23.986328 A 1.0001 1.0001 0 0 0 14 25 L 14 28 A 1.0001 1.0001 0 1 0 16 28 L 16 25 A 1.0001 1.0001 0 0 0 14.984375 23.986328 z"/>
                    <path id="moonIcon" visibility="hidden" fill="#444" d="M14.4 0c-7.92 0-14.4 6.48-14.4 14.4s6.48 14.4 14.4 14.4 14.4-6.48 14.4-14.4-6.48-14.4-14.4-14.4zM14.4 27c-7.02 0-12.6-5.58-12.6-12.6 0-4.32 2.16-8.28 5.76-10.62-0.18 1.08-0.36 2.34-0.36 3.42 0 8.82 7.2 16.02 16.02 16.2-2.34 2.34-5.4 3.6-8.82 3.6z"/>
                </svg>
            </button>
            <!-- Settings Button -->
            <button id="settingsPageButton" title="Open settings page">
                <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="36" height="36" viewBox="0 0 50 50">
                    <path d="M47.16,21.221l-5.91-0.966c-0.346-1.186-0.819-2.326-1.411-3.405l3.45-4.917c0.279-0.397,0.231-0.938-0.112-1.282 l-3.889-3.887c-0.347-0.346-0.893-0.391-1.291-0.104l-4.843,3.481c-1.089-0.602-2.239-1.08-3.432-1.427l-1.031-5.886 C28.607,2.35,28.192,2,27.706,2h-5.5c-0.49,0-0.908,0.355-0.987,0.839l-0.956,5.854c-1.2,0.345-2.352,0.818-3.437,1.412l-4.83-3.45 c-0.399-0.285-0.942-0.239-1.289,0.106L6.82,10.648c-0.343,0.343-0.391,0.883-0.112,1.28l3.399,4.863 c-0.605,1.095-1.087,2.254-1.438,3.46l-5.831,0.971c-0.482,0.08-0.836,0.498-0.836,0.986v5.5c0,0.485,0.348,0.9,0.825,0.985 l5.831,1.034c0.349,1.203,0.831,2.362,1.438,3.46l-3.441,4.813c-0.284,0.397-0.239,0.942,0.106,1.289l3.888,3.891 c0.343,0.343,0.884,0.391,1.281,0.112l4.87-3.411c1.093,0.601,2.248,1.078,3.445,1.424l0.976,5.861C21.3,47.647,21.717,48,22.206,48 h5.5c0.485,0,0.9-0.348,0.984-0.825l1.045-5.89c1.199-0.353,2.348-0.833,3.43-1.435l4.905,3.441 c0.398,0.281,0.938,0.232,1.282-0.111l3.888-3.891c0.346-0.347,0.391-0.894,0.104-1.292l-3.498-4.857 c0.593-1.08,1.064-2.222,1.407-3.408l5.918-1.039c0.479-0.084,0.827-0.5,0.827-0.985v-5.5C47.999,21.718,47.644,21.3,47.16,21.221z M25,32c-3.866,0-7-3.134-7-7c0-3.866,3.134-7,7-7s7,3.134,7,7C32,28.866,28.866,32,25,32z"></path>
                </svg>
            </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 Overlay -->
        <div id="settingsOverlay" style="z-index: 101"></div>

        <!-- Settings Page -->
        <div id="settingsPage" style="z-index: 102">
            <button id="closeSettingsButton" title="Close Settings">X</button>
            <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 selectedShelfTitle = document.getElementById('selectedShelfTitle');
    const shelfList = document.getElementById('shelfList');
    const searchBar = document.getElementById('searchBar');
    const themeToggleButton = document.getElementById('themeToggleButton');
    const settingsPageButton = document.getElementById('settingsPageButton');
    const settingsOverlay = document.getElementById('settingsOverlay');
    const settingsPage = document.getElementById('settingsPage');
    const closeSettingsButton = document.getElementById('closeSettingsButton');
    let selectedShelfId = "";
    let bookShelfData = [];
    let bookShelfDataUpdated = false;
    let loadingBookShelfData = false;
    let pagesToMove = [];
    let bookIdOfMovingPages = '';
    let isSettingsPageOpen = false;

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

    // Change the shelf title with the selected one
    const selectedShelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
    if (selectedShelf) {
        changeSelectedShelfTitle(selectedShelf.title);
    }

    // Paint the DOM
    displayBookShelf();

    // Get saved theme
    chrome.storage.local.get('themeSelected', (data) => {
        const currentTheme = data.themeSelected || 'light';

        if (currentTheme === 'dark') {
            document.body.classList.add('darkTheme');
            document.getElementById('sunIcon').style.visibility = "hidden";
            document.getElementById('moonIcon').style.visibility = "visible";
        } else {
            document.body.classList.remove('darkTheme');
            document.getElementById('sunIcon').style.visibility = "visible";
            document.getElementById('moonIcon').style.visibility = "hidden";
        }
    });

    // Create a timer that check if there are bookshelf data to save
    let intervalId = setInterval(() => {
        if (bookShelfDataUpdated && !loadingBookShelfData) {
            // Save bookshelf data
            chrome.storage.local.set({ 'selectedShelfId': selectedShelfId, '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();
        }
    });

    // Handle click event for the extension name to show/hide the shelf dropdown
    selectedShelfTitle.addEventListener('click', () => {
        const arrowIcon = document.getElementById('arrowIcon');

        shelfList.classList.toggle('close');
        arrowIcon.style.transform = shelfList.classList.contains('close') ? 'rotate(0deg)' : 'rotate(180deg)';
    });

    // Event listener for the search bar
    searchBar.addEventListener('input', () => {
        let timeoutId;

        // Clear the previous timer
        if (timeoutId) {
            clearTimeout(timeoutId);
        }

        // Set a new timer
        timeoutId = setTimeout(() => {
            // TODO: disable or enable (by settings) to move pages when filtering
            //    if (!settings.canMoveWhileFiltering) {
            //        pagesToMove = [];
            //        bookIdOfMovingPages = '';
            //    }

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

    // Event listener for the theme toggle button
    themeToggleButton.addEventListener('click', () => {
        chrome.storage.local.get('themeSelected', (data) => {
            let currentTheme = data.themeSelected || 'light';

            if (currentTheme === 'light') {  // Switch to dark
                document.body.classList.add('darkTheme');
                chrome.storage.local.set({ 'themeSelected': 'dark' });
                document.getElementById('sunIcon').style.visibility = "hidden";
                document.getElementById('moonIcon').style.visibility = "visible";
            } else {  // Switch to light
                document.body.classList.remove('darkTheme');
                chrome.storage.local.set({ 'themeSelected': 'light' });
                document.getElementById('sunIcon').style.visibility = "visible";
                document.getElementById('moonIcon').style.visibility = "hidden";
            }
        });
    });

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

        isSettingsPageOpen = !isSettingsPageOpen;

        if (isSettingsPageOpen) {
            // Open the settings page
            settingsPage.classList.add('open');
            settingsOverlay.classList.add('open');
        } else {
            // Close the settings page
            settingsPage.classList.remove('open');
            settingsOverlay.classList.remove('open');
        }
    });

    // Event listener for the overlay to close the settings page when clicked
    settingsOverlay.addEventListener('click', () => {
        isSettingsPageOpen = false;
        settingsPage.classList.remove('open');
        settingsOverlay.classList.remove('open');
    });

    // Event listener for the close button inside the settings page
    closeSettingsButton.addEventListener('click', () => {
        isSettingsPageOpen = false;
        settingsPage.classList.remove('open');
        settingsOverlay.classList.remove('open');
    });

    // Close the settings page when the Escape key is pressed
    document.addEventListener('keydown', (event) => {
        if ((event.key === 'Escape') && isSettingsPageOpen) {
            isSettingsPageOpen = false;
            settingsPage.classList.remove('open');
            settingsOverlay.classList.remove('open');
        }
    });

    // Function to get bookshelf saved data from storage
    async function LoadBookShelfDataFromStorage() {
        loadingBookShelfData = true;

        const data = await chrome.storage.local.get(['selectedShelfId', 'bookShelfData']);
        if (!data.bookShelfData) {
            bookShelfData = [{ id: generateUUID(), title: 'Shelf 1', books: [] }];
            selectedShelfId = bookShelfData[0].id;
        }
        else {
            bookShelfData = data.bookShelfData;
            selectedShelfId = data.selectedShelfId || bookShelfData[0].id;

            if (!bookShelfData.find(shelf => shelf.id === selectedShelfId)) {
                selectedShelfId = bookShelfData[0].id;

                saveBookShelfDataToStorage();
            }
        }

        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}"]`);
    }

    // Get shelf element from ID
    function getShelfElementById(shelfId) {
        return document.querySelector(`.shelfListItem[data-shelf-id="${shelfId}"]`);
    }

    // Function to change selected shelf title
    function changeSelectedShelfTitle(newTitle) {
        // Clone the arrow icon
        const arrowIconClone = document.getElementById('arrowIcon').cloneNode(true);

        // Change selected shelf title
        selectedShelfTitle.innerHTML = '';
        selectedShelfTitle.appendChild(arrowIconClone);
        selectedShelfTitle.innerHTML += newTitle;
    };

    // 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;

        // Function to create the edit shelf title button
        function createEditShelfTitleButton(shelfId) {
            const editShelfTitleButton = document.createElement('button');
            editShelfTitleButton.title = 'Edit shelf title';
            editShelfTitleButton.className = 'editShelfTitleButton';
            editShelfTitleButton.dataset.mode = 'edit';

            // Create SVG element
            const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            svgElem.setAttribute('viewBox', '0 0 48 48');
            svgElem.setAttribute('width', '20px');
            svgElem.setAttribute('height', '20px');
            const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            pathElem.setAttribute('d', 'M38.657 18.536l2.44-2.44c2.534-2.534 2.534-6.658 0-9.193-1.227-1.226-2.858-1.9-4.597-1.9s-3.371.675-4.597 1.901l-2.439 2.439L38.657 18.536zM27.343 11.464L9.274 29.533c-.385.385-.678.86-.848 1.375L5.076 41.029c-.179.538-.038 1.131.363 1.532C5.726 42.847 6.108 43 6.5 43c.158 0 .317-.025.472-.076l10.118-3.351c.517-.17.993-.463 1.378-.849l18.068-18.068L27.343 11.464z');

            // Append elements in the correct order
            svgElem.appendChild(pathElem);
            editShelfTitleButton.appendChild(svgElem);

            // Toggle between edit and save modes for the shelf title
            editShelfTitleButton.addEventListener('click', () => {
                // Find the shelf index
                const shelf = bookShelfData.find(shelf => shelf.id === shelfId);
                if (!shelf) return;

                // Get HTML element
                const shelfTitle = getShelfElementById(shelfId).getShelfTitle();

                if (editShelfTitleButton.dataset.mode === 'edit') {
                    // Switch to edit mode
                    shelfTitle.contentEditable = true;
                    shelfTitle.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(shelfTitle);
                        range.collapse(false); // Collapse the range to the end

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

                    // Change button to 'Save'
                    editShelfTitleButton.title = 'Save shelf title';
                    editShelfTitleButton.dataset.mode = 'save';

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

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

                    // Update the shelf title
                    shelf.title = newTitle;

                    // Update the selected shelf title
                    if (shelf.id === selectedShelfId) {
                        changeSelectedShelfTitle(shelf.title);
                    }

                    // Save the updated shelf to storage
                    saveBookShelfDataToStorage();

                    // Disable contentEditable
                    shelfTitle.contentEditable = false;

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

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

            return editShelfTitleButton;
        }

        // Function to create the shelf title
        function createShelfTitle(shelfId, shelfTitle) {
            const shelfTitleElem = document.createElement('h2');
            shelfTitleElem.textContent = shelfTitle;
            shelfTitleElem.className = 'shelfTitle';
            shelfTitleElem.contentEditable = false;

            // Switch to this shelf
            shelfTitleElem.addEventListener('click', () => {
                if ((shelfTitleElem.contentEditable === 'false') && (shelfId !== selectedShelfId)) {
                    // Find the shelf
                    const shelf = bookShelfData.find(shelf => shelf.id === shelfId);
                    if (!shelf) return;

                    // Change the selected shelf title
                    changeSelectedShelfTitle(shelf.title);

                    // Change and save the selected shelf
                    selectedShelfId = shelfId;
                    saveBookShelfDataToStorage();

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

            return shelfTitleElem;
        }

        // Function to create the remove shelf button
        function createRemoveShelfButton(shelfId) {
            const removeShelfButton = document.createElement('button');
            removeShelfButton.title = 'Remove this shelf';
            removeShelfButton.className = 'removeShelfButton';

            // Create SVG element
            const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            svgElem.setAttribute('viewBox', '0 0 30 30');
            svgElem.setAttribute('width', '20px');
            svgElem.setAttribute('height', '20px');
            const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            pathElem.setAttribute('d', 'M 7 4 C 6.744125 4 6.4879687 4.0974687 6.2929688 4.2929688 L 4.2929688 6.2929688 C 3.9019687 6.6839688 3.9019687 7.3170313 4.2929688 7.7070312 L 11.585938 15 L 4.2929688 22.292969 C 3.9019687 22.683969 3.9019687 23.317031 4.2929688 23.707031 L 6.2929688 25.707031 C 6.6839688 26.098031 7.3170313 26.098031 7.7070312 25.707031 L 15 18.414062 L 22.292969 25.707031 C 22.682969 26.098031 23.317031 26.098031 23.707031 25.707031 L 25.707031 23.707031 C 26.098031 23.316031 26.098031 22.682969 25.707031 22.292969 L 18.414062 15 L 25.707031 7.7070312 C 26.098031 7.3170312 26.098031 6.6829688 25.707031 6.2929688 L 23.707031 4.2929688 C 23.316031 3.9019687 22.682969 3.9019687 22.292969 4.2929688 L 15 11.585938 L 7.7070312 4.2929688 C 7.5115312 4.0974687 7.255875 4 7 4 z');

            // Append elements in the correct order
            svgElem.appendChild(pathElem);
            removeShelfButton.appendChild(svgElem);

            // Remove shelf
            removeShelfButton.addEventListener('click', () => {
                if (bookShelfData.length > 1) {
                    if (shelfId === selectedShelfId) {
                        alert('Please choose another shelf before removing this.');
                    }
                    else if (confirm('Are you sure you want to remove this shelf?')) {
                        // Remove shelf from data and save it
                        bookShelfData = bookShelfData.filter(shelf => shelf.id !== shelfId);
                        saveBookShelfDataToStorage();

                        // Remove shelf element
                        const shelfElem = getShelfElementById(shelfId);
                        if (shelfElem) {
                            shelfList.removeChild(shelfElem);
                        }
                    }
                }
                else if (confirm('Are you sure you want to reset this shelf?')) {
                    // Remove all books from this shelf
                    bookShelfData[0].books = [];

                    // Change shelf name
                    bookShelfData[0].title = "Shelf 1";

                    // Update the selected shelf title
                    changeSelectedShelfTitle(bookShelfData[0].title);

                    // Save updated shelf
                    saveBookShelfDataToStorage();

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

                    // Display the message that there are no page saved
                    displayResultMessage();
                }
            });

            return removeShelfButton;
        }

        // Function to create the shelf list item
        function createShelfListItem(shelf) {
            const shelfListItem = document.createElement('li');
            shelfListItem.classList.add('shelfListItem');
            shelfListItem.dataset.shelfId = shelf.id;

            // Create children elements
            const editShelfTitleButton = createEditShelfTitleButton(shelf.id);
            const shelfTitle = createShelfTitle(shelf.id, shelf.title);
            const removeShelfButton = createRemoveShelfButton(shelf.id);

            // Append elements to the shelf list item in the desired order
            shelfListItem.appendChild(editShelfTitleButton);
            shelfListItem.appendChild(shelfTitle);
            shelfListItem.appendChild(removeShelfButton);

            // Create functions to retrieve nested elements
            shelfListItem.getShelfTitle = function() {return shelfTitle;}

            return shelfListItem;
        }

        // Function to create the add new shelf button
        function createAddNewShelfButton() {
            const addNewShelfButton = document.createElement('li');
            addNewShelfButton.classList.add('addNewShelfButton');

            // Create SVG element
            const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            svgElem.setAttribute('viewBox', '0 0 48 48');
            svgElem.setAttribute('width', '20px');
            svgElem.setAttribute('height', '20px');
            svgElem.style.marginRight = '5px';
            const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            pathElem.setAttribute('d', 'M 24 4 C 12.972066 4 4 12.972074 4 24 C 4 35.027926 12.972066 44 24 44 C 35.027934 44 44 35.027926 44 24 C 44 12.972074 35.027934 4 24 4 z M 24 7 C 33.406615 7 41 14.593391 41 24 C 41 33.406609 33.406615 41 24 41 C 14.593385 41 7 33.406609 7 24 C 7 14.593391 14.593385 7 24 7 z M 23.976562 13.978516 A 1.50015 1.50015 0 0 0 22.5 15.5 L 22.5 22.5 L 15.5 22.5 A 1.50015 1.50015 0 1 0 15.5 25.5 L 22.5 25.5 L 22.5 32.5 A 1.50015 1.50015 0 1 0 25.5 32.5 L 25.5 25.5 L 32.5 25.5 A 1.50015 1.50015 0 1 0 32.5 22.5 L 25.5 22.5 L 25.5 15.5 A 1.50015 1.50015 0 0 0 23.976562 13.978516 z');

            // Append elements in the correct order
            svgElem.appendChild(pathElem);
            addNewShelfButton.appendChild(svgElem);
            addNewShelfButton.innerHTML += "Add new shelf";

            // Add new shelf
            addNewShelfButton.addEventListener('click', () => {
                // Create new shelf ID
                let newShelfId;
                do {
                    newShelfId = generateUUID();
                } while(bookShelfData.some(shelf => shelf.id === newShelfId));

                // Create new shelf
                const newShelf = {
                    id: newShelfId,
                    title: `Shelf ${bookShelfData.length + 1}`,
                    books: []
                }
                bookShelfData.push(newShelf);  // Add the new shelf at the end of the array

                // Save the new shelf to storage
                saveBookShelfDataToStorage();

                // Insert in the list
                shelfList.insertBefore(createShelfListItem(newShelf), addNewShelfButton);
            });

            return addNewShelfButton;
        }

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

            // Create SVG element
            const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            svgElem.setAttribute('viewBox', '0 0 48 48');
            svgElem.setAttribute('width', '23px');
            svgElem.setAttribute('height', '23px');
            const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            pathElem.setAttribute('d', 'M38.657 18.536l2.44-2.44c2.534-2.534 2.534-6.658 0-9.193-1.227-1.226-2.858-1.9-4.597-1.9s-3.371.675-4.597 1.901l-2.439 2.439L38.657 18.536zM27.343 11.464L9.274 29.533c-.385.385-.678.86-.848 1.375L5.076 41.029c-.179.538-.038 1.131.363 1.532C5.726 42.847 6.108 43 6.5 43c.158 0 .317-.025.472-.076l10.118-3.351c.517-.17.993-.463 1.378-.849l18.068-18.068L27.343 11.464z');

            // Append elements in the correct order
            svgElem.appendChild(pathElem);
            editBookTitleButton.appendChild(svgElem);

            // Toggle between edit and save modes for the book title
            editBookTitleButton.addEventListener('click', () => {
                // Find the shelf
                const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                if (!shelf) return;

                // Find the book
                const book = shelf.books.find(book => book.id === bookId);
                if (!book) 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.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
                    book.title = newTitle;

                    // Save the updated book to storage
                    saveBookShelfDataToStorage();

                    // Disable contentEditable
                    bookTitle.contentEditable = false;

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

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

            return editBookTitleButton;
        }

        // 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 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 the top part of a book header
        function createBookHeaderTop(book) {
            const bookHeaderTop = document.createElement('div');
            bookHeaderTop.className = 'bookHeaderTop';

            // Create children elements
            const editBookTitleButton = createEditBookTitleButton(book.id);
            const bookTitle = createBookTitle(book.title);
            const pagesCount = createPagesCount(book.pages.length);

            // Append elements to the top header in the desired order
            bookHeaderTop.appendChild(editBookTitleButton);
            bookHeaderTop.appendChild(bookTitle);
            bookHeaderTop.appendChild(pagesCount);

            // Create functions to retrieve nested elements
            bookHeaderTop.getEditBookTitleButton = function() {return editBookTitleButton;}
            bookHeaderTop.getBookTitle = function() {return bookTitle;}
            bookHeaderTop.getPagesCount = function() {return pagesCount;}

            return bookHeaderTop;
        }

        // Function to create the book checkbox
        function createBookCheckbox(bookId) {
            const bookCheckbox = document.createElement('input');
            bookCheckbox.type = 'checkbox';
            bookCheckbox.className = 'bookCheckbox';
            bookCheckbox.name = '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 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 shelf
                    const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                    if (!shelf) return;

                    // Find the book
                    const book = shelf.books.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 shelf
                const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                if (!shelf) return;

                // Find the book
                const book = shelf.books.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 the selected page${pagesToRestore.length !== 1 ? '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 shelf
                const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                if (!shelf) return;

                // Find the book
                const book = shelf.books.find(book => book.id === bookId);
                if (!book) return;

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

                // Assert data compatibility
                if (!(pageCheckboxes.length === book.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 page${indicesToRemove.length !== 1 ? 's' : ''}?`)) {
                    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]);
                    book.pages.splice(pageIndex, 1);
                });

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

                // Update pages count
                updatePageCount(bookId);

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

            return removeSelectedPagesButton;
        }

        // Function to create the bottom part of a book header
        function createBookHeaderBottom(bookId) {
            const bookHeaderBottom = document.createElement('div');
            bookHeaderBottom.className = 'bookHeaderBottom';

            // Create children elements
            const bookCheckbox = createBookCheckbox(bookId);
            const moveSelectedPagesButton = createMoveSelectedPagesButton(bookId);
            const restoreSelectedPagesButton = createRestoreSelectedPagesButton(bookId);
            const removeSelectedPagesButton = createRemoveSelectedPagesButton(bookId);

            // Append elements to the bottom header in the desired order
            bookHeaderBottom.appendChild(bookCheckbox);
            bookHeaderBottom.appendChild(moveSelectedPagesButton);
            bookHeaderBottom.appendChild(restoreSelectedPagesButton);
            bookHeaderBottom.appendChild(removeSelectedPagesButton);

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

            return bookHeaderBottom;
        }

        // Function to create a book header
        function createBookHeader(book) {
            const bookId = book.id;

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

            // Create children elements
            const bookHeaderTop = createBookHeaderTop(book);
            const bookHeaderBottom = createBookHeaderBottom(bookId);

            // Append elements to the header in the desired order
            bookHeader.appendChild(bookHeaderTop);
            bookHeader.appendChild(bookHeaderBottom);

            // Create functions to retrieve nested elements
            bookHeader.getBookTitle = function() {return bookHeaderTop.getBookTitle();}
            bookHeader.getPagesCount = function() {return bookHeaderTop.getPagesCount();}
            bookHeader.getBookCheckbox = function() {return bookHeaderBottom.getBookCheckbox();}

            // Add event listener
            bookHeader.addEventListener('click', (event) => {
                // Toggle book collapse/expand state
                if ((event.target === bookHeader) || (event.target === bookHeaderTop) || (event.target === bookHeaderBottom) || (event.target === bookHeaderTop.getPagesCount())
                    || ((event.target === bookHeaderTop.getBookTitle()) && (bookHeaderTop.getEditBookTitleButton().dataset.mode === 'edit'))) {
                    // Find the shelf
                    const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                    if (!shelf) return;

                    // Find the book
                    const book = shelf.books.find(book => book.id === bookId);
                    if (!book) return;

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

                    // Toggle the display style
                    if (book.collapsed) {
                        pagesList.style.display = 'grid';
                        bookHeaderBottom.style.display = 'flex';
                        bookHeaderTop.style.marginBottom = '5px';
                    } else {
                        pagesList.style.display = 'none';
                        bookHeaderBottom.style.display = 'none';
                        bookHeaderTop.style.marginBottom = '0';
                    }
                    book.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';
            pageCheckbox.name = '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';
            pageLink.title = page.url;

            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 shelf
                const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                if (!shelf) return;

                // Find the book
                const book = shelf.books.find(book => book.id === bookId);
                if (!book) return;

                // Find the page index
                const pageIndex = book.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 === book.pages.length)) {
                    console.assert(false, `Assert error when removing ${pageId} page in ${bookId} book`);
                    return;
                }

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

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

                // Remove the book if no pages are left
                if (book.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) return;

                // Find the shelf
                const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
                if (!shelf) return;

                // Find the book
                let book = shelf.books.find(book => book.id === bookId);
                if (!book) return;

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

                // Check if the pages we are moving have the same ID as those in the book
                let bookIds;
                let pageToAdd = JSON.parse(JSON.stringify(pagesToMove));  // Make a deep copy (NOTE: can be slow)
                do {
                    // Get book pages IDs
                    bookIds = new Set(book.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
                book.pages.splice(pageIndex, 0, ...pageToAdd);

                // Remove pages from previous book
                book = shelf.books.find(book => book.id === bookIdOfMovingPages);
                if (book) {
                    bookIds = new Set(pagesToMove.map(page => page.id));
                    book.pages = book.pages.filter(page => !bookIds.has(page.id));

                    if (book.pages.length === 0) {
                        // Remove the book because no pages are left
                        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 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, '');

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

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

            // 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
        shelfList.innerHTML = '';
        bookShelfData.forEach((shelf) => {
            shelfList.appendChild(createShelfListItem(shelf));

            if (shelf.id === selectedShelfId) {
                shelf.books.forEach((book) => {
                    fragment.appendChild(createBookContainer(book));
                });
            }
        });
        shelfList.appendChild(createAddNewShelfButton());

        // 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) {
        // Find the shelf
        const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
        if (!shelf) return;

        // Find the book
        const book = shelf.books.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 shelf
        const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
        if (!shelf) return;

        // Find the book index
        const bookIndex = shelf.books.findIndex(book => book.id === bookId);
        if (bookIndex < 0) return;

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

        // Remove the book
        bookContainer.parentElement.removeChild(bookContainer);
        shelf.books.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() {
        // Find the shelf
        const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);

        // 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 the data is correct
        if (!shelf) {
            resultMessage.style.display = 'block';
            resultMessage.textContent = 'Error when loading the shelf. Try to reload the extension.';
        }
        // Check if there are books to visualize
        else if (shelf.books.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);
}

.darkTheme {
    /* --- 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);
}

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

h2 {
    color: var(--color-text-secondary);
    margin: 0;
}

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;
    margin: 0 5px;
    margin-right: 20px;
}

svg path {
    fill: var(--color-text-secondary);
}

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

#mainHeader {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    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;
}

#selectedShelfTitle {
    font-size: 28px;
    font-weight: 700;
    text-decoration: none;
    color: var(--color-text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
}

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

#arrowIcon {
    transition: transform 0.3s;
    margin-right: 5px;
}

#shelfList {
    display: block;
    position: fixed;
    top: 80px; /* mainHeader.height + mainHeader.paddingTop + mainHeader.paddingBottom */
    left: 0;
    width: 420px;
    background-color: var(--color-header-bg);
    border: 1px solid var(--color-border-header);
    list-style-type: none;
    margin: 0;
    padding: 5px 10px;
    box-shadow: 0 2px 4px var(--color-shadow);
    transition: left 0.3s ease;
    overflow: hidden;
}

#shelfList.close {
    left: -440px;
}

.editShelfTitleButton {
    background-color: transparent;
    width: 20px;
    height: 20px;
    border: none;
    padding: 0;
    margin: 0 5px 0 0;
}

.editShelfTitleButton:hover {
    background-color: transparent;
    opacity: 0.8;
}

.shelfTitle {
    font-family: 'Lora', serif;
    font-size: 20px;
    text-decoration: none;
    flex-grow: 1;
    padding: 0;
}

.shelfTitle[contenteditable="false"]:hover {
    text-decoration: underline;
}

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

.removeShelfButton {
    background-color: transparent;
    width: 20px;
    height: 20px;
    border: none;
    padding: 0;
    margin: 0 0 0 5px;
}

.removeShelfButton:hover {
    background-color: transparent;
    opacity: 0.8;
}

.shelfListItem, .addNewShelfButton {
    display: flex;
    align-items: center;
    color: var(--color-text-secondary);
    font-size: 16px;
    border-radius: 4px;
    background-color: var(--color-page-bg);
    padding: 5px;
    margin: 5px 0;
    cursor: pointer;
}

.addNewShelfButton: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;
}

#themeToggleButton, #settingsPageButton {
    background-color: transparent;
    width: 36px;
    height: 36px;
    border: none;
    padding: 0;
    margin-left: 10px;
}

#themeToggleButton:hover, #settingsPageButton:hover {
    opacity: 0.8;
}

#mainBody {
    margin-top: 90px;
    padding: 20px;
    padding-bottom: 0;
}

#mainPage {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

#settingsOverlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.4);
}

#settingsOverlay.open {
    display: block;
}

#settingsPage {
    position: fixed;
    top: 0;
    right: -440px; /* width + padding-left + padding-right */
    width: 400px;
    height: 100%;
    background-color: var(--color-page-bg);
    box-shadow: -2px 0 5px var(--color-shadow);
    padding: 20px;
    transition: right 0.3s ease;
    display: block;
    overflow-y: auto;
}

#settingsPage.open {
    right: 0;
}

#closeSettingsButton {
    background-color: transparent;
    color: var(--color-button-primary);
    border: none;
    font-size: 24px;
    position: absolute;
    top: 10px;
    right: 10px;
}

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

#bookShelf {
    display: grid;
    width: 100%;
    max-width: 1000px;
}

.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);
}

.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, .bookHeaderTop, .bookHeaderBottom {
    align-items: center;
    cursor: pointer;
    background-color: var(--color-book-bg);
}

.bookHeader {
    display: grid;
    padding: 15px;
}

.bookHeaderTop {
    display: flex;
    margin-bottom: 5px;
}

.editBookTitleButton {
    background-color: transparent;
    width: 23px;
    height: 23px;
    border: none;
    padding: 0;
    margin: 0 15px 0 0;
}

.editBookTitleButton:hover {
    background-color: transparent;
    opacity: 0.8;
}

.bookHeaderBottom {
    display: flex;
    margin-top: 5px;
}

.bookCheckbox {
    margin-right: 10px;
}

.bookTitle {
    font-family: 'Lora', serif;
    flex-grow: 1;
    padding: 0;
}

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

.pagesCount {
    font-family: 'Lora', serif;
    color: var(--color-text-accent);
    margin: 0 5px 0 15px;
    padding: 0;
}

.moveSelectedPagesButton {
    margin-left: 0;
}

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

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

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

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