<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Placeholder Example</title>
    <style>
        .content {
            display: none;
            margin-top: 20px;
        }

        /* First button styling */
#firstButton {
    background-color: orange;  /* Set background color */
    color: white;              /* Text color */
    border: none;              /* Remove border */
    padding: 10px 20px;        /* Padding for size */
    cursor: pointer;           /* Pointer cursor on hover */
    font-size: 16px;           /* Font size */

}

/* Hover effect for the first button */
#firstButton:hover {
    background-color: darkorange; /* Darker shade on hover */
}

/* Second button styling */
#secondButton {
    background-color: green;   /* Set background color */
    color: white;              /* Text color */
    border: none;              /* Remove border */
    padding: 10px 20px;        /* Padding for size */
    cursor: pointer;           /* Pointer cursor on hover */
    font-size: 16px;           /* Font size */

}

/* Hover effect for the second button */
#secondButton:hover {
    background-color: darkgreen; /* Darker shade on hover */
}

    </style>
</head>
<body>

  <button id="firstButton" onclick="showContent('content1')">Go to the Create Your Own Flashcards page (Click Here)</button>
<button id="secondButton" onclick="showContent('content2')">Go to the Flashcards Practice & Study page</button>


    <div id="content1" class="content">



      <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flashcards with Edit and Delete</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }

        h1, h3 {
            color: #333;
        }

        input[type="text"], select, button {
            width: 92%;
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #0056b3;
        }

        #flashcards-container {
            margin-top: 20px;
        }

        .flashcard {
            background-color: #ffffff;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 15px;
            transition: transform 0.2s;
        }

        .flashcard:hover {
            transform: translateY(-5px);
        }

        .flashcard-topic,
        .flashcard-question,
        .flashcard-answer {
            margin: 5px 0;
        }

        .flashcard-buttons {
            display: flex;
            gap: 10px;
        }

        #log-container {
            margin-top: 20px;
            background-color: #ffffff;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            max-height: 300px;
            overflow-y: auto;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        pre {
            margin: 0;
            font-size: 14px;
            color: #333;
        }

        .delete-flashcard {
            background-color: #dc3545;
        }

        .delete-flashcard:hover {
            background-color: #c82333;
        }

        .edit-flashcard {
            background-color: #28a745;
        }

        .edit-flashcard:hover {
            background-color: #218838;
        }

         #selected-topic {
            font-weight: bold;
            margin-top: 10px;
        }
        #warning {
            color: red;
            display: none;
        }



    .dropdown-menu {
        background-color: white;
        border: 1px solid #ddd;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        padding: 15px;
        position: absolute;
         width: 400px;
        z-index: 1000;
    }

    .dropdown-menu button {
        margin: 5px;
        padding: 10px;
        font-size: 14px;
        cursor: pointer;
    }

    .dropdown-menu button:hover {
        background-color: #f0f0f0;
    }


    h2 {
        margin-left: 20px;
    }

     h3 {
        margin-left: 20px;
    }


        #log-container,
h4 {
        display: none;
}


    </style>
</head>
<body>
    <hr style="border: none; height: 3px; background: linear-gradient(to right, #ff7e5f, #feb47b);">

   <h2>Create Flashcards with Edit and Delete</h2>


   <div class="container">

<button id="toggleButton" onclick="toggleDropdownContent(event)">How to Create Flashcards (Step-by-Step - Click Here)</button>

<div id="dropdownContent1" class="dropdown" style="display: none;">
        <div id="dropdown-content">


<span class="close" onclick="closeDropdown(event)">&times;</span>
         <br>
        <h2>Steps to Create and Manage Flashcards</h2>
        <ol>
                <li><strong>Create a Topic:</strong>
                        <ul>
                                <li>Use the "Create Topic" button to create a new topic.</li>
                                <li>If the topic already exists, select it from the topic list.</li>
                        </ul>
                </li>
                <br>
                <hr style="border: 1px solid #007BFF;">
                <li><strong>Add Flashcards:</strong>
                        <ul>
                                <li>Input your question and answer in the respective input fields.</li>
                                <li>Click the "Add Flashcard" button to save the flashcard to the selected topic.</li>
                        </ul>
                </li>
                <br>
                <hr style="border: 1px solid #28A745;">
                <li><strong>Edit Flashcards:</strong>
                        <ul>
                                <li>Use the "Select Topic" filter to choose the topic you want to edit.</li>
                                <li>After applying the filter, only the flashcards from the selected topic will be displayed.</li>
                                <li>Click the "Edit" button to modify the flashcard content and save changes by clicking the "Save" button.</li>
                        </ul>
                </li>
                <br>
                <hr style="border: 1px solid #DC3545;">
                <li><strong>Delete Flashcards:</strong>
                        <ul>
                                <li>To delete a flashcard entirely, use the "Delete" button for the specific flashcard.</li>
                        </ul>
                </li>
                <br>


                <hr style="border: 1px solid #FFC107;">
                <li><strong>Practice Flashcards:</strong>
                        <ul>
                                <li>Once flashcards are created, click the "Go to Flashcards Practice Page" button to access the practice and Review (recall) section.</li>
                        </ul>
                </li>
                <br>
                <hr style="border: 1px solid #17A2B8;">


        </ol>

</div>


    </div>


       </div>





    <h3>Create Topic</h3>
    <input type="text" id="topic-input" placeholder="Enter topic">
    <button id="create-topic">Create Topic</button>

    <h3>Select Topic</h3>
    <select id="topic-select">
        <option value="">--Select a Topic--</option>
    </select>



   <h3>Add Question and Answer</h3>
    <div id="selected-topic">No topic selected</div>
    <div id="warning">Please select a topic before adding a flashcard.</div>
    <input type="text" id="question-input" placeholder="Enter question">
    <input type="text" id="answer-input" placeholder="Enter answer">
    <button id="add-flashcard">Add Flashcard</button>

   <hr style="border: none; height: 3px; background: linear-gradient(to right, #ff7e5f, #feb47b);">

     <h3>Filter Flashcards by Topic to Edit</h3>
    <select id="filter-select">
        <option value="">--All Topics--</option>
    </select>
    <button id="filter-flashcards">Filter</button>

    <h3>Flashcards</h3>
    <div id="flashcards-container1"></div>

        <div id="deleteDropdown" class="dropdown-menu" style="display: none;">
        <p>Are you sure you want to delete this flashcard?</p>
        <button id="confirmDelete">Yes</button>
        <button id="cancelDelete">No</button>
</div>

  <h4>Logs</h4>
    <div id="log-container"></div>



<script>
 let db;
const dbName = "FlashcardProgress1DBAA";
const flashcardsStoreName = "Flashcards store";
const progressMetricsStoreName = "ProgressMetrics store";

const topics = {};
const flashcards = [];
let topicCount = 0;
let flashcardCount = 0;

let filteredTopics = [];
let filterStage = null;
let reviewStages = {};
let completedFlashcards = [];
let currentDate = new Date();
const reviewStageColors = { 0: 'red', 1: 'pink', 2: 'blue', 3: 'green' };

// Open IndexedDB
function openDatabase() {
    const request = indexedDB.open('FlashcardProgress1DBAA', 1);

    request.onupgradeneeded = (event) => {
        db = event.target.result;

        if (!db.objectStoreNames.contains('Flashcards store')) {
            db.createObjectStore('Flashcards store', { keyPath: 'id', autoIncrement: true });
        }

        if (!db.objectStoreNames.contains('ProgressMetrics store')) {
            db.createObjectStore('ProgressMetrics store', { keyPath: 'metricId', autoIncrement: true });
        }
    };

    request.onsuccess = (event) => {
        db = event.target.result;
        console.log('Database "FlashcardProgress1DBAA" opened successfully');
        retrieveLog();
    };

    request.onerror = (event) => {
        console.error('Database error:', event.target.errorCode);
    };
}

