<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Ultimate Study Planner App</title>
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Montserrat:wght@500;700&display=swap" rel="stylesheet">
    <!-- Chart.js CDN -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Reset & Basic Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Roboto', sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: background-color 0.3s, color 0.3s;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* CSS Variables for Light and Dark Modes */
        :root {
            --bg-color: #f5f7fa;
            --text-color: #333;
            --primary-color: #4CAF50;
            --secondary-color: #2196F3;
            --accent-color: #FFC107;
            --danger-color: #f44336;
            --card-bg-color: #ffffff;
            --input-bg-color: #f0f0f0;
            --border-color: #ddd;
        }

        [data-theme="dark"] {
            --bg-color: #1e1e1e;
            --text-color: #ddd;
            --primary-color: #81C784;
            --secondary-color: #64B5F6;
            --accent-color: #FFD54F;
            --danger-color: #e57373;
            --card-bg-color: #2c2c2c;
            --input-bg-color: #3a3a3a;
            --border-color: #444;
        }

        /* Navbar */
        .navbar {
            background-color: var(--primary-color);
            padding: 15px 20px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .navbar h1 {
            font-family: 'Montserrat', sans-serif;
            font-size: 1.5rem;
        }

        .theme-toggle {
            cursor: pointer;
            font-size: 1.2rem;
            background: none;
            border: none;
            color: white;
            display: flex;
            align-items: center;
        }

        /* Container */
        .container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        /* Sidebar */
        .sidebar {
            width: 250px;
            background-color: var(--card-bg-color);
            border-right: 1px solid var(--border-color);
            padding: 20px;
            transition: transform 0.3s;
            height: calc(100vh - 60px); /* Adjust based on navbar height */
            overflow-y: auto;
        }

        .sidebar h2 {
            margin-bottom: 20px;
            font-family: 'Montserrat', sans-serif;
            font-size: 1.3rem;
            color: var(--primary-color);
        }

        .sidebar ul {
            list-style: none;
        }

        .sidebar ul li {
            margin-bottom: 15px;
            cursor: pointer;
            padding: 10px;
            border-radius: 8px;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar ul li:hover, .sidebar ul li.active {
            background-color: var(--primary-color);
            color: white;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        /* Tabs Content */
        .tab-content {
            display: none;
            animation: fadeIn 0.5s;
        }

        .tab-content.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* Forms */
        form {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
        }

        input[type="text"], input[type="date"], textarea, select {
            padding: 10px;
            border: none;
            border-radius: 8px;
            background-color: var(--input-bg-color);
            flex: 1 1 200px;
            color: var(--text-color);
            transition: background-color 0.3s;
        }

        textarea {
            resize: vertical;
            min-height: 80px;
        }

        input[type="text"]:focus, input[type="date"]:focus, textarea:focus, select:focus {
            outline: none;
            background-color: var(--secondary-color);
            color: white;
        }

        button {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            background-color: var(--primary-color);
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
            font-size: 1rem;
        }

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

        /* Lists */
        .task-list, .flashcard-list, .habit-list, .goal-list, .note-list {
            list-style: none;
        }

        .task-item, .flashcard-item, .habit-item, .goal-item, .note-item {
            background-color: var(--card-bg-color);
            padding: 15px;
            margin-bottom: 15px;
            border-left: 5px solid var(--primary-color);
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            position: relative;
            transition: background-color 0.3s;
        }

        [data-theme="dark"] .task-item, [data-theme="dark"] .flashcard-item, [data-theme="dark"] .habit-item, [data-theme="dark"] .goal-item, [data-theme="dark"] .note-item {
            background-color: #333;
            border-left-color: var(--primary-color);
        }

        .task-item.completed, .habit-item.completed, .goal-item.completed {
            border-left-color: var(--secondary-color);
            text-decoration: line-through;
            color: var(--text-color);
            opacity: 0.7;
        }

        .item-actions {
            position: absolute;
            top: 10px;
            right: 10px;
        }

        .item-actions button {
            background: none;
            border: none;
            cursor: pointer;
            margin-left: 5px;
            font-size: 1.1rem;
            transition: color 0.3s;
            color: var(--text-color);
        }

        .item-actions button:hover {
            color: var(--primary-color);
        }

        /* Modals */
        .modal {
            display: none; 
            position: fixed; 
            z-index: 1000; 
            left: 0;
            top: 0;
            width: 100%; 
            height: 100%; 
            overflow: auto; 
            background-color: rgba(0,0,0,0.5); 
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: var(--card-bg-color);
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            position: relative;
            color: var(--text-color);
        }

        [data-theme="dark"] .modal-content {
            background-color: #2c2c2c;
        }

        .close-modal {
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--danger-color);
            cursor: pointer;
        }

        .close-modal:hover {
            color: var(--text-color);
        }

        /* Charts */
        .chart-container {
            position: relative;
            width: 100%;
            height: 400px;
            margin-bottom: 30px;
        }

        /* Flashcard Review */
        #flashcardContainer {
            display: none;
            margin-top: 20px;
            text-align: center;
        }

        #currentFlashcard {
            padding: 20px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            min-height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            background-color: var(--input-bg-color);
            transition: background-color 0.3s;
        }

        [data-theme="dark"] #currentFlashcard {
            background-color: #3a3a3a;
        }

        #flashcardContainer button {
            margin: 10px 5px;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: -250px;
                top: 0;
                height: 100%;
                transition: transform 0.3s;
                z-index: 1001;
            }

            .sidebar.active {
                transform: translateX(250px);
            }

            .main-content {
                margin-left: 0;
            }

            .menu-toggle {
                display: block;
                cursor: pointer;
                font-size: 1.5rem;
                color: white;
                margin-right: 15px;
            }

            .navbar-left {
                display: flex;
                align-items: center;
            }
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <div class="navbar">
        <div class="navbar-left">
            <span class="menu-toggle" onclick="toggleSidebar()">☰</span>
            <h1>📚 Ultimate Study Planner</h1>
        </div>
        <button class="theme-toggle" onclick="toggleTheme()">🌓</button>
    </div>

    <!-- Container -->
    <div class="container">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <h2>Navigation</h2>
            <ul>
                <li class="active" data-tab="tasksTab">✔️ Tasks</li>
                <li data-tab="calendarTab">📅 Calendar</li>
                <li data-tab="pomodoroTab">⏲️ Pomodoro Timer</li>
                <li data-tab="notesTab">📝 Notes</li>
                <li data-tab="habitsTab">🏃 Habits</li>
                <li data-tab="goalsTab">🎯 Goals</li>
                <li data-tab="flashcardsTab">🃏 Flashcards</li>
                <li data-tab="dashboardTab">📈 Dashboard</li>
            </ul>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Tasks Tab -->
            <section class="tab-content active" id="tasksTab">
                <h2>📋 Tasks</h2>
                <form id="taskForm">
                    <input type="text" id="taskTitle" placeholder="Task Title" required>
                    <input type="date" id="taskDate" required>
                    <textarea id="taskDesc" placeholder="Task Description" required></textarea>
                    <button type="submit">Add Task</button>
                </form>
                <ul class="task-list" id="taskList">
                    <!-- Tasks will be dynamically added here -->
                </ul>
            </section>

            <!-- Calendar Tab -->
            <section class="tab-content" id="calendarTab">
                <h2>📅 Calendar</h2>
                <div class="calendar" id="calendar">
                    <!-- Calendar will be generated here -->
                </div>
            </section>

            <!-- Pomodoro Timer Tab -->
            <section class="tab-content" id="pomodoroTab">
                <h2>⏲️ Pomodoro Timer</h2>
                <div class="timer">
                    <div class="timer-display" id="timerDisplay">25:00</div>
                    <div class="timer-controls">
                        <button id="startTimer">Start</button>
                        <button id="pauseTimer">Pause</button>
                        <button id="resetTimer">Reset</button>
                    </div>
                </div>
            </section>

            <!-- Notes Tab -->
            <section class="tab-content" id="notesTab">
                <h2>📝 Notes</h2>
                <form id="notesForm">
                    <textarea id="noteContent" placeholder="Take a note..." required></textarea>
                    <button type="submit">Add Note</button>
                </form>
                <ul class="note-list" id="notesList">
                    <!-- Notes will be dynamically added here -->
                </ul>
            </section>

            <!-- Habits Tab -->
            <section class="tab-content" id="habitsTab">
                <h2>🏃 Habits</h2>
                <form id="habitsForm">
                    <input type="text" id="habitName" placeholder="Habit Name" required>
                    <select id="habitFrequency" required>
                        <option value="" disabled selected>Frequency</option>
                        <option value="Daily">Daily</option>
                        <option value="Weekly">Weekly</option>
                        <option value="Monthly">Monthly</option>
                    </select>
                    <button type="submit">Add Habit</button>
                </form>
                <ul class="habit-list" id="habitsList">
                    <!-- Habits will be dynamically added here -->
                </ul>
            </section>

            <!-- Goals Tab -->
            <section class="tab-content" id="goalsTab">
                <h2>🎯 Goals</h2>
                <form id="goalsForm">
                    <input type="text" id="goalName" placeholder="Goal Name" required>
                    <input type="date" id="goalDeadline" required>
                    <textarea id="goalDesc" placeholder="Goal Description" required></textarea>
                    <button type="submit">Add Goal</button>
                </form>
                <ul class="goal-list" id="goalsList">
                    <!-- Goals will be dynamically added here -->
                </ul>
            </section>

            <!-- Flashcards Tab -->
            <section class="tab-content" id="flashcardsTab">
                <h2>🃏 Flashcards</h2>
                <form id="flashcardsForm">
                    <input type="text" id="flashcardQuestion" placeholder="Question" required>
                    <textarea id="flashcardAnswer" placeholder="Answer" required></textarea>
                    <button type="submit">Add Flashcard</button>
                </form>
                <button id="startFlashcardReview">Start Review Session</button>
                <div id="flashcardContainer" style="display:none; margin-top:20px;">
                    <div class="flashcard" id="currentFlashcard">
                        <!-- Flashcard content will appear here -->
                    </div>
                    <div style="margin-top:10px; display:flex; justify-content:center; gap:10px;">
                        <button id="showAnswer">Show Answer</button>
                        <button id="nextFlashcard">Next</button>
                    </div>
                </div>
                <ul class="flashcard-list" id="flashcardsList">
                    <!-- Flashcards will be dynamically added here -->
                </ul>
            </section>

            <!-- Dashboard Tab -->
            <section class="tab-content" id="dashboardTab">
                <h2>📈 Dashboard</h2>
                <div class="chart-container">
                    <canvas id="tasksChart"></canvas>
                </div>
                <div class="chart-container">
                    <canvas id="habitsChart"></canvas>
                </div>
                <div class="chart-container">
                    <canvas id="timeChart"></canvas>
                </div>
            </section>
        </main>
    </div>

    <!-- Edit Task Modal -->
    <div id="editTaskModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeModal('editTaskModal')">&times;</span>
            <h2>Edit Task</h2>
            <form id="editTaskForm">
                <input type="text" id="editTaskTitle" placeholder="Task Title" required>
                <input type="date" id="editTaskDate" required>
                <textarea id="editTaskDesc" placeholder="Task Description" required></textarea>
                <button type="submit">Update Task</button>
            </form>
        </div>
    </div>

    <!-- Edit Habit Modal -->
    <div id="editHabitModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeModal('editHabitModal')">&times;</span>
            <h2>Edit Habit</h2>
            <form id="editHabitForm">
                <input type="text" id="editHabitName" placeholder="Habit Name" required>
                <select id="editHabitFrequency" required>
                    <option value="" disabled selected>Frequency</option>
                    <option value="Daily">Daily</option>
                    <option value="Weekly">Weekly</option>
                    <option value="Monthly">Monthly</option>
                </select>
                <button type="submit">Update Habit</button>
            </form>
        </div>
    </div>

    <!-- Edit Goal Modal -->
    <div id="editGoalModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeModal('editGoalModal')">&times;</span>
            <h2>Edit Goal</h2>
            <form id="editGoalForm">
                <input type="text" id="editGoalName" placeholder="Goal Name" required>
                <input type="date" id="editGoalDeadline" required>
                <textarea id="editGoalDesc" placeholder="Goal Description" required></textarea>
                <button type="submit">Update Goal</button>
            </form>
        </div>
    </div>

    <!-- Edit Flashcard Modal -->
    <div id="editFlashcardModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeModal('editFlashcardModal')">&times;</span>
            <h2>Edit Flashcard</h2>
            <form id="editFlashcardForm">
                <input type="text" id="editFlashcardQuestion" placeholder="Question" required>
                <textarea id="editFlashcardAnswer" placeholder="Answer" required></textarea>
                <button type="submit">Update Flashcard</button>
            </form>
        </div>
    </div>

    <script>
        /* ----------------------- Sidebar Toggle for Mobile ----------------------- */
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        /* ----------------------- Theme Toggle ----------------------- */
        function toggleTheme() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
        }

        // Initialize theme based on user preference
        (function() {
            const savedTheme = localStorage.getItem('theme') || 'light';
            document.documentElement.setAttribute('data-theme', savedTheme);
        })();

        /* ----------------------- Tabs Functionality ----------------------- */
        const sidebarItems = document.querySelectorAll('.sidebar ul li');
        const tabContents = document.querySelectorAll('.tab-content');

        sidebarItems.forEach(item => {
            item.addEventListener('click', () => {
                // Remove active class from all sidebar items
                sidebarItems.forEach(i => i.classList.remove('active'));
                // Add active class to clicked item
                item.classList.add('active');
                // Hide all tab contents
                tabContents.forEach(tc => tc.classList.remove('active'));
                // Show the selected tab content
                document.getElementById(item.dataset.tab).classList.add('active');
                // Close sidebar on mobile after selection
                if (window.innerWidth <= 768) toggleSidebar();
            });
        });

        /* ----------------------- Tasks Functionality ----------------------- */
        let tasks = [];
        const taskForm = document.getElementById('taskForm');
        const taskList = document.getElementById('taskList');
        const editTaskModal = document.getElementById('editTaskModal');
        const editTaskForm = document.getElementById('editTaskForm');
        let currentEditTaskId = null;

        // Load Tasks from Local Storage
        function loadTasks() {
            if (localStorage.getItem('tasks')) {
                tasks = JSON.parse(localStorage.getItem('tasks'));
                renderTasks();
            }
        }

        // Add Task
        taskForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const title = document.getElementById('taskTitle').value.trim();
            const date = document.getElementById('taskDate').value;
            const desc = document.getElementById('taskDesc').value.trim();

            if (title && date && desc) {
                const task = {
                    id: Date.now(),
                    title,
                    date,
                    desc,
                    completed: false
                };
                tasks.push(task);
                saveTasks();
                renderTasks();
                updateCalendar();
                updateDashboardCharts();
                taskForm.reset();
            }
        });

        // Save Tasks to Local Storage
        function saveTasks() {
            localStorage.setItem('tasks', JSON.stringify(tasks));
        }

        // Render Tasks
        function renderTasks() {
            taskList.innerHTML = '';
            if (tasks.length === 0) {
                taskList.innerHTML = '<p style="text-align:center; color:#777;">No tasks added yet.</p>';
                return;
            }

            tasks.sort((a, b) => new Date(a.date) - new Date(b.date));
            tasks.forEach(task => {
                const li = document.createElement('li');
                li.className = 'task-item';
                if (task.completed) li.classList.add('completed');

                const title = document.createElement('h3');
                title.textContent = task.title;

                const desc = document.createElement('p');
                desc.textContent = task.desc;

                const meta = document.createElement('small');
                meta.textContent = `Due: ${task.date}`;

                const actions = document.createElement('div');
                actions.className = 'item-actions';

                const completeBtn = document.createElement('button');
                completeBtn.innerHTML = task.completed ? '✅' : '✔️';
                completeBtn.title = task.completed ? 'Mark as Incomplete' : 'Mark as Complete';
                completeBtn.onclick = () => toggleTaskCompletion(task.id);

                const editBtn = document.createElement('button');
                editBtn.innerHTML = '✏️';
                editBtn.title = 'Edit Task';
                editBtn.onclick = () => openEditTaskModal(task.id);

                const deleteBtn = document.createElement('button');
                deleteBtn.innerHTML = '🗑️';
                deleteBtn.title = 'Delete Task';
                deleteBtn.onclick = () => deleteTask(task.id);

                actions.appendChild(completeBtn);
                actions.appendChild(editBtn);
                actions.appendChild(deleteBtn);

                li.appendChild(title);
                li.appendChild(desc);
                li.appendChild(meta);
                li.appendChild(actions);

                taskList.appendChild(li);
            });
        }

        // Toggle Task Completion
        function toggleTaskCompletion(id) {
            tasks = tasks.map(task => {
                if (task.id === id) {
                    task.completed = !task.completed;
                }
                return task;
            });
            saveTasks();
            renderTasks();
            updateCalendar();
            updateDashboardCharts();
        }

        // Delete Task
        function deleteTask(id) {
            if (confirm('Are you sure you want to delete this task?')) {
                tasks = tasks.filter(task => task.id !== id);
                saveTasks();
                renderTasks();
                updateCalendar();
                updateDashboardCharts();
            }
        }

        // Open Edit Task Modal
        function openEditTaskModal(id) {
            currentEditTaskId = id;
            const task = tasks.find(t => t.id === id);
            if (task) {
                document.getElementById('editTaskTitle').value = task.title;
                document.getElementById('editTaskDate').value = task.date;
                document.getElementById('editTaskDesc').value = task.desc;
                editTaskModal.style.display = 'flex';
            }
        }

        // Close Modal
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // Update Task
        editTaskForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const title = document.getElementById('editTaskTitle').value.trim();
            const date = document.getElementById('editTaskDate').value;
            const desc = document.getElementById('editTaskDesc').value.trim();

            if (title && date && desc && currentEditTaskId !== null) {
                tasks = tasks.map(task => {
                    if (task.id === currentEditTaskId) {
                        return { ...task, title, date, desc };
                    }
                    return task;
                });
                saveTasks();
                renderTasks();
                updateCalendar();
                updateDashboardCharts();
                editTaskModal.style.display = 'none';
            }
        });

        /* ----------------------- Calendar Functionality ----------------------- */
        function updateCalendar() {
            generateCalendar();
        }

        function generateCalendar() {
            const calendar = document.getElementById('calendar');
            calendar.innerHTML = ''; // Clear previous calendar

            const today = new Date();
            const currentMonth = today.getMonth();
            const currentYear = today.getFullYear();

            const firstDay = new Date(currentYear, currentMonth).getDay();
            const daysInMonth = new Date(currentYear, currentMonth +1, 0).getDate();

            let tbl = `<table style="width:100%; border-collapse: collapse;">
                        <thead>
                            <tr>
                                <th style="padding:10px;">Sun</th>
                                <th style="padding:10px;">Mon</th>
                                <th style="padding:10px;">Tue</th>
                                <th style="padding:10px;">Wed</th>
                                <th style="padding:10px;">Thu</th>
                                <th style="padding:10px;">Fri</th>
                                <th style="padding:10px;">Sat</th>
                            </tr>
                        </thead>
                        <tbody><tr>`;

            // Blank cells before first day
            for (let i = 0; i < firstDay; i++) {
                tbl += '<td style="padding:10px; border:1px solid var(--border-color);"></td>';
            }

            for (let date = 1; date <= daysInMonth; date++) {
                if ((firstDay + date -1) % 7 === 0 && date !==1 ) {
                    tbl += '</tr><tr>';
                }

                const fullDate = `${currentYear}-${String(currentMonth +1).padStart(2, '0')}-${String(date).padStart(2, '0')}`;
                const dayTasks = tasks.filter(task => task.date === fullDate);

                let tasksHtml = '';
                dayTasks.forEach(task => {
                    tasksHtml += `<li title="${task.desc}" style="background-color: var(--primary-color); color:white; margin-bottom:2px; padding:2px 4px; border-radius:4px; font-size:0.8rem;">${task.title}</li>`;
                });

                tbl += `<td style="padding:10px; border:1px solid var(--border-color); vertical-align: top;">
                            <strong>${date}</strong>
                            <ul style="list-style:none; padding-left:0; margin-top:5px;">${tasksHtml}</ul>
                        </td>`;
            }

            // Blank cells after last day
            const remaining = 7 - ((firstDay + daysInMonth) % 7);
            if (remaining < 7) {
                for (let i = 0; i < remaining; i++) {
                    tbl += '<td style="padding:10px; border:1px solid var(--border-color);"></td>';
                }
            }

            tbl += '</tr></tbody></table>';
            calendar.innerHTML = tbl;
        }

        /* ----------------------- Pomodoro Timer Functionality ----------------------- */
        let timerDisplay = document.getElementById('timerDisplay');
        let startBtn = document.getElementById('startTimer');
        let pauseBtn = document.getElementById('pauseTimer');
        let resetBtn = document.getElementById('resetTimer');

        let timer;
        let timeLeft = 25 * 60; // 25 minutes
        let isRunning = false;

        let pomodoroSessions = parseInt(localStorage.getItem('pomodoroSessions')) || 0;

        startBtn.addEventListener('click', () => {
            if (!isRunning) {
                timer = setInterval(() => {
                    if (timeLeft > 0) {
                        timeLeft--;
                        updateTimerDisplay();
                    } else {
                        clearInterval(timer);
                        alert('Pomodoro session completed!');
                        pomodoroSessions++;
                        localStorage.setItem('pomodoroSessions', pomodoroSessions);
                        updateDashboardCharts();
                        timeLeft = 25 * 60;
                        updateTimerDisplay();
                        isRunning = false;
                        notifyUser('Pomodoro session completed!');
                    }
                }, 1000);
                isRunning = true;
                notifyUser('Pomodoro session started!');
            }
        });

        pauseBtn.addEventListener('click', () => {
            if (isRunning) {
                clearInterval(timer);
                isRunning = false;
                notifyUser('Pomodoro session paused!');
            }
        });

        resetBtn.addEventListener('click', () => {
            clearInterval(timer);
            isRunning = false;
            timeLeft = 25 * 60;
            updateTimerDisplay();
            notifyUser('Pomodoro timer reset!');
        });

        function updateTimerDisplay() {
            let minutes = Math.floor(timeLeft / 60);
            let seconds = timeLeft % 60;
            timerDisplay.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }

        // Initialize Timer Display
        updateTimerDisplay();

        /* ----------------------- Notifications ----------------------- */
        function notifyUser(message) {
            if (Notification.permission === 'granted') {
                new Notification(message);
            } else if (Notification.permission !== 'denied') {
                Notification.requestPermission().then(permission => {
                    if (permission === 'granted') {
                        new Notification(message);
                    }
                });
            }
        }

        /* ----------------------- Notes Functionality ----------------------- */
        let notes = [];
        const notesForm = document.getElementById('notesForm');
        const notesList = document.getElementById('notesList');

        // Load Notes
        function loadNotes() {
            if (localStorage.getItem('notes')) {
                notes = JSON.parse(localStorage.getItem('notes'));
                renderNotes();
            }
        }

        // Add Note
        notesForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const content = document.getElementById('noteContent').value.trim();
            if (content) {
                const note = {
                    id: Date.now(),
                    content
                };
                notes.push(note);
                saveNotes();
                renderNotes();
                updateDashboardCharts();
                notesForm.reset();
            }
        });

        // Save Notes to Local Storage
        function saveNotes() {
            localStorage.setItem('notes', JSON.stringify(notes));
        }

        // Render Notes
        function renderNotes() {
            notesList.innerHTML = '';
            if (notes.length === 0) {
                notesList.innerHTML = '<p style="text-align:center; color:#777;">No notes added yet.</p>';
                return;
            }

            notes.forEach(note => {
                const li = document.createElement('li');
                li.className = 'note-item';

                const p = document.createElement('p');
                p.textContent = note.content;

                const actions = document.createElement('div');
                actions.className = 'item-actions';

                const deleteBtn = document.createElement('button');
                deleteBtn.innerHTML = '🗑️';
                deleteBtn.title = 'Delete Note';
                deleteBtn.onclick = () => deleteNote(note.id);

                actions.appendChild(deleteBtn);

                li.appendChild(p);
                li.appendChild(actions);

                notesList.appendChild(li);
            });
        }

        // Delete Note
        function deleteNote(id) {
            if (confirm('Are you sure you want to delete this note?')) {
                notes = notes.filter(note => note.id !== id);
                saveNotes();
                renderNotes();
                updateDashboardCharts();
            }
        }

        /* ----------------------- Habits Functionality ----------------------- */
        let habits = [];
        const habitsForm = document.getElementById('habitsForm');
        const habitsList = document.getElementById('habitsList');
        const currentDate = new Date().toISOString().split('T')[0];

        // Load Habits
        function loadHabits() {
            if (localStorage.getItem('habits')) {
                habits = JSON.parse(localStorage.getItem('habits'));
                renderHabits();
            }
        }

        // Add Habit
        habitsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const name = document.getElementById('habitName').value.trim();
            const frequency = document.getElementById('habitFrequency').value;

            if (name && frequency) {
                const habit = {
                    id: Date.now(),
                    name,
                    frequency,
                    completedDates: []
                };
                habits.push(habit);
                saveHabits();
                renderHabits();
                updateDashboardCharts();
                habitsForm.reset();
            }
        });

        // Save Habits to Local Storage
        function saveHabits() {
            localStorage.setItem('habits', JSON.stringify(habits));
        }

        // Render Habits
        function renderHabits() {
            habitsList.innerHTML = '';
            if (habits.length === 0) {
                habitsList.innerHTML = '<p style="text-align:center; color:#777;">No habits added yet.</p>';
                return;
            }

            habits.forEach(habit => {
                const li = document.createElement('li');
                li.className = 'habit-item';
                if (isHabitCompletedToday(habit)) li.classList.add('completed');

                const name = document.createElement('span');
                name.textContent = `${habit.name} (${habit.frequency})`;

                const actions = document.createElement('div');
                actions.className = 'item-actions';

                const toggleBtn = document.createElement('button');
                toggleBtn.innerHTML = isHabitCompletedToday(habit) ? '✅' : '✔️';
                toggleBtn.title = isHabitCompletedToday(habit) ? 'Mark as Incomplete' : 'Mark as Complete';
                toggleBtn.onclick = () => toggleHabitCompletion(habit.id);

                const editBtn = document.createElement('button');
                editBtn.innerHTML = '✏️';
                editBtn.title = 'Edit Habit';
                editBtn.onclick = () => openEditHabitModal(habit.id);

                const deleteBtn = document.createElement('button');
                deleteBtn.innerHTML = '🗑️';
                deleteBtn.title = 'Delete Habit';
                deleteBtn.onclick = () => deleteHabit(habit.id);

                actions.appendChild(toggleBtn);
                actions.appendChild(editBtn);
                actions.appendChild(deleteBtn);

                li.appendChild(name);
                li.appendChild(actions);

                habitsList.appendChild(li);
            });
        }

        // Check if Habit is Completed Today
        function isHabitCompletedToday(habit) {
            return habit.completedDates.includes(currentDate);
        }

        // Toggle Habit Completion
        function toggleHabitCompletion(id) {
            habits = habits.map(habit => {
                if (habit.id === id) {
                    if (habit.completedDates.includes(currentDate)) {
                        habit.completedDates = habit.completedDates.filter(date => date !== currentDate);
                    } else {
                        habit.completedDates.push(currentDate);
                    }
                }
                return habit;
            });
            saveHabits();
            renderHabits();
            updateDashboardCharts();
        }

        // Delete Habit
        function deleteHabit(id) {
            if (confirm('Are you sure you want to delete this habit?')) {
                habits = habits.filter(habit => habit.id !== id);
                saveHabits();
                renderHabits();
                updateDashboardCharts();
            }
        }

        // Open Edit Habit Modal
        function openEditHabitModal(id) {
            currentEditTaskId = id;
            const habit = habits.find(h => h.id === id);
            if (habit) {
                document.getElementById('editHabitName').value = habit.name;
                document.getElementById('editHabitFrequency').value = habit.frequency;
                editHabitModal.style.display = 'flex';
            }
        }

        // Update Habit
        editHabitForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const name = document.getElementById('editHabitName').value.trim();
            const frequency = document.getElementById('editHabitFrequency').value;

            if (name && frequency && currentEditTaskId !== null) {
                habits = habits.map(habit => {
                    if (habit.id === currentEditTaskId) {
                        return { ...habit, name, frequency };
                    }
                    return habit;
                });
                saveHabits();
                renderHabits();
                editHabitModal.style.display = 'none';
                updateDashboardCharts();
            }
        });

        /* ----------------------- Goals Functionality ----------------------- */
        let goals = [];
        const goalsForm = document.getElementById('goalsForm');
        const goalsList = document.getElementById('goalsList');

        // Load Goals
        function loadGoals() {
            if (localStorage.getItem('goals')) {
                goals = JSON.parse(localStorage.getItem('goals'));
                renderGoals();
            }
        }

        // Add Goal
        goalsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const name = document.getElementById('goalName').value.trim();
            const deadline = document.getElementById('goalDeadline').value;
            const desc = document.getElementById('goalDesc').value.trim();

            if (name && deadline && desc) {
                const goal = {
                    id: Date.now(),
                    name,
                    deadline,
                    desc,
                    completed: false
                };
                goals.push(goal);
                saveGoals();
                renderGoals();
                updateDashboardCharts();
                goalsForm.reset();
            }
        });

        // Save Goals to Local Storage
        function saveGoals() {
            localStorage.setItem('goals', JSON.stringify(goals));
        }

        // Render Goals
        function renderGoals() {
            goalsList.innerHTML = '';
            if (goals.length === 0) {
                goalsList.innerHTML = '<p style="text-align:center; color:#777;">No goals added yet.</p>';
                return;
            }

            goals.forEach(goal => {
                const li = document.createElement('li');
                li.className = 'goal-item';
                if (goal.completed) li.classList.add('completed');
                if (new Date(goal.deadline) < new Date() && !goal.completed) {
                    li.style.borderLeftColor = 'var(--danger-color)';
                }

                const title = document.createElement('h3');
                title.textContent = goal.name;

                const desc = document.createElement('p');
                desc.textContent = goal.desc;

                const meta = document.createElement('small');
                meta.textContent = `Deadline: ${goal.deadline}`;

                const actions = document.createElement('div');
                actions.className = 'item-actions';

                const completeBtn = document.createElement('button');
                completeBtn.innerHTML = goal.completed ? '✅' : '✔️';
                completeBtn.title = goal.completed ? 'Mark as Incomplete' : 'Mark as Complete';
                completeBtn.onclick = () => toggleGoalCompletion(goal.id);

                const editBtn = document.createElement('button');
                editBtn.innerHTML = '✏️';
                editBtn.title = 'Edit Goal';
                editBtn.onclick = () => openEditGoalModal(goal.id);

                const deleteBtn = document.createElement('button');
                deleteBtn.innerHTML = '🗑️';
                deleteBtn.title = 'Delete Goal';
                deleteBtn.onclick = () => deleteGoal(goal.id);

                actions.appendChild(completeBtn);
                actions.appendChild(editBtn);
                actions.appendChild(deleteBtn);

                li.appendChild(title);
                li.appendChild(desc);
                li.appendChild(meta);
                li.appendChild(actions);

                goalsList.appendChild(li);
            });
        }

        // Toggle Goal Completion
        function toggleGoalCompletion(id) {
            goals = goals.map(goal => {
                if (goal.id === id) {
                    goal.completed = !goal.completed;
                }
                return goal;
            });
            saveGoals();
            renderGoals();
            updateDashboardCharts();
        }

        // Delete Goal
        function deleteGoal(id) {
            if (confirm('Are you sure you want to delete this goal?')) {
                goals = goals.filter(goal => goal.id !== id);
                saveGoals();
                renderGoals();
                updateDashboardCharts();
            }
        }

        // Open Edit Goal Modal
        function openEditGoalModal(id) {
            currentEditTaskId = id;
            const goal = goals.find(g => g.id === id);
            if (goal) {
                document.getElementById('editGoalName').value = goal.name;
                document.getElementById('editGoalDeadline').value = goal.deadline;
                document.getElementById('editGoalDesc').value = goal.desc;
                editGoalModal.style.display = 'flex';
            }
        }

        // Update Goal
        editGoalForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const name = document.getElementById('editGoalName').value.trim();
            const deadline = document.getElementById('editGoalDeadline').value;
            const desc = document.getElementById('editGoalDesc').value.trim();

            if (name && deadline && desc && currentEditTaskId !== null) {
                goals = goals.map(goal => {
                    if (goal.id === currentEditTaskId) {
                        return { ...goal, name, deadline, desc };
                    }
                    return goal;
                });
                saveGoals();
                renderGoals();
                editGoalModal.style.display = 'none';
                updateDashboardCharts();
            }
        });

        /* ----------------------- Flashcards Functionality ----------------------- */
        let flashcards = [];
        const flashcardsForm = document.getElementById('flashcardsForm');
        const flashcardsList = document.getElementById('flashcardsList');
        const startFlashcardReviewBtn = document.getElementById('startFlashcardReview');
        const flashcardContainer = document.getElementById('flashcardContainer');
        const currentFlashcard = document.getElementById('currentFlashcard');
        const showAnswerBtn = document.getElementById('showAnswer');
        const nextFlashcardBtn = document.getElementById('nextFlashcard');
        let flashcardIndex = 0;
        let isAnswerShown = false;

        // Load Flashcards from Local Storage
        function loadFlashcards() {
            if (localStorage.getItem('flashcards')) {
                flashcards = JSON.parse(localStorage.getItem('flashcards'));
                renderFlashcards();
            }
        }

        // Add Flashcard
        flashcardsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const question = document.getElementById('flashcardQuestion').value.trim();
            const answer = document.getElementById('flashcardAnswer').value.trim();

            if (question && answer) {
                const flashcard = {
                    id: Date.now(),
                    question,
                    answer
                };
                flashcards.push(flashcard);
                saveFlashcards();
                renderFlashcards();
                updateDashboardCharts();
                flashcardsForm.reset();
            }
        });

        // Save Flashcards to Local Storage
        function saveFlashcards() {
            localStorage.setItem('flashcards', JSON.stringify(flashcards));
        }

        // Render Flashcards
        function renderFlashcards() {
            flashcardsList.innerHTML = '';
            if (flashcards.length === 0) {
                flashcardsList.innerHTML = '<p style="text-align:center; color:#777;">No flashcards added yet.</p>';
                return;
            }

            flashcards.forEach(flashcard => {
                const li = document.createElement('li');
                li.className = 'flashcard-item';

                const q = document.createElement('p');
                q.textContent = `Q: ${flashcard.question}`;

                const a = document.createElement('p');
                a.textContent = `A: ${flashcard.answer}`;

                const actions = document.createElement('div');
                actions.className = 'item-actions';

                const editBtn = document.createElement('button');
                editBtn.innerHTML = '✏️';
                editBtn.title = 'Edit Flashcard';
                editBtn.onclick = () => openEditFlashcardModal(flashcard.id);

                const deleteBtn = document.createElement('button');
                deleteBtn.innerHTML = '🗑️';
                deleteBtn.title = 'Delete Flashcard';
                deleteBtn.onclick = () => deleteFlashcard(flashcard.id);

                actions.appendChild(editBtn);
                actions.appendChild(deleteBtn);

                li.appendChild(q);
                li.appendChild(a);
                li.appendChild(actions);

                flashcardsList.appendChild(li);
            });
        }

        // Delete Flashcard
        function deleteFlashcard(id) {
            if (confirm('Are you sure you want to delete this flashcard?')) {
                flashcards = flashcards.filter(fc => fc.id !== id);
                saveFlashcards();
                renderFlashcards();
                updateDashboardCharts();
            }
        }

        // Flashcard Review Functionality
        startFlashcardReviewBtn.addEventListener('click', () => {
            if (flashcards.length === 0) {
                alert('No flashcards available for review.');
                return;
            }
            flashcardContainer.style.display = 'block';
            flashcardIndex = 0;
            isAnswerShown = false;
            showNextFlashcard();
        });

        showAnswerBtn.addEventListener('click', () => {
            if (flashcards[flashcardIndex]) {
                currentFlashcard.textContent = `A: ${flashcards[flashcardIndex].answer}`;
                isAnswerShown = true;
            }
        });

        nextFlashcardBtn.addEventListener('click', () => {
            flashcardIndex++;
            isAnswerShown = false;
            if (flashcardIndex >= flashcards.length) {
                alert('Flashcard review session completed!');
                flashcardContainer.style.display = 'none';
            } else {
                showNextFlashcard();
            }
        });

        function showNextFlashcard() {
            if (flashcardIndex < flashcards.length) {
                currentFlashcard.textContent = `Q: ${flashcards[flashcardIndex].question}`;
            }
        }

        // Open Edit Flashcard Modal
        function openEditFlashcardModal(id) {
            currentEditTaskId = id;
            const flashcard = flashcards.find(fc => fc.id === id);
            if (flashcard) {
                document.getElementById('editFlashcardQuestion').value = flashcard.question;
                document.getElementById('editFlashcardAnswer').value = flashcard.answer;
                editFlashcardModal.style.display = 'flex';
            }
        }

        // Update Flashcard
        editFlashcardForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const question = document.getElementById('editFlashcardQuestion').value.trim();
            const answer = document.getElementById('editFlashcardAnswer').value.trim();

            if (question && answer && currentEditTaskId !== null) {
                flashcards = flashcards.map(fc => {
                    if (fc.id === currentEditTaskId) {
                        return { ...fc, question, answer };
                    }
                    return fc;
                });
                saveFlashcards();
                renderFlashcards();
                editFlashcardModal.style.display = 'none';
                updateDashboardCharts();
            }
        });

        /* ----------------------- Dashboard Charts Functionality ----------------------- */
        let tasksChart, habitsChart, timeChart;

        // Initialize Charts
        function initializeCharts() {
            const tasksCtx = document.getElementById('tasksChart').getContext('2d');
            tasksChart = new Chart(tasksCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Tasks Completed',
                        data: [],
                        backgroundColor: 'rgba(76, 175, 80, 0.2)',
                        borderColor: 'rgba(76, 175, 80, 1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { display: true }
                    }
                }
            });

            const habitsCtx = document.getElementById('habitsChart').getContext('2d');
            habitsChart = new Chart(habitsCtx, {
                type: 'bar',
                data: {
                    labels: ['Daily', 'Weekly', 'Monthly'],
                    datasets: [{
                        label: 'Habits Completed',
                        data: [0, 0, 0],
                        backgroundColor: [
                            'rgba(76, 175, 80, 0.6)',
                            'rgba(33, 150, 243, 0.6)',
                            'rgba(255, 193, 7, 0.6)'
                        ],
                        borderColor: [
                            'rgba(76, 175, 80, 1)',
                            'rgba(33, 150, 243, 1)',
                            'rgba(255, 193, 7, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            precision:0
                        }
                    }
                }
            });

            const timeCtx = document.getElementById('timeChart').getContext('2d');
            timeChart = new Chart(timeCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Time Studied (m)', 'Remaining Time (m)'],
                    datasets: [{
                        data: [0, 0],
                        backgroundColor: [
                            'rgba(33, 150, 243, 0.6)',
                            'rgba(200, 200, 200, 0.3)'
                        ],
                        borderColor: [
                            'rgba(33, 150, 243,1)',
                            'rgba(200, 200, 200, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { display: true },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `${context.label}: ${context.parsed}m`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // Update Dashboard Charts
        function updateDashboardCharts() {
            updateTasksChart();
            updateHabitsChart();
            updateTimeChart();
        }

        // Tasks Chart - Tasks Completed Over Time
        function updateTasksChart() {
            const completedTasksPerDay = {};

            tasks.forEach(task => {
                if (task.completed) {
                    if (completedTasksPerDay[task.date]) {
                        completedTasksPerDay[task.date]++;
                    } else {
                        completedTasksPerDay[task.date] = 1;
                    }
                }
            });

            const labels = Object.keys(completedTasksPerDay).sort();
            const data = Object.values(completedTasksPerDay);

            tasksChart.data.labels = labels;
            tasksChart.data.datasets[0].data = data;
            tasksChart.update();
        }

        // Habits Chart - Habits Completed
        function updateHabitsChart() {
            let completedDaily = 0, completedWeekly = 0, completedMonthly = 0;

            habits.forEach(habit => {
                habit.completedDates.forEach(date => {
                    const dateObj = new Date(date);
                    const frequency = habit.frequency;
                    if (frequency === 'Daily') {
                        completedDaily++;
                    } else if (frequency === 'Weekly') {
                        // Check if within last 7 days
                        const today = new Date();
                        const sevenDaysAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
                        if (new Date(date) >= sevenDaysAgo) {
                            completedWeekly++;
                        }
                    } else if (frequency === 'Monthly') {
                        // Check if within current month
                        const today = new Date();
                        const currentMonth = today.getMonth();
                        const currentYear = today.getFullYear();
                        if (dateObj.getMonth() === currentMonth && dateObj.getFullYear() === currentYear) {
                            completedMonthly++;
                        }
                    }
                });
            });

            habitsChart.data.datasets[0].data = [completedDaily, completedWeekly, completedMonthly];
            habitsChart.update();
        }

        // Time Tracking Chart - Total Study Time
        function updateTimeChart() {
            const totalSeconds = parseInt(localStorage.getItem('studyTime')) || 0;
            const totalMinutes = Math.floor(totalSeconds / 60);
            const remainingMinutes = Math.max(0, 60 * 24 - totalMinutes); // Assuming a day has 1440 minutes

            timeChart.data.datasets[0].data = [totalMinutes, remainingMinutes];
            timeChart.update();
        }

        /* ----------------------- Flashcards Functionality ----------------------- */
        let flashcardsListData = [];
        const flashcardsContainer = document.getElementById('flashcardContainer');

        function loadFlashcardsData() {
            if (localStorage.getItem('flashcards')) {
                flashcardsListData = JSON.parse(localStorage.getItem('flashcards'));
                renderFlashcards();
            }
        }

        /* ----------------------- Initialize All Modules ----------------------- */
        window.onload = function() {
            loadTasks();
            loadNotes();
            loadHabits();
            loadGoals();
            loadFlashcardsData();
            initializeCharts();
            updateDashboardCharts();
            generateCalendar();
            loadPomodoroSessions();
        }

        /* ----------------------- Complete Study Planner Functionality ----------------------- */
        // Additional functionalities like Time Tracking are already integrated above.

    </script>
</body>
</html>