// Save log to IndexedDB
function saveLog() {
    if (!db) {
        console.error('Database is not initialized');
        return;
    }

    const transaction = db.transaction(['Flashcards store'], 'readwrite');
    const store = transaction.objectStore('Flashcards store');

    const logEntry = {
        id: 1,
        topics,
        flashcards
    };

    const request = store.put(logEntry);

    request.onsuccess = () => {
        console.log('Log saved successfully');
    };

    request.onerror = (event) => {
        console.error('Error saving log:', event.target.errorCode);
    };
}

function retrieveLog() {
    if (!db) {
        console.error('Database is not initialized');
        return;
    }

    const transaction = db.transaction(['Flashcards store'], 'readonly');
    const store = transaction.objectStore('Flashcards store');
    const request = store.get(1);

    request.onsuccess = (event) => {
        const logEntry = request.result;
        if (logEntry) {
            Object.assign(topics, logEntry.topics);

            // Check for duplicates before adding
            logEntry.flashcards.forEach(flashcard => {
                if (!flashcards.some(existingCard => existingCard.id === flashcard.id)) {
                    flashcards.push(flashcard);
                }
            });

            topicCount = Object.keys(topics).length;
            flashcardCount = flashcards.length;
            updateLog();
            displayFlashcards();
            populateTopics();
        } else {
            console.log('No log entry found');
        }
    };

    request.onerror = (event) => {
        console.error('Error retrieving log:', event.target.errorCode);
    };
}




// Update log on the page
function updateLog() {
    const logContainer = document.getElementById('log-container');
    logContainer.innerHTML = `
        <pre>const topics = ${JSON.stringify(topics, null, 2)};</pre>
        <pre>const flashcards = ${JSON.stringify(flashcards, null, 2)};</pre>
    `;
    saveLog();
}

// Populate topics in dropdowns
function populateTopics() {
    const topicSelect = document.getElementById('topic-select');
    const filterSelect = document.getElementById('filter-select');
    topicSelect.innerHTML = '<option value="">--Select a Topic--</option>';
    filterSelect.innerHTML = '<option value="">--All Topics--</option>';

    Object.keys(topics).forEach((key) => {
        const option = document.createElement('option');
        option.value = key;
        option.textContent = topics[key];
        topicSelect.appendChild(option);
        filterSelect.appendChild(option.cloneNode(true));
    });
}

// Display flashcards on the page
function displayFlashcards(filterTopic = '') {
    const container = document.getElementById('flashcards-container1');
    container.innerHTML = '';

    flashcards.forEach(({ id, topic, question, answer }) => {
        if (!filterTopic || topic === filterTopic) {
            const topicName = topics[topic];
            const flashcardHTML = `
                <div class="flashcard" data-id="${id}">
                    <div class="flashcard-content">
                        <p class="flashcard-topic"><strong>Topic:</strong> <span class="topic-name">${topicName}</span></p>
                        <p class="flashcard-question"><strong>Q:</strong> <span class="question-text">${question}</span></p>
                        <p class="flashcard-answer"><strong>A:</strong> <span class="answer-text">${answer}</span></p>
                    </div>
                    <div class="flashcard-buttons">
                        <button class="edit-flashcard">Edit</button>
                        <button class="delete-flashcard">Delete</button>
                    </div>
                </div>
            `;
            container.innerHTML += flashcardHTML;
        }
    });

    setupFlashcardButtons();
}

// Setup edit and delete buttons
function setupFlashcardButtons() {
    document.querySelectorAll('.edit-flashcard').forEach(button => {
        button.addEventListener('click', handleEditFlashcard);
    });

    document.querySelectorAll('.delete-flashcard').forEach(button => {
        button.addEventListener('click', handleDeleteFlashcard);
    });
}

// Recalculate topic numbering
function recalculateTopicNumbers() {
    let newTopicCount = 0;
    const updatedTopics = {};

    Object.keys(topics)
        .sort((a, b) => parseInt(a.replace('topic', '')) - parseInt(b.replace('topic', '')))
        .forEach(key => {
            newTopicCount++;
            const oldTopicName = topics[key].split('. ')[1];
            updatedTopics[key] = `${newTopicCount}. ${oldTopicName}`;
        });

    Object.assign(topics, updatedTopics);
    populateTopics();
}

// Update dropdown options
function updateDropdownOption(topicKey, newTopicName) {
    const selectTopic = document.getElementById('topic-select');
    const filterSelect = document.getElementById('filter-select');

    Array.from(selectTopic.options).forEach(option => {
        if (option.value === topicKey) {
            option.textContent = newTopicName;
        }
    });

    Array.from(filterSelect.options).forEach(option => {
        if (option.value === topicKey) {
            option.textContent = newTopicName;
        }
    });
}

// Remove topic from dropdowns
function removeTopicFromDropdowns(topicKey) {
    const selectTopic = document.getElementById('topic-select');
    const filterSelect = document.getElementById('filter-select');

    Array.from(selectTopic.options).forEach(option => {
        if (option.value === topicKey) {
            selectTopic.removeChild(option);
        }
    });

    Array.from(filterSelect.options).forEach(option => {
        if (option.value === topicKey) {
            filterSelect.removeChild(option);
        }
    });
}

// Handle flashcard editing
function handleEditFlashcard(e) {
    const flashcard = e.target.closest('.flashcard');
    const content = flashcard.querySelector('.flashcard-content');
    const isEditing = e.target.textContent === 'Save';

    if (isEditing) {
        const newTopicName = content.querySelector('.edit-topic').value.trim();
        const newQuestion = content.querySelector('.edit-question').value.trim();
        const newAnswer = content.querySelector('.edit-answer').value.trim();

        const flashcardData = flashcards.find(f => f.id == flashcard.getAttribute('data-id'));
        if (flashcardData) {
            flashcardData.question = newQuestion;
            flashcardData.answer = newAnswer;

            const oldTopicKey = flashcardData.topic;
            const oldTopicName = topics[oldTopicKey].split('. ')[1];

            if (newTopicName && newTopicName !== oldTopicName) {
                topics[oldTopicKey] = topics[oldTopicKey].replace(oldTopicName, newTopicName);
                updateDropdownOption(oldTopicKey, topics[oldTopicKey]);
            }

            content.innerHTML = `
                <p class="flashcard-topic"><strong>Topic:</strong> <span class="topic-name">${topics[oldTopicKey]}</span></p>
                <p class="flashcard-question"><strong>Q:</strong> <span class="question-text">${newQuestion}</span></p>
                <p class="flashcard-answer"><strong>A:</strong> <span class="answer-text">${newAnswer}</span></p>
            `;
            e.target.textContent = 'Edit';
            updateLog();
        }
    } else {
        const topicName = content.querySelector('.topic-name').textContent.split('. ')[1];
        const question = content.querySelector('.question-text').textContent;
        const answer = content.querySelector('.answer-text').textContent;

        content.innerHTML = `
            <p class="flashcard-topic"><strong>Topic:</strong> <input type="text" class="edit-topic" value="${topicName}"></p>
            <p class="flashcard-question"><strong>Q:</strong> <input type="text" class="edit-question" value="${question}"></p>
            <p class="flashcard-answer"><strong>A:</strong> <input type="text" class="edit-answer" value="${answer}"></p>
        `;
        e.target.textContent = 'Save';
    }
}


function handleDeleteFlashcard(e) {
    const flashcard = e.target.closest('.flashcard');
    const id = flashcard.getAttribute('data-id');
    const dropdown = document.getElementById('deleteDropdown');

    // Show dropdown
    toggleDropdown(e, 'deleteDropdown');

    // Attach event listeners for confirmation
    document.getElementById('confirmDelete').onclick = () => {
        const index = flashcards.findIndex(f => f.id == id);

        if (index > -1) {
            const topicKey = flashcards[index].topic;
            flashcards.splice(index, 1);

            const remainingFlashcards = flashcards.filter(f => f.topic === topicKey);

            if (remainingFlashcards.length === 0) {
                delete topics[topicKey];
                removeTopicFromDropdowns(topicKey);
                recalculateTopicNumbers();
            }

            displayFlashcards();
            updateLog();
        }

        // Hide dropdown after action
        dropdown.style.display = 'none';
    };

    // Handle cancel action
    document.getElementById('cancelDelete').onclick = () => {
        dropdown.style.display = 'none';
    };
}



function toggleDropdown(event, dropdownId) {
    event.stopPropagation(); // Prevent immediate closing due to outside click listener

    const dropdown = document.getElementById(dropdownId);
    const isVisible = dropdown.style.display === "block";

    if (isVisible) {
        dropdown.style.display = "none";
        return;
    }

    // Show dropdown and calculate its position
    dropdown.style.display = "block";
    dropdown.style.position = "absolute";
    dropdown.style.width = "100vw"; // Full screen width
    dropdown.style.left = "0"; // Align to the left edge of the screen

    const buttonRect = event.target.getBoundingClientRect(); // Get bounding box of the button

    // Position dropdown below the button
    const top = buttonRect.bottom + window.scrollY + 10; // Add a small gap (10px)
    dropdown.style.top = `${top}px`;
}


// Add new topic
document.getElementById('create-topic').addEventListener('click', () => {
    const topicName = document.getElementById('topic-input').value.trim();
    if (topicName) {
        topicCount++;
        const topicKey = `topic${topicCount}`;
        topics[topicKey] = `${Object.keys(topics).length + 1}. ${topicName}`;

        recalculateTopicNumbers();
        populateTopics();
        document.getElementById('topic-input').value = '';
        updateLog();
    }
});

// Select topic for flashcard addition
document.getElementById('topic-select').addEventListener('change', () => {
    const selectedTopic = document.getElementById('topic-select').value;
    const topicName = topics[selectedTopic] || 'No topic selected';
    document.getElementById('selected-topic').textContent = `Selected Topic: ${topicName}`;
    document.getElementById('warning').style.display = 'none';
});

// Add flashcard
document.getElementById('add-flashcard').addEventListener('click', () => {
    const selectedTopic = document.getElementById('topic-select').value;
    const question = document.getElementById('question-input').value.trim();
    const answer = document.getElementById('answer-input').value.trim();

    // Limit flashcards for the free version
    const MAX_FREE_FLASHCARDS = 10;

    // Remove previous alerts if any
    const existingAlert = document.getElementById('flashcard-alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    if (flashcards.length >= MAX_FREE_FLASHCARDS) {
        const alertMessage = document.createElement('div');
        alertMessage.id = 'flashcard-alert';
        alertMessage.style.color = 'red';
        alertMessage.style.border = '1px solid red';
        alertMessage.style.padding = '10px';
        alertMessage.style.marginTop = '10px';
        alertMessage.textContent = 'You have reached the limit of 10 flashcards in the free version. Unlock the premium version to add more (Unlimited Adding)!';
        document.getElementById('add-flashcard').insertAdjacentElement('afterend', alertMessage);
        return;
    }

    if (!selectedTopic) {
        const alertMessage = document.createElement('div');
        alertMessage.id = 'flashcard-alert';
        alertMessage.style.color = 'red';
        alertMessage.style.border = '1px solid red';
        alertMessage.style.padding = '10px';
        alertMessage.style.marginTop = '10px';
        alertMessage.textContent = 'Please select a topic for the flashcard!';
        document.getElementById('add-flashcard').insertAdjacentElement('afterend', alertMessage);
        return;
    }

    if (question && answer) {
        flashcardCount++;
        flashcards.push({
            id: flashcardCount,
            topic: selectedTopic,
            question,
            answer
        });

        document.getElementById('question-input').value = '';
        document.getElementById('answer-input').value = '';
        displayFlashcards();
        updateLog();
    }
});



// Filter flashcards by topic
document.getElementById('filter-flashcards').addEventListener('click', () => {
    const selectedTopic = document.getElementById('filter-select').value;
    displayFlashcards(selectedTopic);
});

// Apply filter when a topic is selected
document.getElementById('filter-select').addEventListener('change', () => {
    const selectedTopic = document.getElementById('filter-select').value;
    displayFlashcards(selectedTopic); // Filter flashcards based on selected topic
});


// Initialize the database
openDatabase();



</script>


</body>
</html>






    </div>

    <div id="content2" class="content">


     <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flashcard System with Pagination and Review Tracking</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        /* General Styles */
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            padding: 20px;
            box-sizing: border-box;
        }
        .app-header {
            width: auto;
            background-color: #6200ea;
            padding: 15px 20px;
            box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
            color: white;
            font-size: 24px;
            font-weight: 500;
            text-align: center;
        }
        .log-container {
            margin-top: 20px;
            width: 100%;
            max-width: 600px;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
            padding: 15px;
            overflow-y: auto;
            max-height: 200px;
        }
        .log {
            font-size: 14px;
            color: #333;
            line-height: 1.5;
        }
    </style>

    <style>
/* General Styles */
body {
    font-family: 'Roboto', sans-serif;
    background-color: #f5f5f5;
    margin: 0;
    padding: 0;
    overflow-x: hidden; /* Prevent horizontal scrolling */
}

.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}



.date-changer {
    margin-bottom: 20px;
    font-size: 16px;
}

.topic-filter, #layout-select {
    width: 100%;
    font-size: 16px;
    padding: 12px;
    border-radius: 8px;
    border: 1px solid #ddd;
    background-color: #ffffff;
    color: #333;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
    appearance: none;
    cursor: pointer;
    text-align: left;
}

.filter-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 15px;
    margin-bottom: 20px;
    width: 100%;
    max-width: 300px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
}

.filter-btn, .show-all-btn, .apply-btn {
    background-color: #6200ea;
    color: #fff;
    padding: 12px 15px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: background-color 0.3s, box-shadow 0.3s;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.15);
}

.filter-btn:hover, .apply-btn:hover {
    background-color: #3700b3;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}

/* Show All Button Distinct Style */
.show-all-btn {
    background-color: #03dac6;
    color: #fff;
}

.show-all-btn:hover {
    background-color: #018786;
}

.badge {
    background-color: #fff;
    color: #6200ea;
    padding: 4px 10px;
    border-radius: 8px;
    font-weight: 500;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 5px;
    box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
}

.modern-card {
    position: relative;
    background-color: white;
    border-radius: 15px;
    width: 100%;
    max-width: 100%; /* Full width to avoid scrolling in vertical layout */
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
    transition: box-shadow 0.3s;
    border: 2px solid #ddd;
    box-sizing: border-box; /* Ensure padding is contained within the card */
}

.question {
    font-size: 20px;
    font-weight: 500;
    color: #333;
    margin-bottom: 10px;
    padding-right: 30px; /* Space for the bookmark */
}

.answer {
    font-size: 18px;
    color: #333;
    margin-top: 10px;
    padding: 10px;
    border-radius: 8px;
    background-color: #f9f9f9;
    display: none;
}

.buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
}
.dont-know-btn, .know-btn {
    padding: 10px 20px;
    width: auto;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    color: #fff;
}

.dont-know-btn {
    background-color: #e53935;
}

.know-btn {
    background-color: #388e3c;
}

/* Hover effect for dont-know-btn */
.dont-know-btn:hover {
    background-color: #d32f2f; /* Darker shade of red */
}

/* Hover effect for know-btn */
.know-btn:hover {
    background-color: #2e7d32; /* Darker shade of green */
}

.bookmark {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 18px;
    color: #ddd;
    cursor: default;
    transition: color 0.3s;
}

.review-metric {
    text-align: center;
    font-size: 16px;
    font-weight: 500;
    color: #555;
    margin-top: 15px;
}

.filter-info {
    background-color: #e3f2fd;
    color: #1e88e5;
    padding: 10px 15px;
    border-radius: 8px;
    font-weight: 500;
    font-size: 16px;
    margin-bottom: 20px;
    text-align: center;
    width: 100%;
    max-width: 600px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}

.topic-header {
    font-size: 24px;
    font-weight: 700;
    color: #6200ea;
    margin: 20px 0 10px;
    text-align: center;
    width: 100%;
}

/* Hide extra elements in horizontal layout */
.horizontal-layout .modern-card {
    display: none; /* Only the current flashcard will be displayed in the horizontal layout */
}

.horizontal-layout .navigation-buttons {
    display: flex; /* Show navigation buttons in horizontal layout */
}

.horizontal-layout .flashcard-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 110%; /* Use full width */
    max-width: 800px; /* Adjust max-width if needed for screen fit */
    padding: 0 20px;
    box-sizing: border-box;
}

.horizontal-layout .modern-card {
    width: 110%; /* Stretch to fill container */
    max-width: 800px; /* Optional: adjust for full screen width */
}

/* Horizontal layout info box styling */
#horizontal-info {
    display: none; /* Only visible in horizontal layout */
    text-align: center;
    margin: 15px 0;
    padding: 10px;
    background-color: #f0f0f0;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    font-family: 'Roboto', sans-serif;
}

#horizontal-topic {
    font-size: 20px;
    font-weight: 700;
    color: #6200ea;
    margin-bottom: 5px;
}

#horizontal-position {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}


 .navigation-buttons {
    display: flex;
    justify-content: center; /* Center buttons on smaller screens */
        gap: 30px;
    width: 100%;
    max-width: 800px; /* Adjust as needed */
    margin: 20px auto;
    padding: 10px 20px;
    box-sizing: border-box;
    margin-bottom: 40px;
}

.navigation-buttons button {
    background-color: #6200ea; /* Primary color */
    color: #ffffff;
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s, box-shadow 0.3s;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.15);
}

.navigation-buttons button:disabled {
    background-color: #9e9e9e; /* Gray color when disabled */
    cursor: not-allowed;
    box-shadow: none;
}

.navigation-buttons button:hover:not(:disabled) {
    background-color: #3700b3; /* Darker color on hover */
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}


.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0,0.4);
    padding-top: 60px;
}

.modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 400px;
    text-align: center;
}

.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}


    /* Ensure flashcards-container stretches fully in vertical layout */
.vertical-layout .flashcard-container {
        width: 100%; /* Use full width in vertical layout */
        max-width: none; /* Remove max-width constraint */
        padding: 0; /* Optional: remove padding if added */
        box-sizing: border-box;
        margin: 0 auto; /* Center align in the container */
}

/* Ensure container and flashcards align correctly in all layouts */
.flashcard-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
}

/* Add this class to body or main container when in vertical layout mode */
.vertical-layout .container {
        width: 100%; /* Ensure container width is full */
}



/* Dropdown container styling */
.dropdown {
    display: none; /* Hidden by default */
    position: absolute;
    background-color: #ffffff;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.15);
    width: 400px;
    z-index: 1000;
}

.dropdown-content {
    color: #333;
    font-size: 16px;
}

.close {
    position: absolute;
    top: 5px;
    right: 10px;
    font-size: 20px;
    cursor: pointer;
}






    </style>
</head>
<body>

<!-- App Header -->
<div class="app-header">
    MBBS Flashcards Study
</div>

<hr>
<p style="margin-left: 20px; font-size: 12px;"><b>Create your own Flashcards</b>: Add difficult-to-remember points daily during preparation.</p>
<p style="margin-left: 20px; font-size: 12px;"><b>Review with Spaced Repetition</b>: Reinforce and retain information effectively in your brain.</p>
<p style="margin-left: 20px; font-size: 12px;"><b>Master the Syllabus</b>: Memorize challenging concepts & facts smartly and complete all 4 rounds of revision before the exam.</p>
<hr>




<!-- Main Container -->
<div class="container">


<button id="toggleButton" onclick="toggleDropdownContent(event)">How to Use the Flashcard System (Step-by-Step - Click Here)</button>

<div id="dropdownContent2" class="dropdown" style="display: none;">
    <div id="dropdown-content">
<!-- Close "X" inside the dropdown -->
<span class="close" onclick="closeDropdown(event)">&times;</span>
        <h2>How to Use the Flashcard System</h2>

        <ol>
            <li><strong>Select Layout:</strong>
                <ul>
                    <li>Choose how you want to view flashcards:</li>
                    <li><strong>Horizontal Layout:</strong> One flashcard displayed at a time.</li>
                    <li><strong>Vertical Layout (Default):</strong> Flashcards shown one below another.</li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #007BFF;">

            <li><strong>Select Topics:</strong>
                <ul>
                    <li>Pick multiple topics you want to study.</li>
                    <li>At the end of each topic, you’ll see:
                        <ul>
                            <li>Total flashcards in that topic.</li>
                            <li>Flashcards you’ve reviewed at least once (e.g., <strong>(2/6)</strong> means 2 out of 6 reviewed).</li>
                        </ul>
                    </li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #28A745;">

            <li><strong>Apply Filter:</strong>
                <ul>
                    <li>Click <strong>Apply Filter</strong> to display selected topics.</li>
                    <li>All Flashcards of selected topics will appear in your chosen layout (horizontal or vertical).</li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #DC3545;">

            <li><strong>Review Flashcards:</strong>
                <ul>
                    <li>View the flashcard to read the question and try to recall the answer.</li>
        <li>After attempting to recall, use the buttons:</li>
                    <li>Use the buttons:
                        <ul>
                            <li><strong>Know:</strong> If you know the answer.</li>
                            <li><strong>Don’t Know:</strong> If unsure or don’t know the answer.</li>
                            <li>If you initially clicked "Know" but later feel unsure, click "Don’t Know" to adjust your response.</li>
                        </ul>
                    </li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #FFC107;">

            <li><strong>Review Stages:</strong>
                <ul>
                    <li>Each reviewed flashcard shows the next review date.</li>
                    <li>Review stages based on time intervals:
                        <ul>
                            <li><strong>First Review:</strong> 3 days after the first read.</li>
                            <li><strong>Second Review:</strong> 7 days after the first review.</li>
                            <li><strong>Third Review:</strong> 14 days after the second review.</li>
                            <li><strong>Final Review:</strong> 28 days after the third review.</li>
                            <li><strong>Completed:</strong> No further reviews needed.</li>
                        </ul>
                    </li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #17A2B8;">

            <li><strong>Pending Review Flashcards:</strong>
                <ul>
                    <li>Flashcards ready for review are shown in the <strong>Pending Review</strong> section.</li>
                    <li>Pending cards only show from selected topics.</li>
                    <li>To view all pending flashcards from all topics, select and apply <strong>"All Topics"</strong> in the topic section (by default, "All Topics" is applied).</li>
                    <li>When you are inside the Pending Flashcards Review section, to exit this section, click the <strong>"Show All Flashcards"</strong> button. It displays all flashcards (including pending flashcards) from the selected topics.</li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #6C757D;">

            <li><strong>Bookmark Colors:</strong>
                <ul>
                    <li>Flashcard review stages are visually represented:</li>
                    <li><strong>Red:</strong> First Review.</li>
                    <li><strong>Pink:</strong> Second Review.</li>
                    <li><strong>Blue:</strong> Third Review.</li>
                    <li><strong>Green:</strong> Final Review.</li>
                    <li><strong>Gold:</strong> Completed.</li>
                </ul>
            </li>
            <br>
            <hr style="border: 1px solid #343A40;">

              <li><strong>Efficient Learning:</strong>
                <ul>
                    <li>The system ensures:</li>
                    <li><strong>Easy Points Flashcards:</strong> Reviewed in fewer rounds.</li>
                    <li><strong>Moderate/Difficult Points:</strong> Reviewed more frequently in more number of rounds.</li>
                    <li>Saves your time by allocating appropriate focus on difficult flashcards.</li>
                    <li>You can utilize your time efficiently and complete your syllabus within your time schedule.</li>
                </ul>
            </li>

        </ol>
    </div>
</div>

 <br>


     <!-- Dropdown for Layout Selection -->
    <div class="custom-select-container">
        <label for="layout-select"><b>Select Layout:</b></label>
        <select id="layout-select" class="custom-select" onchange="selectLayout(this.value)">
            <option value="vertical">Vertical Layout</option>
            <option value="horizontal">Horizontal Layout</option>
        </select>
    </div>

    <!-- Topic Selection Multi-select -->
    <div class="custom-select-container">
        <label for="topic-filter"><b>Select Multiple Topics & Apply Filter:</b></label>
        <select id="topic-filter" class="topic-filter" multiple>
            <!-- Options will be dynamically populated -->
        </select>
    </div>

    <!-- Apply Filter and Show All Buttons -->
    <button class="apply-btn" onclick="applySelectedTopics()">Apply Selected Topics</button><br>
    <button class="show-all-btn" onclick="showAllFlashcards()">Show All Flashcards</button>

    <!-- Filter Container with Buttons for Review Stages -->
    <div class="filter-container">
        <button class="filter-btn" onclick="filterFlashcards(0)">First Review<br> (Red) <span id="count-stage-0" class="badge">0</span></button>
        <button class="filter-btn" onclick="filterFlashcards(1)">Second Review<br> (Pink) <span id="count-stage-1" class="badge">0</span></button>
        <button class="filter-btn" onclick="filterFlashcards(2)">Third Review<br> (Blue) <span id="count-stage-2" class="badge">0</span></button>
        <button class="filter-btn" onclick="filterFlashcards(3)">Final Review<br> (Green) <span id="count-stage-3" class="badge">0</span></button>
        <button class="filter-btn" id="completed-flashcards-btn" onclick="filterFlashcards(4)">Completed Flashcards<br> 🏆 <span id="count-completed" class="badge">0 completed</span></button>
    </div>

    <div id="filter-info-container"></div> <!-- Filter info container for separate line display -->

<div id="horizontal-info" style="display: none;">
    <div id="horizontal-topic"></div>
    <div id="horizontal-position"></div>
</div>



    <!-- Flashcard Display Area -->
    <div id="flashcards-container" class="flashcard-container">
        <!-- Flashcards will be rendered here dynamically -->
    </div>

    <!-- Navigation for Horizontal Layout -->
    <div class="navigation-buttons" style="display: none;">
        <button id="prev-btn" onclick="navigateFlashcards('prev')" disabled>Previous</button>
        <button id="next-btn" onclick="navigateFlashcards('next')">Next</button>
    </div>
</div>



<!-- Dropdown content that replaces the modal -->
<div id="bookmarkDropdown" class="dropdown">
    <div class="dropdown-content">
        <!-- Close button -->
<!-- Close "X" inside the dropdown -->
<span class="close" onclick="closeDropdown(event)">&times;</span>
        <h2>Review Stage Colors</h2>
        <ul>
            <li><span style="color: red;"><i class="fas fa-bookmark"></i></span> First Review</li>
            <li><span style="color: pink;"><i class="fas fa-bookmark"></i></span> Second Review</li>
            <li><span style="color: blue;"><i class="fas fa-bookmark"></i></span> Third Review</li>
            <li><span style="color: green;"><i class="fas fa-bookmark"></i></span> Final Review</li>
            <li><span style="color: gold;"><i class="fas fa-bookmark"></i></span> Completed</li>
        </ul>
    </div>
</div>


<!-- Dropdown for Inactive Know Button Click -->
<div id="inactiveKnowDropdown" class="dropdown">
    <div class="dropdown-content">
        <span class="close" onclick="closeDropdown('inactiveKnowDropdown')">&times;</span>
        <h2>Button Inactive</h2>
        <p>The "Know" button is inactive until the review is ready. Please wait until the next review date.</p>
    </div>
</div>



<script>
document.addEventListener('DOMContentLoaded', () => {
    openDatabase();
    const layoutSelect = document.getElementById('layout-select');
    const initialLayout = layoutSelect.value || 'vertical';  // Default to vertical
    selectLayout(initialLayout);
});



// Database functions
function openDatabase() {
    const request = indexedDB.open(dbName, 1);

    request.onupgradeneeded = (event) => {
        db = event.target.result;

        if (!db.objectStoreNames.contains(flashcardsStoreName)) {
            db.createObjectStore(flashcardsStoreName, { keyPath: 'id', autoIncrement: true });
        }

        if (!db.objectStoreNames.contains(progressMetricsStoreName)) {
            db.createObjectStore(progressMetricsStoreName, { keyPath: 'metricId', autoIncrement: true });
        }
    };

    request.onsuccess = (event) => {
        db = event.target.result;
        console.log('Database "FlashcardProgressDB" opened successfully');

        // Load flashcards and topics from the database
        loadFlashcardsAndTopics();
        loadProgress();
    };

    request.onerror = (event) => {
        console.error('Database error:', event.target.errorCode);
    };
}

// Load flashcards and topics from 'Flashcards store'
function loadFlashcardsAndTopics() {
    const transaction = db.transaction([flashcardsStoreName], 'readonly');
    const store = transaction.objectStore(flashcardsStoreName);
    const request = store.get(1);  // Retrieve the single log entry with id: 1

    request.onsuccess = (event) => {
        const logEntry = event.target.result;

        if (logEntry) {
            // Clear existing data to prevent duplicates
            flashcards.length = 0; // Clear the flashcards array
            Object.keys(topics).forEach(key => delete topics[key]); // Clear the topics object

            // Populate topics and flashcards from the log entry
            Object.assign(topics, logEntry.topics);
            flashcards.push(...logEntry.flashcards);

            console.log('Flashcards loaded:', flashcards);
            console.log('Topics loaded:', topics);

            // Update the topic dropdown with newly loaded topics
            updateTopicProgress();

            renderFlashcards();  // Ensure flashcards render after loading
        } else {
            console.log('No log entry found');
        }
    };

    request.onerror = (event) => {
        console.error('Error loading flashcards and topics:', event.target.errorCode);
    };
}


// Load progress metrics from 'ProgressMetrics store'
function loadProgress() {
    const transaction = db.transaction([progressMetricsStoreName], "readonly");
    const store = transaction.objectStore(progressMetricsStoreName);
    const request = store.getAll();

    request.onsuccess = (event) => {
        event.target.result.forEach(progress => {
            reviewStages[progress.flashcardId] = {
                reviewStage: progress.reviewStage,
                dueDate: progress.dueDate
            };
        });
        console.log('Progress metrics loaded:', reviewStages);
        applyReviewMetrics();
    };

    request.onerror = (event) => {
        console.error('Error loading progress metrics:', event.target.errorCode);
    };
}

// Save progress metrics to 'ProgressMetrics store'
function saveProgress(id, reviewStage, dueDate, revealedTimestamp) {
    const transaction = db.transaction([progressMetricsStoreName], 'readwrite');
    const store = transaction.objectStore(progressMetricsStoreName);
    const data = { flashcardId: id, reviewStage, dueDate, revealedTimestamp };

    store.put(data);
}

// Flashcard functions
function selectLayout(value) {
    if (value === 'horizontal') {
        switchToHorizontalLayout();
    } else {
        switchToVerticalLayout();
    }
    applyCurrentFilters();
}

function switchToHorizontalLayout() {
    isHorizontal = true;
    document.body.classList.add('horizontal-layout');
    document.body.classList.remove('vertical-layout'); // Remove vertical layout class
    currentFlashcardIndex = 0;
    document.getElementById('horizontal-info').style.display = 'block';
    document.querySelector('.navigation-buttons').style.display = 'flex';
    applyCurrentFilters();
}

function switchToVerticalLayout() {
    isHorizontal = false;
    document.body.classList.add('vertical-layout'); // Add vertical layout class
    document.body.classList.remove('horizontal-layout'); // Ensure horizontal class is removed
    document.getElementById('horizontal-info').style.display = 'none';
    document.querySelector('.navigation-buttons').style.display = 'none';
    applyCurrentFilters();
}


function showFlashcard(index) {
    const flashcards = document.querySelectorAll('.modern-card');
    if (index < 0 || index >= flashcards.length) return;

    flashcards.forEach(flashcard => flashcard.style.display = 'none');

    const currentFlashcard = flashcards[index];
    const topic = currentFlashcard.dataset.topic;
    const topicFlashcards = Array.from(flashcards).filter(f => f.dataset.topic === topic);
    const currentPosition = topicFlashcards.indexOf(currentFlashcard) + 1;
    const totalInTopic = topicFlashcards.length;

    document.getElementById('horizontal-topic').textContent = topics[topic];
    document.getElementById('horizontal-position').textContent = `Flashcard ${currentPosition} of ${totalInTopic}`;

    currentFlashcard.style.display = 'block';

    document.getElementById('prev-btn').disabled = index === 0;
    document.getElementById('next-btn').disabled = index === flashcards.length - 1;
}

function navigateFlashcards(direction) {
    const flashcards = document.querySelectorAll('.modern-card');
    if (direction === 'next' && currentFlashcardIndex < flashcards.length - 1) {
        currentFlashcardIndex++;
    } else if (direction === 'prev' && currentFlashcardIndex > 0) {
        currentFlashcardIndex--;
    }
    showFlashcard(currentFlashcardIndex);
}



function updateTopicProgress() {
    const topicSelect = document.getElementById('topic-filter');
    topicSelect.innerHTML = '';

    // Add 'All Topics' option
    const allOption = document.createElement('option');
    allOption.value = 'all';
    allOption.textContent = 'All Topics';
    topicSelect.appendChild(allOption);

    // Iterate through topics and update progress
    Object.keys(topics).forEach(topicKey => {
        const topicName = topics[topicKey];
        const totalFlashcards = flashcards.filter(card => card.topic === topicKey).length;
        const reviewedFlashcards = flashcards.filter(card => card.topic === topicKey && reviewStages[card.id]).length;

        const option = document.createElement('option');
        option.value = topicKey;

       if (reviewedFlashcards === totalFlashcards && totalFlashcards > 0) {
            option.textContent = `${topicName} 🔹(${reviewedFlashcards}/${totalFlashcards}) ✔️`;
        } else {
            option.textContent = `${topicName} 🔹(${reviewedFlashcards}/${totalFlashcards})`;
        }

        topicSelect.appendChild(option);
    });
}


function applySelectedTopics() {
        const topicSelect = document.getElementById('topic-filter');
        const selectedOptions = Array.from(topicSelect.selectedOptions);
        const selectedTopicValues = selectedOptions.map(option => option.value);

        if (selectedTopicValues.includes('all')) {
                filteredTopics = [];
        } else {
                filteredTopics = selectedTopicValues.filter(value => value !== 'all');
        }

        currentFlashcardIndex = 0;
        renderFlashcards();
}

function renderFlashcards() {
    const flashcardsContainer = document.getElementById('flashcards-container');
    const filterInfoContainer = document.getElementById('filter-info-container');

    flashcardsContainer.innerHTML = ''; // Clear the container
    filterInfoContainer.innerHTML = ''; // Clear the filter info

    const allTopicsSelected = filteredTopics.length === 0 || filteredTopics.length === Object.keys(topics).length;

    const selectedTopicsText = allTopicsSelected
        ? 'All Topics'
        : filteredTopics.map(topic => topics[topic] || 'All Topics').join(', ');

    const selectedReviewStageText = filterStage === null
        ? 'Showing All Flashcards of Selected Topics'
        : `Review Stage: ${getReviewStageLabel(filterStage)} (To Exit the Review stage, Click "Show All Flashcards" Button)` ;

    const filterInfo = document.createElement('div');
    filterInfo.className = 'filter-info';

    const topicsLine = document.createElement('div');
    topicsLine.textContent = `Topics selected: ${selectedTopicsText}`;
    filterInfo.appendChild(topicsLine);

    const reviewStageLine = document.createElement('div');
    reviewStageLine.textContent = selectedReviewStageText;
    filterInfo.appendChild(reviewStageLine);

    filterInfoContainer.appendChild(filterInfo);

    let currentTopic = null;

    flashcards.forEach(flashcard => {
        const reviewStageData = reviewStages[flashcard.id];

        // Check if flashcard's dueDate is reached and it matches the filtered stage
        const isDue = reviewStageData && new Date(reviewStageData.dueDate) <= currentDate;
        const isTopicMatch = filteredTopics.length === 0 || filteredTopics.includes(flashcard.topic);
        let isStageMatch = filterStage === null || (reviewStageData?.reviewStage === filterStage && isDue);

        if (filterStage === 4) {  // Check for completed flashcards
            isStageMatch = reviewStageData?.reviewStage === 4;
        }

        if (isTopicMatch && isStageMatch) {
            if (!isHorizontal && currentTopic !== flashcard.topic) {
                currentTopic = flashcard.topic;
                const topicHeader = document.createElement('div');
                topicHeader.className = 'topic-header';
                topicHeader.textContent = topics[flashcard.topic];
                flashcardsContainer.appendChild(topicHeader);
            }

            const isAnswerVisible = reviewStageData?.revealedTimestamp &&
                (new Date() - new Date(reviewStageData.revealedTimestamp)) < 24 * 60 * 60 * 1000;

            const card = document.createElement('div');
            card.className = 'modern-card';
            card.dataset.flashcardId = flashcard.id;
            card.dataset.topic = flashcard.topic;

            // Remove memory tip and emoji lines from card HTML
            card.innerHTML = `
                <div class="question">${flashcard.question}</div>
                <div class="answer" style="display: ${isAnswerVisible ? 'block' : 'none'}">
                    ${flashcard.answer}
                </div>
                <div class="review-metric"></div>
                <div class="buttons">
                    <button class="dont-know-btn" onclick="handleReviewClick(${flashcard.id}, false)">Don't Know</button>
                    <button class="know-btn" onclick="handleReviewClick(${flashcard.id}, true)" ondblclick="handleInactiveKnowClick(event)">Know</button>
                </div>
                <i class="fas fa-bookmark bookmark" onclick="toggleDropdown(event, 'bookmarkDropdown')"></i>
            `;
            flashcardsContainer.appendChild(card);
        }
    });

    applyReviewMetrics();
    updatePendingCounts();

    if (isHorizontal) {
        currentFlashcardIndex = 0; // Reset index for horizontal layout
        showFlashcard(currentFlashcardIndex);
    }

    attachBookmarkListeners(); // Ensure listeners are attached only to valid elements
}

function attachBookmarkListeners() {
    const bookmarks = document.querySelectorAll('.bookmark');  // Select all bookmark icons
    bookmarks.forEach(bookmark => {
        bookmark.addEventListener('click', (event) => {
            toggleDropdown(event, 'bookmarkDropdown');  // Replace with your dropdown logic
        });
    });
}



function filterFlashcards(stage) {
    filterStage = stage;
    currentFlashcardIndex = 0;
    renderFlashcards();
}


function showAllFlashcards() {
        if (filteredTopics.length === 0) {
                const topicSelect = document.getElementById('topic-filter');
                const selectedOptions = Array.from(topicSelect.selectedOptions);
                filteredTopics = selectedOptions.map(option => option.value).filter(value => value !== 'all');
        }
        filterStage = null;
        currentFlashcardIndex = 0;
        renderFlashcards();
}

function applyReviewMetrics() {
    document.querySelectorAll('.modern-card').forEach(card => {
        const flashcardId = parseInt(card.dataset.flashcardId);
        const reviewMetric = card.querySelector('.review-metric');
        const bookmark = card.querySelector('.bookmark');
        const knowButton = card.querySelector('.know-btn');

        if (reviewStages[flashcardId]) {
            const { reviewStage, dueDate } = reviewStages[flashcardId];
            reviewMetric.dataset.reviewStage = reviewStage;
            reviewMetric.dataset.dueDate = dueDate;

            const timeRemaining = (new Date(dueDate).getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24);

            if (reviewStage === 4) {
                reviewMetric.textContent = '🏆 Final Review: Completed';
                reviewMetric.style.color = 'gold';
                bookmark.style.color = 'gold';
                card.style.borderColor = 'gold';
                knowButton.disabled = true;
                knowButton.style.backgroundColor = 'gray';
            } else if (timeRemaining <= 0) {
                reviewMetric.textContent = '🔔 Ready for Review';
                reviewMetric.style.color = '#388e3c';
                knowButton.disabled = false;
                knowButton.style.backgroundColor = '#388e3c';
                bookmark.style.color = reviewStageColors[reviewStage];
                card.style.borderColor = reviewStageColors[reviewStage];
            } else {
                const stageColor = reviewStageColors[reviewStage];
                reviewMetric.textContent = `${getReviewText(reviewStage, dueDate)}`;
                reviewMetric.style.color = stageColor;
                bookmark.style.color = stageColor;
                card.style.borderColor = stageColor;
                knowButton.disabled = true;
                knowButton.style.backgroundColor = 'gray';
            }
        } else {
            // Reset styles for flashcards without a saved review stage
            bookmark.style.color = '';
            card.style.borderColor = '';
            reviewMetric.textContent = '';
        }
    });
}


function handleReviewClick(flashcardId, isKnow) {
    const flashcard = document.querySelector(`[data-flashcard-id="${flashcardId}"]`);
    const answer = flashcard.querySelector('.answer');
    let reviewStage = reviewStages[flashcardId]?.reviewStage || 0;
    const dueDate = new Date(currentDate);
    const revealedTimestamp = new Date().toISOString();  // Save current timestamp

    answer.style.display = 'block';

    if (isKnow) {
        reviewStage = getNextStage(reviewStage, dueDate);
    } else {
        reviewStage = 0;
        dueDate.setDate(dueDate.getDate() + 3);
    }

    reviewStages[flashcardId] = { reviewStage, dueDate: dueDate.toISOString(), revealedTimestamp };
    saveProgress(flashcardId, reviewStage, dueDate.toISOString(), revealedTimestamp);

    applyReviewMetrics();
    updatePendingCounts();
    updateTopicProgress();
}



function getNextStage(reviewStage, dueDate) {
        if (reviewStage === 0) {
                dueDate.setDate(dueDate.getDate() + 7);
                return 1;
        } else if (reviewStage === 1) {
                dueDate.setDate(dueDate.getDate() + 14);
                return 2;
        } else if (reviewStage === 2) {
                dueDate.setDate(dueDate.getDate() + 28);
                return 3;
        }
        return 4;
}

function getReviewText(reviewStage, dueDate) {
        const timeRemaining = (new Date(dueDate) - currentDate) / (1000 * 60 * 60 * 24);
        return `${["First Review", "Second Review", "Third Review", "Final Review"][reviewStage]} in ${Math.ceil(timeRemaining)} days`;
}

function getReviewStageLabel(stage) {
        const labels = ["First Review", "Second Review", "Third Review", "Final Review"];
        return labels[stage] || "Completed Flashcards List";
}

function updatePendingCounts() {
    const counts = [0, 0, 0, 0, 0]; // Add a count for completed flashcards
    flashcards.forEach(flashcard => {
        const flashcardData = reviewStages[flashcard.id];
        if (flashcardData) {
            if (flashcardData.reviewStage < 4 && new Date(flashcardData.dueDate) <= currentDate) {
                counts[flashcardData.reviewStage]++;
            } else if (flashcardData.reviewStage === 4) {
                counts[4]++;
            }
        }
    });
    counts.forEach((count, index) => {
        if (index < 4) {
            document.getElementById(`count-stage-${index}`).textContent = `${count} pending`;
        } else {
            document.getElementById('count-completed').textContent = `${count} completed`;
        }
    });
}


function simulateDateTimeChange() {
        const dateInput = document.getElementById('current-date').value;
        const timeInput = document.getElementById('current-time').value;

        if (dateInput && timeInput) {
                currentDate = new Date(`${dateInput}T${timeInput}:00`);
        } else {
                currentDate = new Date();
        }
        refreshFlashcards();
}

function refreshFlashcards() {
        applyReviewMetrics();
        updatePendingCounts();
}

function applyCurrentFilters() {
        if (filterStage !== null) {
                filterFlashcards(filterStage);
        } else {
                renderFlashcards();
        }

        if (isHorizontal) {
                currentFlashcardIndex = 0;
                showFlashcard(currentFlashcardIndex);
        }
}



</script>



<script>
// Toggle dropdown near the clicked bookmark icon, centered horizontally in the viewport
function toggleDropdown(event, dropdownId) {
    event.stopPropagation();  // Prevent immediate closing due to outside click listener

    const dropdown = document.getElementById(dropdownId);
    const isVisible = dropdown.style.display === "block";

    // Hide dropdown if already visible
    if (isVisible) {
        dropdown.style.display = "none";
        return;
    }

    // Show and position dropdown
    dropdown.style.display = "block";
    dropdown.style.position = "absolute";

    const rect = event.target.getBoundingClientRect();

    // Set top position just below the clicked bookmark icon
    dropdown.style.top = `${rect.bottom + window.scrollY}px`;

    // Center horizontally in the viewport, using transform for responsive centering
    dropdown.style.left = "50%";
    dropdown.style.transform = "translateX(-50%)";  // Center align horizontally

    // Optional: Set max width for small screens
    dropdown.style.maxWidth = "90vw";  // Allow dropdown to adjust within viewport
}

// Close dropdown when clicking outside of it
window.addEventListener('click', function(event) {
    const dropdown = document.getElementById('bookmarkDropdown');
    if (dropdown && dropdown.style.display === "block" && !dropdown.contains(event.target)) {
        dropdown.style.display = "none";
    }
});

function closeDropdown(dropdownId) {
    const dropdown = document.getElementById(dropdownId);
    if (dropdown) {
        dropdown.style.display = "none";
    }
}



// Handle inactive "Know" button click to show dropdown
function handleInactiveKnowClick(event) {
    if (event.target.disabled) {
        toggleDropdown(event, 'inactiveKnowDropdown');
    }
}

// Function to toggle dropdown visibility
function toggleDropdown(event, dropdownId) {
    event.stopPropagation(); // Prevent immediate closing due to outside click listener

    const dropdown = document.getElementById(dropdownId);
    const isVisible = dropdown.style.display === "block";

    // Hide dropdown if already visible
    if (isVisible) {
        dropdown.style.display = "none";
        return;
    }

    // Show and position dropdown
    dropdown.style.display = "block";
    dropdown.style.position = "absolute";

    const rect = event.target.getBoundingClientRect();

    // Position below the "Know" button
    dropdown.style.top = `${rect.bottom + window.scrollY}px`;
    dropdown.style.left = "50%"; // Center horizontally in the viewport
    dropdown.style.transform = "translateX(-50%)"; // Center alignment

    dropdown.style.maxWidth = "90vw"; // Allow dropdown to adjust within viewport on smaller screens
}

// Close dropdown when clicking outside of it
window.addEventListener('click', function(event) {
    const dropdown = document.getElementById('inactiveKnowDropdown');
    if (dropdown && dropdown.style.display === "block" && !dropdown.contains(event.target)) {
        dropdown.style.display = "none";
    }
});

// Optional: Close dropdown function for specific dropdowns
function closeDropdown(dropdownId) {
    document.getElementById(dropdownId).style.display = "none";
}




// All other flashcard functions and event listeners (unchanged from original)

document.addEventListener('DOMContentLoaded', () => {
    openDatabase();
    const layoutSelect = document.getElementById('layout-select');
    const initialLayout = layoutSelect.value || 'vertical';  // Default to vertical
    selectLayout(initialLayout);
    attachBookmarkListeners(); // Ensure this is called after rendering
});





</script>



    </div>

   <script>
    // Load the second HTML content by default if needed
    document.addEventListener("DOMContentLoaded", function() {
        showContent('content2');  // Load content1 by default
    });

    function showContent(contentId) {
        // Hide all content divs
        document.querySelectorAll('.content').forEach(div => div.style.display = 'none');

        // Show the selected content div
        const contentDiv = document.getElementById(contentId);
        contentDiv.style.display = 'block';

        // If content2 is selected, reload it and load flashcards and topics
        if (contentId === 'content2') {
            loadFlashcardsAndTopics(); // Load flashcards only when content2 is shown
        }
    }

    // Load flashcards and topics from 'Flashcards store'
    function loadFlashcardsAndTopics() {
        const transaction = db.transaction([flashcardsStoreName], 'readonly');
        const store = transaction.objectStore(flashcardsStoreName);
        const request = store.get(1);  // Retrieve the single log entry with id: 1

        request.onsuccess = (event) => {
            const logEntry = event.target.result;

            if (logEntry) {
                // Clear existing data to prevent duplicates
                flashcards.length = 0; // Clear the flashcards array
                Object.keys(topics).forEach(key => delete topics[key]); // Clear the topics object

                // Populate topics and flashcards from the log entry
                Object.assign(topics, logEntry.topics);
                flashcards.push(...logEntry.flashcards);

                console.log('Flashcards loaded:', flashcards);
                console.log('Topics loaded:', topics);

                // Update the topic dropdown with newly loaded topics
                updateTopicProgress();

                renderFlashcards();  // Ensure flashcards render after loading
            } else {
                console.log('No log entry found');
            }
        };

        request.onerror = (event) => {
            console.error('Error loading flashcards and topics:', event.target.errorCode);
        };
    }
</script>





<script>
// Function to Toggle the Dropdown Below the Button
function toggleDropdownContent(event) {
    event.stopPropagation(); // Prevent immediate closing due to outside click listener

    // Get the button that triggered the event
    const button = event.target;

    // Find the corresponding dropdown (assumes it's the next sibling in the DOM)
    const dropdown = button.nextElementSibling;

    // Check if the dropdown is visible
    const isVisible = dropdown.style.display === "block";

    // Hide all open dropdowns
    const dropdowns = document.querySelectorAll('.dropdown');
    dropdowns.forEach(d => {
        d.style.display = 'none';
    });

    // If the clicked dropdown was already open, just close it
    if (isVisible) {
        dropdown.style.display = "none";
        return;
    }

    // Show and position the clicked dropdown
    dropdown.style.display = "block";
    dropdown.style.position = "absolute";

    const rect = button.getBoundingClientRect();

    // Set top position just below the button
    dropdown.style.top = `${rect.bottom + window.scrollY}px`;

    // Center horizontally in the viewport
    dropdown.style.left = "50%";
    dropdown.style.transform = "translateX(-50%)"; // Center horizontally

    // Optional: Set max width for small screens
    dropdown.style.maxWidth = "90vw"; // Allow dropdown to fit within viewport
}

// Close dropdown when clicking outside
window.addEventListener('click', function (event) {
    const dropdowns = document.querySelectorAll('.dropdown');

    dropdowns.forEach(dropdown => {
        if (dropdown.style.display === "block" && !dropdown.contains(event.target)) {
            dropdown.style.display = "none";
        }
    });
});

// Function to Explicitly Close a Dropdown
function closeDropdown(event) {
    event.stopPropagation(); // Prevent triggering the window click listener

    // Find the dropdown containing the clicked close button
    const dropdown = event.target.closest('.dropdown');
    if (dropdown) {
        dropdown.style.display = "none";
    }
}

// Function to Close Dropdown when "X" is Clicked
function closeDropdown(event) {
    event.stopPropagation(); // Prevent triggering the window click listener

    // Find the closest parent dropdown containing the clicked "X"
    const dropdown = event.target.closest('.dropdown');

    // If the dropdown is found, hide it
    if (dropdown) {
        dropdown.style.display = "none";
    }
}



</script>


</body>
</html>
