<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Learning - Premium</title>
    <link rel="icon" type="image/x-icon"
        href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXH01KD_9TMda5AESIluex5Jg2BDv71A07hA&s">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --accent-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            --light-bg: #f8fafc;
            --card-bg: #ffffff;
            --text-primary: #2d3748;
            --text-secondary: #718096;
            --border-color: #e2e8f0;
            --shadow-sm: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--light-bg);
            color: var(--text-primary);
            line-height: 1.6;
            overflow-x: hidden;
        }

        .premium-header {
            background: var(--primary-gradient);
            backdrop-filter: blur(20px);
            border: none;
            box-shadow: var(--shadow-lg);
            z-index: 1050;
            padding: 0.8rem 0;
        }

        .sub-header-nav {
            position: fixed;
            top: 76px;
            /* Adjust based on header height */
            left: 0;
            width: 100%;
            background: white;
            z-index: 1040;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            padding: 10px 0;
            display: flex;
            justify-content: center;
            gap: 15px;
            overflow-x: auto;
        }

        .nav-pill-btn {
            background: #f1f5f9;
            color: var(--text-primary);
            border: none;
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            white-space: nowrap;
            text-decoration: none;
        }

        .nav-pill-btn:hover {
            background: #e2e8f0;
            transform: translateY(-2px);
            color: var(--text-primary);
        }

        .nav-pill-btn.active-feature {
            background: var(--accent-gradient);
            color: white;
            box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
        }

        .main-container {
            margin-top: 150px;
            /* Increased top margin for double header */
            padding: 0 1rem;
            max-width: 1200px;
            margin-left: auto;
            margin-right: auto;
        }

        .output-part {
            margin-bottom: 2rem;
        }

        .output-part .card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            box-shadow: var(--shadow-md);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .output-part .card:hover {
            box-shadow: var(--shadow-lg);
            transform: translateY(-2px);
        }

        .card-body {
            padding: 2rem;
            background: linear-gradient(135deg, #fffef7 0%, #fff9e6 100%);
        }

        /* #chat-container {
            height: clamp(200px, 70vh, 500px);
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: #cbd5e0 transparent;
            display : none;
        } */

        #chat-container::-webkit-scrollbar {
            width: 6px;
        }

        #chat-container::-webkit-scrollbar-track {
            background: transparent;
        }

        #chat-container::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 3px;
        }

        #chat-container::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }

        .input-part {
            background: var(--card-bg);
            border-radius: 24px;
            padding: 1.5rem;
            box-shadow: var(--shadow-xl);
            border: 1px solid var(--border-color);
            position: bottom;
            bottom: 1rem;
            z-index: 100;
        }

        .language-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .language-section {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        .form-label {
            font-weight: 600;
            color: var(--text-primary);
            margin: 0;
            font-size: 0.9rem;
        }

        .form-select {
            border: 2px solid var(--border-color);
            border-radius: 12px;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            min-width: 140px;
        }

        .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            align-items: center;
            flex-wrap: wrap;
        }

        .btn-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid var(--border-color);
            background: var(--card-bg);
            color: var(--text-secondary);
            transition: all 0.3s ease;
            text-decoration: none;
        }

        .btn-icon:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .btn-icon.btn-light:hover {
            background: var(--accent-gradient);
            color: white;
            border-color: transparent;
        }

        .btn-icon.btn-danger:hover {
            background: var(--secondary-gradient);
            color: white;
            border-color: transparent;
        }

        .message-input-container {
            position: relative;
            margin-bottom: 1rem;
        }

        #message-input {
            border: 2px solid var(--border-color);
            border-radius: 16px;
            padding: 1rem 3.5rem 1rem 1rem;
            font-size: 1rem;
            transition: all 0.3s ease;
            resize: vertical;
            min-height: 60px;
        }

        #message-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .file-upload-icon {
            position: absolute;
            right: 12px;
            bottom: 12px;
            cursor: pointer;
            color: var(--text-secondary);
            transition: all 0.3s ease;
            padding: 8px;
            border-radius: 8px;
        }

        .file-upload-icon:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.1);
        }

        .controls-container {
            display: flex;
            gap: 0.75rem;
            align-items: center;
            flex-wrap: wrap;
            justify-content: space-between;
        }

        .control-buttons {
            display: flex;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        .btn {
            border-radius: 12px;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            transition: all 0.3s ease;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .btn-primary {
            background: var(--primary-gradient);
            color: white;
        }

        .btn-secondary {
            background: var(--dark-gradient);
            color: white;
        }

        .btn-danger {
            background: var(--secondary-gradient);
            color: white;
        }

        .btn-info {
            background: var(--accent-gradient);
            color: white;
        }

        .loading-animation {
            width: 24px;
            height: 24px;
            border: 3px solid var(--border-color);
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .image-popup {
            position: absolute;
            top: -120px;
            left: 50%;
            transform: translateX(-50%);
            background: var(--card-bg);
            border: 2px solid var(--border-color);
            border-radius: 16px;
            padding: 1rem;
            z-index: 1000;
            max-width: 300px;
        }

        .image-popup img {
            width: 100%;
            height: auto;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }

        .popup-buttons {
            display: flex;
            gap: 0.5rem;
            justify-content: center;
        }

        .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: var(--shadow-xl);
        }

        .modal-header {
            background: var(--primary-gradient);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 1.5rem;
        }

        .modal-title {
            font-weight: 700;
        }

        .btn-close {
            filter: invert(1);
        }

        .modal-body {
            padding: 2rem;
        }

        .form-check-input:checked {
            background-color: #667eea;
            border-color: #667eea;
        }

        .form-check-label {
            font-weight: 500;
            color: var(--text-primary);
        }

        #image-preview {
            margin-bottom: 1rem;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .main-container {
                margin-top: 140px;
                padding: 0 0.5rem;
            }

            .head-part {
                flex-direction: column;
                text-align: center;
                gap: 0.5rem;
            }

            .language-controls {
                flex-direction: column;
                align-items: stretch;
                gap: 1rem;
            }

            .language-section {
                justify-content: center;
            }

            .action-buttons {
                justify-content: center;
            }

            .controls-container {
                flex-direction: column;
                gap: 1rem;
            }

            .control-buttons {
                justify-content: center;
                width: 100%;
            }

            .btn {
                flex: 1;
                min-width: 120px;
                justify-content: center;
            }

            .input-part {
                padding: 1rem;
                border-radius: 20px;
            }

            #message-input {
                padding: 0.75rem 3rem 0.75rem 0.75rem;
            }

            .card-body {
                padding: 1rem;
            }
        }

        @media (max-width: 480px) {
            .premium-header h1 {
                font-size: 1.5rem;
            }

            .premium-header h5 {
                font-size: 0.9rem;
            }

            .btn {
                padding: 0.6rem 1rem;
                font-size: 0.9rem;
            }

            .btn-icon {
                width: 40px;
                height: 40px;
            }

            .control-buttons {
                flex-direction: column;
                width: 100%;
            }

            .btn {
                width: 100%;
            }
        }

        /* Animation for smooth transitions */
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Enhanced focus states for accessibility */
        .btn:focus,
        .form-select:focus,
        .form-control:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }

        /* Improved scrollbar for webkit browsers */
        * {
            scrollbar-width: thin;
            scrollbar-color: #cbd5e0 transparent;
        }

        *::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        *::-webkit-scrollbar-track {
            background: transparent;
        }

        *::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 4px;
        }

        *::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }


        #char-count-display {
            text-align: right;
            /* Aligns the text to the right */
            font-size: 0.8em;
            /* Makes the font slightly smaller than parent text */
            color: #666;
            /* A subtle grey color */
            margin-top: 5px;
            /* Adds a small space above the counter */
            /* Optional: For when the limit is exceeded */
            transition: color 0.3s ease;
            /* Smooth transition for color change */
        }

        /* Style for when the character limit is exceeded */
        #char-count-display.limit-exceeded {
            color: red;
            /* Changes color to red */
            font-weight: bold;
            /* Makes text bold for emphasis */
        }

        .file-upload-icon:hover {
            background-color: #e9ecef;
        }

        /* Crop Modal Styles */
        .crop-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            overflow-y: auto;
        }

        .crop-modal-content {
            background: white;
            margin: 2% auto;
            padding: 20px;
            border-radius: 8px;
            max-width: 90%;
            width: 800px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .crop-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .crop-modal-header h3 {
            margin: 0;
            color: #333;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .close-btn:hover {
            color: #333;
        }

        .crop-image {
            max-width: 100%;
            max-height: 400px;
            display: block;
            margin: 0 auto;
        }

        .crop-options {
            margin: 15px 0;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
        }

        .crop-options label {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
        }

        .crop-options select,
        .crop-options input[type="number"] {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .crop-options input[type="number"] {
            width: 80px;
        }

        .controls {
            margin: 20px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .btn-primary {
            background-color: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background-color: #0056b3;
        }

        .btn-success {
            background-color: #28a745;
            color: white;
        }

        .btn-success:hover {
            background-color: #1e7e34;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #545b62;
        }

        .btn-danger {
            background-color: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background-color: #c82333;
        }

        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            display: none;
            text-align: center;
        }

        .status.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .status.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .status.info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }

        /* Responsive Design */
        @media (max-width: 600px) {
            .crop-modal-content {
                width: 95%;
                margin: 5% auto;
                padding: 15px;
            }

            .controls {
                flex-direction: column;
                align-items: center;
            }

            .btn {
                width: 100%;
                max-width: 200px;
                justify-content: center;
            }

            .crop-options {
                flex-direction: column;
                gap: 10px;
            }
        }

        /* --------------- */

        /* #chat-container {
  display: block;
  width: 40%;
  flex-direction: column;
  gap: 10px; */

        .chat-wrapper {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .chat-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
            position: relative;
        }

        .chat-bubble.user {
            background-color: #dcf8c6;
            align-self: flex-end;
            /* push bubble to right side */
            border-bottom-right-radius: 0;
            text-align: left;
        }

        .chat-bubble.gemini {
            background-color: #f1f0f0;
            align-self: flex-start;
            /* push bubble to left side */
            border-bottom-left-radius: 0;
            text-align: left;
        }

        .feedback-popup {
            display: none;
            position: fixed;
            bottom: 50px;
            left: 50%;
            transform: translateX(-50%);
            background: #ffffff;
            padding: 20px 24px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            z-index: 9999;
            width: 320px;
            max-width: 90%;
        }

        .feedback-popup textarea {
            width: 100%;
            height: 90px;
            resize: vertical;
            padding: 10px 12px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 14px;
            line-height: 1.4;
            outline: none;
            transition: border 0.2s ease;
        }

        .feedback-popup textarea:focus {
            border-color: #007bff;
        }

        .popup-buttons {
            text-align: right;
            margin-top: 10px;
        }

        .popup-buttons button {
            background: #007bff;
            color: #fff;
            border: none;
            padding: 8px 14px;
            font-size: 14px;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.2s ease, transform 0.1s ease;
        }

        .popup-buttons button:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }

        .popup-buttons button.cancel-btn {
            background: #6c757d;
        }

        .popup-buttons button.cancel-btn:hover {
            background: #5a6268;
        }

        .feedback-buttons {
            margin-top: 8px;
        }

        .feedback-buttons button {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 20px;
            margin-right: 8px;
            transition: transform 0.1s ease-in-out;
        }

        .side-drawer {
            position: fixed;
            top: 0;
            left: -320px;
            /* Start hidden off screen */
            width: 300px;
            height: 100%;
            background: #fff;
            box-shadow: 2px 0 12px rgba(0, 0, 0, 0.15);
            padding: 20px;
            transition: left 0.3s ease;
            z-index: 2000;
            overflow-y: auto;
        }

        .side-drawer.open {
            left: 0;
            /* Slide in from left edge */
        }

        .menu-btn {
            background: none;
            border: none;
            font-size: 26px;
            cursor: pointer;
            color: white;
        }


        .side-drawer ul {
            list-style: none;
            padding: 0;
        }

        .side-drawer li {
            margin: 10px 0;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 6px;
            transition: background 0.2s ease;
        }

        .side-drawer li:hover {
            background: #f0f0f0;
        }

        .side-drawer .close-btn {
            margin-top: 20px;
            background: #dc3545;
            color: #fff;
            border: none;
            padding: 8px 14px;
            border-radius: 6px;
            cursor: pointer;
        }

        .side-drawer .close-btn:hover {
            background: #c82333;
        }

        .side-drawer {
            overflow-y: auto;
        }

        .drawer-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .drawer-header h6 {
            margin: 0;
            flex: 1;
            /* take available space */
            white-space: nowrap;
            /* prevent wrapping */
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 22px;
            cursor: pointer;
            color: #333;
            flex-shrink: 0;
            /* don’t shrink */
        }

        #limitModal {
            display: none;
            position: fixed;
            z-index: 9999;
            /* On top of everything */
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(2px);
            align-items: center;
            justify-content: center;
        }

        /* Modal box */
        #limitModal .modal-content {
            background: #fff;
            padding: 20px 25px;
            width: 320px;
            max-width: 90%;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            animation: scaleUp 0.2s ease-out;
        }

        /* Modal text */
        #limitModal p {
            font-size: 16px;
            margin-bottom: 20px;
            color: #333;
        }

        /* Buttons */
        #limitModal button {
            padding: 10px 18px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            margin: 0 8px;
            transition: background 0.2s ease;
        }

        #limitModal button:first-child {
            background: #28a745;
            color: white;
        }

        #limitModal button:first-child:hover {
            background: #218838;
        }

        #limitModal button:last-child {
            background: #dc3545;
            color: white;
        }

        #limitModal button:last-child:hover {
            background: #c82333;
        }

        /* Animation */
        @keyframes scaleUp {
            from {
                transform: scale(0.9);
                opacity: 0;
            }

            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        .progress-btn i {
            color: #007bff;
            transition: transform 0.2s ease, color 0.2s ease;
        }

        .progress-btn:hover i {
            transform: scale(1.2);
            color: #00b894;
            /* soft green on hover */
        }

        #user-score {
            transition: opacity 0.3s ease, transform 0.3s ease;
            display: inline-block;
        }

        #user-score.animate {
            transform: scale(1.2);
            color: #28a745;
            /* green flash on score change */
        }

        .progress-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background: #fff;
            padding: 20px;
            border-radius: 12px;
            width: 90%;
            max-width: 400px;
            margin: 10% auto;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }

        .modal-content h5 {
            margin-bottom: 10px;
        }

        .modal-content .close {
            position: absolute;
            right: 20px;
            top: 15px;
            font-size: 22px;
            cursor: pointer;
        }

        .progress-btn i {
            color: #007bff;
            transition: transform 0.2s ease, color 0.2s ease;
        }

        .progress-btn:hover i {
            transform: scale(1.2);
            color: #00b894;
            /* soft green on hover */
        }


        .dashboard-btn {
            display: inline-block;
            padding: 15px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            text-decoration: none;
            border-radius: 30px;
            font-weight: 600;
            font-size: 1.1em;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .dashboard-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
        }
    </style>
</head>

<body class="container-fluid py-4">

    <header class="fixed-top premium-header">
        <div class="container head-part d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center gap-3">
                <button class="menu-btn" onclick="toggleDrawer()">
                    <i class="fas fa-comment-dots"></i>
                </button>
                <h1 class="mb-0 fs-3">Interactive Learning</h1>
            </div>
            {% if user %}
            <h5 class="mb-0 d-none d-md-block">Welcome: {{user.name}} <span id="user-score"
                    style="margin-left: 8px; font-weight: bold; color: white;">(Score: 0)</span></h5>
            {% endif %}
        </div>
    </header>

    <div class="sub-header-nav">
        <button onclick="goToDashboard()" class="nav-pill-btn">
            <i class="fas fa-chart-bar"></i> Dashboard
        </button>
        <a href="/dictation-practice" class="nav-pill-btn">
            <i class="fas fa-pen-fancy"></i> Dictation
        </a>
        <a href="/quiz-practice" class="nav-pill-btn">
            <i class="fas fa-brain"></i> Quiz AI
        </a>
    </div>


    <!-- Progress Modal -->
    <div id="progress-modal" class="progress-modal" style="display:none;">
        <div class="modal-content">
            <span class="close" onclick="closeProgressModal()">&times;</span>
            <h5>Progress Summary</h5>
            <div id="progress-details"></div>
            <canvas id="progressChart" width="200" height="200"></canvas>
        </div>
    </div>

    <div id="side-drawer" class="side-drawer">
        <div class="drawer-header">
            <h6>My Conversations</h6>
            <button class="close-btn" onclick="toggleDrawer()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <ul id="conversation-list"></ul>
    </div>

    <div class="main-container">
        <div class="output-part">
            <!-- <div class="card">
                <div class="card-body" id="chat-container"></div>
            </div> -->

            <div class="chat-wrapper">
                <div class="chat-container" id="chat-container"></div>
            </div>

            <!-- Feedback Popup -->
            <div id="feedback-popup" class="feedback-popup">
                <textarea id="feedback-text" placeholder="Tell us more..."></textarea>
                <div class="popup-buttons">
                    <button onclick="submitFeedback()">Submit</button>
                    <button class="cancel-btn" onclick="closeFeedbackPopup()">Cancel</button>
                </div>
            </div>
        </div>

        <div id="limitModal">
            <div
                style="background:#fff; padding:20px; margin:100px auto; width:300px; border-radius:10px; text-align:center;">
                <p>Do you want to continue with the same content?</p>
                <button onclick="sendLimitResponse('#Yes')">Yes</button>
                <button onclick="sendLimitResponse('#No')">No</button>
            </div>
        </div>

        <div id="image-preview" class="mt-2"></div>

        <div class="input-part fade-in" id="draggable-input">
            <div class="language-controls">
                <div class="language-section">
                    <label for="language-select" class="form-label">Select Language:</label>
                    <select id="language-select" class="form-select">
                        <option value="english" selected>English</option>
                        <option value="hindi">Hindi</option>
                        <option value="telugu">Telugu</option>
                        <option value="bengali">Bengali</option>
                        <option value="tamil">Tamil</option>
                        <option value="marathi">Marathi</option>
                        <option value="gujarati">Gujarati</option>
                        <option value="kannada">Kannada</option>
                        <option value="malayalam">Malayalam</option>
                        <option value="odia">Odia</option>
                        <option value="punjabi">Punjabi</option>
                        <option value="assamese">Assamese</option>
                        <option value="urdu">Urdu</option>
                        <option value="sanskrit">Sanskrit</option>
                    </select>
                </div>

                <div class="action-buttons">
                    <button id="reset-button" class="btn-icon btn-light" title="Reset">
                        <i class="fas fa-redo"></i>
                    </button>
                    <button id="settings-button" class="btn-icon btn-light" title="Settings" data-bs-toggle="modal"
                        data-bs-target="#settingsModal">
                        <i class="fas fa-cog"></i>
                    </button>
                    <a class="btn-icon btn-danger logout-btn" onclick="logOut()" title="Logout">
                        <i class="fas fa-sign-out-alt"></i>
                    </a>
                </div>
            </div>

            <div class="message-input-container">
                <textarea id="message-input" rows="2" class="form-control" placeholder="Type your message..."
                    onkeydown="handleKeyDown(event)" oninput="updateCharCount()"></textarea>
                <label for="file-upload" class="file-upload-icon"
                    title="Supported Files(pdf, png, jpg and jpeg), Maximum File Size: 10MB">
                    <i class="fas fa-paperclip" style="font-size: 20px;"></i>
                </label>
                <input type="file" id="file-upload" style="display: none;" accept=".pdf,image/*">
            </div>
            <div id="char-count-display" style="text-align: right; font-size: 0.8em; color: #666; margin-top: 5px;">
                0 / 4000 characters
            </div>


            <!-- Crop Modal -->


            <div id="cropModal" class="crop-modal">
                <div class="crop-modal-content">
                    <div class="crop-modal-header">
                        <h3>Crop Your Image</h3>
                        <button class="close-btn" onclick="closeCropModal()">&times;</button>
                    </div>

                    <div class="status" id="cropStatus"></div>

                    <!-- Crop Options -->
                    <div class="crop-options" style="display: none;">
                        <label>
                            <i class="fas fa-crop"></i>
                            Aspect Ratio:
                            <select id="aspectRatio">
                                <option value="free">Free</option>
                                <option value="1">1:1 Square</option>
                                <option value="1.3333">4:3</option>
                                <option value="1.7778">16:9</option>
                                <option value="0.6667">2:3</option>
                            </select>
                        </label>

                        <label>
                            <i class="fas fa-arrows-alt-h"></i>
                            Width:
                            <input type="number" id="cropWidth" placeholder="Auto" min="50" max="2000">
                        </label>

                        <label>
                            <i class="fas fa-arrows-alt-v"></i>
                            Height:
                            <input type="number" id="cropHeight" placeholder="Auto" min="50" max="2000">
                        </label>

                        <label>
                            <i class="fas fa-star"></i>
                            Quality:
                            <select id="quality">
                                <option value="0.9">High (90%)</option>
                                <option value="0.8" selected>Medium (80%)</option>
                                <option value="0.6">Low (60%)</option>
                            </select>
                        </label>
                    </div>

                    <div style="text-align: center; margin: 20px 0;">
                        <img id="cropImage" class="crop-image" src="" alt="Crop Image">
                    </div>

                    <!-- Controls -->
                    <div class="controls">
                        <button class="btn btn-secondary" onclick="resetCrop()">
                            <i class="fas fa-refresh"></i> Reset
                        </button>
                        <button class="btn btn-success" onclick="applyCropAndSend()">
                            <i class="fas fa-check"></i> Apply & Send
                        </button>
                        <button class="btn btn-danger" onclick="closeCropModal()">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                    </div>
                </div>
            </div>


            <div class="controls-container">
                <div class="control-buttons">
                    <button class="btn btn-secondary" id="pause-resume-button" onclick="toggleSpeech()"
                        style="display: none;">
                        <i class="fas fa-pause"></i> Pause
                    </button>
                    <button class="btn btn-danger" id="stop-button" onclick="stopSpeech()" style="display: none;">
                        <i class="fas fa-stop"></i> Stop
                    </button>
                    <button class="btn btn-info" id="start-speech-button" onclick="handleSpeechButtonClick()">
                        <i class="fas fa-microphone"></i> Start Speech
                    </button>
                    <button class="btn btn-primary" onclick="sendMessage()">
                        <i class="fas fa-paper-plane"></i> Send
                    </button>
                </div>

                <div id="loading-indicator" style="display: none;">
                    <div class="loading-animation"></div>
                </div>
            </div>

            <div id="pasted-image-popup" style="display: none;" class="image-popup shadow-sm">
                <img id="preview-img" src="" alt="Pasted Preview" />
                <div class="popup-buttons mt-2">
                    <button class="btn btn-sm btn-primary me-2" onclick="sendPastedImage()">Send</button>
                    <button class="btn btn-sm btn-outline-secondary" onclick="removePastedImage()">Remove</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" aria-labelledby="settingsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="settingsModalLabel">
                        <i class="fas fa-cog me-2"></i>Settings
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-4">
                        <label class="form-label">
                            <i class="fas fa-layer-group me-2"></i>Explanation Level:
                        </label>
                        <div class="mt-2">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="classMode" id="classModeBrief"
                                    value="brief">
                                <label class="form-check-label" for="classModeBrief">Brief</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="classMode" id="classModeStandard"
                                    value="standard" checked>
                                <label class="form-check-label" for="classModeStandard">Standard</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="classMode" id="classModeDetailed"
                                    value="detailed">
                                <label class="form-check-label" for="classModeDetailed">Detailed</label>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">
                            <i class="fas fa-volume-up me-2"></i>Voice Configuration:
                        </label>
                        <div class="mt-2">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="voiceConfig" id="voiceConfigMale"
                                    value="male" checked>
                                <label class="form-check-label" for="voiceConfigMale">Male Voice</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="voiceConfig" id="voiceConfigFemale"
                                    value="female">
                                <label class="form-check-label" for="voiceConfigFemale">Female Voice</label>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label" for="aiModelSelect">
                            <i class="fas fa-robot me-2"></i>AI Model:
                        </label>
                        <select class="form-select mt-2" id="aiModelSelect">
                            <option value="gemini" selected>Gemini</option>
                            <option value="deepseek">DeepSeek</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Close
                    </button>
                    <button type="button" class="btn btn-primary" onclick="saveSettings()">
                        <i class="fas fa-save me-2"></i>Save changes
                    </button>
                </div>
            </div>
        </div>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>

        const accessToken = "{{ access_token }}";
        const chatContainer = document.getElementById('chat-container');
        const audioPlayer = new Audio();
        const loadingIndicator = document.getElementById('loading-indicator');
        const pauseResumeButton = document.getElementById('pause-resume-button');
        const stopButton = document.getElementById('stop-button');
        const startSpeechButton = document.getElementById('start-speech-button');
        let progressChartInstance = null;

        document.getElementById('reset-button').addEventListener('click', function () {
            location.reload();
        });

        function saveSettings() {
            const classMode = document.querySelector('input[name="classMode"]:checked').value;
            const voiceConfig = document.querySelector('input[name="voiceConfig"]:checked').value;
            const aiModel = document.getElementById('aiModelSelect').value;

            // Store settings (e.g., in localStorage)
            localStorage.setItem('classMode', classMode);
            localStorage.setItem('voiceConfig', voiceConfig);
            localStorage.setItem('aiModel', aiModel);

            // You can also update a global JS object if needed
            // appSettings.classMode = classMode;
            // appSettings.voiceConfig = voiceConfig;
            // appSettings.aiModel = aiModel;

            console.log("Settings saved:", { classMode, voiceConfig, aiModel });

            // Close the modal
            const settingsModal = bootstrap.Modal.getInstance(document.getElementById('settingsModal'));
            settingsModal.hide();

            // Here you would typically re-initialize or adjust your application's behavior
            // based on the new settings.
        }

        // Function to load settings when the page loads (optional, but good for persistence)
        document.addEventListener('DOMContentLoaded', (event) => {
            // --- Set default values if not found in localStorage ---
            const defaultClassMode = 'standard'; // Matches your HTML default 'standard'
            const defaultVoiceConfig = 'male';   // Matches your HTML default 'male'
            const defaultAiModel = 'gemini';     // Matches your HTML default 'gemini'

            let savedClassMode = localStorage.getItem('classMode');
            if (savedClassMode) {
                document.querySelector(`input[name="classMode"][value="${savedClassMode}"]`).checked = true;
            } else {
                // Set default in localStorage and check the corresponding radio button
                localStorage.setItem('classMode', defaultClassMode);
                document.querySelector(`input[name="classMode"][value="${defaultClassMode}"]`).checked = true;
            }

            let savedVoiceConfig = localStorage.getItem('voiceConfig');
            if (savedVoiceConfig) {
                document.querySelector(`input[name="voiceConfig"][value="${savedVoiceConfig}"]`).checked = true;
            } else {
                // Set default in localStorage and check the corresponding radio button
                localStorage.setItem('voiceConfig', defaultVoiceConfig);
                document.querySelector(`input[name="voiceConfig"][value="${defaultVoiceConfig}"]`).checked = true;
            }

            let savedAiModel = localStorage.getItem('aiModel');
            if (savedAiModel) {
                document.getElementById('aiModelSelect').value = savedAiModel;
            } else {
                // Set default in localStorage and set the corresponding select option
                localStorage.setItem('aiModel', defaultAiModel);
                document.getElementById('aiModelSelect').value = defaultAiModel;
            }

            // You could also initialize a global settings object here if you prefer
            // window.appSettings = {
            //     classMode: localStorage.getItem('classMode'),
            //     voiceConfig: localStorage.getItem('voiceConfig'),
            //     aiModel: localStorage.getItem('aiModel')
            // };
        });



        let isSpeaking = false;
        let shouldResume = false;
        let isRecording = false;
        let mediaRecorder;
        let recordedChunks;
        let speechRecognitionActive = false;
        let speechStartTimeout;
        let clientId = generateClientId(); // Generate unique client ID
        let pendingPastedImage;

        // Generate a unique client ID
        function generateClientId() {
            return 'client_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
        }

        // Helper function to convert base64 to Blob
        function base64toBlob(base64Data, contentType = '') {
            const byteCharacters = atob(base64Data);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            return new Blob([byteArray], { type: contentType });
        }

        // Send data to FastAPI backend
        async function sendToBackend(messageType, content) {
            const selectedLanguage = document.getElementById("language-select").value;
            const savedClassMode = localStorage.getItem('classMode');
            const savedVoiceConfig = localStorage.getItem('voiceConfig');
            const savedAiModel = localStorage.getItem('aiModel');
            if (messageType === 'text') {
                const blob = new Blob([content], { type: 'text/plain' });
                content = blob;

            }
            const formData = new FormData();
            formData.append('client_id', clientId);
            formData.append('language', selectedLanguage);
            formData.append('message_type', messageType);
            formData.append('content', content);
            formData.append('mode', savedClassMode);
            formData.append('voice', savedVoiceConfig);
            formData.append('model', savedAiModel);



            if (accessToken) {
                formData.append('access_token', accessToken);
            }

            try {
                showLoadingAnimation();
                const response = await fetch('https://lm.warals.codetorise.com/chat/', {
                    method: 'POST',
                    body: formData
                });
                console.log('Response status:', response.status);
                console.log('Response headers:', response.redirected == true ? 'Redirected to ' + response.url : 'No redirection');
                if (response.redirected) {
                    console.warn('Backend request resulted in a redirect. Assuming session expired.');



                    // Use setTimeout to ensure the message is briefly visible before redirecting
                    setTimeout(logOut, 100);

                    return; // EXIT the function to stop processing the (now login page) response
                }
                // --- ADDED CODE START: Session Expiration Check ---
                if (response.status === 401 || response.status === 403) {
                    console.warn('Session expired or unauthorized. Forcing logout.');
                    // 1. Display a message to the user
                    addMessage('Your session has expired. Please log in again.', 'gemini');
                    hideLoadingAnimation();

                    // 2. Clear token/session data (if necessary, though logOut should handle it)
                    localStorage.removeItem('accessToken'); // Assuming token is stored here

                    // 3. Force redirect/logout after a short delay for the user to see the message
                    setTimeout(logOut, 2000); // logOut() redirects to /logout
                    return; // Exit the function to prevent further processing
                }
                // --- ADDED CODE END ---

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();


                // Handle the response
                if (data.gemini_response) {
                    // Handle normal Gemini response


                    if (data.score !== undefined) {
                        const scoreElement = document.getElementById("user-score");
                        if (scoreElement) {
                            const oldScoreText = scoreElement.textContent.match(/\d+/);
                            const oldScore = oldScoreText ? parseInt(oldScoreText[0]) : 0;
                            const newScore = parseInt(data.score);

                            if (newScore !== oldScore) {
                                // Fade out
                                scoreElement.style.transition = "opacity 0.3s ease";
                                scoreElement.style.opacity = "0";

                                setTimeout(() => {
                                    // Count-up animation
                                    let current = oldScore;
                                    const step = newScore > oldScore ? 1 : -1;
                                    const interval = setInterval(() => {
                                        current += step;
                                        scoreElement.textContent = `(Score: ${current})`;
                                        if (current === newScore) {
                                            clearInterval(interval);
                                        }
                                    }, 50); // speed of count animation

                                    // Fade in
                                    scoreElement.style.opacity = "1";

                                    // 🌟 Add scale animation effect
                                    scoreElement.classList.add("animate");
                                    setTimeout(() => scoreElement.classList.remove("animate"), 500);
                                }, 300);
                            }
                        }
                    }

                    addMessage(`Gemini: ${data.gemini_response}`, 'gemini', data.message_id);
                    if (data.add_condetion) {
                        console.log('limit has reached');
                        showLimitModal();
                    }

                    // Handle audio if present
                    if (data.audio_base64 && !speechRecognitionActive) {
                        const audioBlob = base64toBlob(data.audio_base64, 'audio/mpeg');
                        const audioURL = URL.createObjectURL(audioBlob);
                        audioPlayer.src = audioURL;
                        audioPlayer.play();
                        isSpeaking = true;
                        document.getElementById('pause-resume-button').style.display = 'inline-block';
                        document.getElementById('stop-button').style.display = 'inline-block';
                        pauseResumeButton.innerHTML = '<i class="fas fa-pause"></i> Pause';

                        audioPlayer.onended = () => {
                            isSpeaking = false;
                            pauseResumeButton.innerHTML = '<i class="fas fa-play"></i> Play';
                            URL.revokeObjectURL(audioURL);
                        };
                    }


                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('Error: Failed to connect to server', 'gemini');
            } finally {
                hideLoadingAnimation();
            }
        }

        function toggleSpeech() {
            if (isSpeaking) {
                audioPlayer.pause();
                isSpeaking = false;
                pauseResumeButton.innerHTML = '<i class="fas fa-play"></i> Play';
            } else if (audioPlayer.src) {
                audioPlayer.play();
                isSpeaking = true;
                pauseResumeButton.innerHTML = '<i class="fas fa-pause"></i> Pause';
            }
        }

        function stopSpeech() {
            if (isSpeaking) {
                audioPlayer.pause();
                audioPlayer.currentTime = 0;
                isSpeaking = false;
                pauseResumeButton.innerHTML = '<i class="fas fa-play"></i> Play';
            }
        }

        function handleSpeechButtonClick() {
            if (!speechRecognitionActive) {
                speechRecognitionActive = true;
                startSpeechListening();
                startSpeechButton.innerHTML = '<i class="fas fa-microphone-slash"></i> Listening...';
            } else {
                stopSpeechListening();
                speechRecognitionActive = false;
                startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
            }
        }

        async function startSpeechListening() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const source = audioContext.createMediaStreamSource(stream);
                const analyser = audioContext.createAnalyser();
                const processor = audioContext.createScriptProcessor(2048, 1, 1);
                source.connect(analyser);
                analyser.connect(processor);
                processor.connect(audioContext.destination);

                recordedChunks = [];
                mediaRecorder = new MediaRecorder(stream);
                let silenceStart = null;
                const SILENCE_DELAY = 3000; // 3 seconds

                mediaRecorder.ondataavailable = event => {
                    if (event.data.size > 0) {
                        recordedChunks.push(event.data);
                    }
                };

                mediaRecorder.onstop = () => {
                    processor.disconnect();
                    analyser.disconnect();
                    source.disconnect();
                    if (recordedChunks.length > 0) {
                        const audioBlob = new Blob(recordedChunks, { type: 'audio/webm' });
                        sendToBackend('audio', audioBlob);
                        addMessage('You sent a voice message', 'user');
                    }
                    isRecording = false;
                    speechRecognitionActive = false;
                    startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
                };

                processor.onaudioprocess = function () {
                    const data = new Uint8Array(analyser.frequencyBinCount);
                    analyser.getByteFrequencyData(data);
                    const volume = data.reduce((a, b) => a + b) / data.length;

                    const THRESHOLD = 10; // adjust this for sensitivity
                    if (volume > THRESHOLD) {
                        if (!isRecording) {
                            mediaRecorder.start();
                            isRecording = true;
                            console.log("Speech detected, recording started");
                        }
                        silenceStart = null; // reset silence timer
                        if (isSpeaking) {
                            audioPlayer.pause();
                            shouldResume = true;
                        }
                    } else {
                        if (isRecording) {
                            if (!silenceStart) {
                                silenceStart = Date.now();
                            } else if (Date.now() - silenceStart > SILENCE_DELAY) {
                                mediaRecorder.stop();
                                stream.getTracks().forEach(track => track.stop());
                                console.log("Silence detected, recording stopped");
                            }
                        }
                    }
                };
            } catch (err) {
                console.error("Microphone error:", err);
                speechRecognitionActive = false;
                startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
            }
        }

        function stopSpeechListening() {
            if (isRecording && mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.stop();
                isRecording = false;
            }
            speechRecognitionActive = false;
            startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
        }

        // Handle Enter key press
        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault(); // Prevent newline
                sendMessage();

            }
        }

        // Send text message function
        function sendMessage() {
            const input = document.getElementById('message-input');
            const text = input.value.trim();

            const savedClassMode = localStorage.getItem('classMode');
            const savedVoiceConfig = localStorage.getItem('voiceConfig');
            const savedAiModel = localStorage.getItem('aiModel');
            console.log('Class Mode', savedClassMode);
            console.log('Voice Selected', savedVoiceConfig);
            console.log('Selected AI Model', savedAiModel);

            if (text !== "") {
                // Add user message to the chat
                addMessage(`You: ${text}`, 'user');


                // Send to backend
                sendToBackend('text', text);

                // Clear the input field
                input.value = '';
            }
            if (pendingPastedImage) {
                sendToBackend('file', pendingPastedImage);
                pendingPastedImage = null;
                document.getElementById('image-preview').innerHTML = ""; // Clear preview
            }

        }
        // ___________________________________________________________________
        // // Add message to chat container
        // function addMessage(message, sender) {
        //     const messageCard = document.createElement('div');
        //     messageCard.classList.add('card', 'chat-message');
        //     messageCard.classList.add(sender === 'user' ? 'user-card' : 'gemini-card');
        //     document.getElementById('chat-container').style.display = 'block';
        //     const cardBody = document.createElement('div');
        //     cardBody.classList.add('card-body');
        //     cardBody.innerHTML = message;

        //     messageCard.appendChild(cardBody);
        //     chatContainer.appendChild(messageCard);
        //     chatContainer.scrollTop = chatContainer.scrollHeight; // Scroll to bottom
        // }
        // ___________________________________________

        // update the addMessage function to handle different message types
        // function addMessage(text, sender, messageId = null) {
        //   const chatContainer = document.getElementById('chat-container');

        //   const messageCard = document.createElement('div');
        //   messageCard.className = `chat-bubble ${sender}`;
        //   document.getElementById('chat-container').style.display = 'block';

        //   if (messageId) {
        //     messageCard.dataset.messageId = messageId;
        //   }

        //   let buttonsHtml = '';
        //   if (sender === 'gemini' && messageId) {
        //     buttonsHtml = `
        //       <div class="feedback-buttons">
        //         <button onclick="openFeedbackPopup(${messageId}, true)">👍</button>
        //         <button onclick="openFeedbackPopup(${messageId}, false)">👎</button>
        //       </div>
        //     `;
        //   }

        //   messageCard.innerHTML = `
        //     <div class="bubble-content">${text}</div>
        //     ${buttonsHtml}
        //   `;

        //   chatContainer.appendChild(messageCard);
        //   chatContainer.scrollTop = chatContainer.scrollHeight;
        // }
        // second try

        let feedbackMessageId = null;
        let feedbackLiked = null;
        let disLiked = null;

        function addMessage(text, sender, messageId = null) {
            const chatContainer = document.getElementById('chat-container');

            const messageCard = document.createElement('div');
            messageCard.className = `chat-bubble ${sender}`;
            if (messageId) {
                messageCard.dataset.messageId = messageId;
            }

            let buttonsHtml = '';
            if (sender === 'gemini' && messageId) {
                buttonsHtml = `
      <div class="feedback-buttons">
        <button onclick="liked(${messageId}, true)">👍</button>
        <button onclick="openFeedbackPopup(${messageId}, true)">👎</button>
      </div>
    `;
            }

            messageCard.innerHTML = `
    <div class="bubble-content">${text}</div>
    ${buttonsHtml}
  `;

            chatContainer.appendChild(messageCard);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        async function liked(messageId, liked) {
            feedbackMessageId = messageId;

            const response = await fetch('/api/feedback', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message_id: feedbackMessageId,
                    liked: liked,
                    disliked: false,
                    feedback: ""
                })
            });

            if (response.ok) {
                console.log(`Feedback for message ${messageId}: liked = ${liked}`);
            } else {
                alert('Something went wrong.');
            }


        }

        function openFeedbackPopup(messageId, liked) {
            feedbackMessageId = messageId;
            disLiked = liked;

            document.getElementById('feedback-popup').style.display = 'block';
        }

        function closeFeedbackPopup() {
            document.getElementById('feedback-popup').style.display = 'none';
        }

        async function submitFeedback() {
            const feedbackText = document.getElementById('feedback-text').value;

            const response = await fetch('/api/feedback', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message_id: feedbackMessageId,
                    liked: false,
                    disliked: disLiked,
                    feedback: feedbackText
                })
            });

            if (response.ok) {

            } else {
                alert('Something went wrong.');
            }

            closeFeedbackPopup();
        }





        // Loading animation functions
        function showLoadingAnimation() {
            loadingIndicator.style.display = 'block';
        }

        function hideLoadingAnimation() {
            loadingIndicator.style.display = 'none';
        }

        // Handle file input change event
        document.getElementById('file-upload').addEventListener('change', handleFileSelected);




        async function handleFileSelected(event) {
            let file = event.target.files[0]; // Use 'let' because we might reassign if compression was there
            const MAX_FILE_SIZE_MB = 5; // Set your desired max size in MB to 5MB
            const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024; // Convert to bytes

            if (!file) {
                return;
            }

            const allowedTypes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg', 'audio/mpeg', 'audio/wav']; // Added audio types if your backend supports them
            if (!allowedTypes.includes(file.type)) {
                alert("Only PDF, image, and audio files are allowed.");
                event.target.value = ''; // Clear selection
                return;
            }

            // Check file size against the new 5MB limit
            if (file.size > MAX_FILE_SIZE_BYTES) {
                alert(`File size is too large. Maximum allowed size is ${MAX_FILE_SIZE_MB}MB.`);
                event.target.value = ''; // Clears the selected file(s)
                return;
            }

            // --- REMOVED FILE RESIZING (COMPRESSION) LOGIC ---
            // The previous 'if (file.type.startsWith('image/') && file.size > maxSize)' block is gone.
            // 'file' here will always be the original selected file (after initial size/type checks).

            // Now, send the 'file' directly using sendToBackendWithFile
            // No need to read as DataURL here if you're sending the File object.
            // However, if you want a preview *before* sending, you'd still use FileReader
            // but the `sendToBackend` call will be different.

            let messageType = 'file'; // Default messageType for files
            if (file.type.startsWith('audio/')) {
                messageType = 'audio';
            }

            // Optional: If you still want to display an image preview for images
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = await function (e) {
                    addMessage(`<img src="${e.target.result}" style="max-width: 200px; max-height: 200px; object-fit: contain;">`, 'user'); // Adjust styling as needed
                };
                reader.readAsDataURL(file); // Read as Data URL for preview purposes only
            }

            // Display immediate feedback to the user
            addMessage(`You selected a file: ${file.name} (${(file.size / (1024 * 1024)).toFixed(2)} MB)`, 'user');

            // Send the actual File object to the backend
            sendToBackend(messageType, file);


        }

        // Function to compress image using Canvas API
        function compressImage(file, targetSizeInBytes, quality = 0.8) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const img = new Image();
                    img.onload = () => {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');

                        // Set initial canvas dimensions to image dimensions
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0, img.width, img.height);

                        // Function to try and compress
                        const tryCompress = (currentQuality) => {
                            // For JPEG, quality ranges from 0 to 1
                            // For PNG, quality is ignored (it's lossless unless resized)
                            // If you need PNG transparency and size reduction, you typically only resize.
                            const mimeType = 'image/jpeg'; // Or file.type if you want to keep original type (beware of PNG size)

                            canvas.toBlob((blob) => {
                                if (!blob) {
                                    reject(new Error('Canvas toBlob failed.'));
                                    return;
                                }

                                if (blob.size <= targetSizeInBytes || currentQuality <= 0.1) { // Stop if target reached or quality too low
                                    resolve(new File([blob], file.name, { type: mimeType, lastModified: Date.now() }));
                                } else {
                                    // Reduce quality and try again
                                    const newQuality = Math.max(0.1, currentQuality - 0.1); // Decrease quality by 0.1
                                    tryCompress(newQuality);
                                }
                            }, mimeType, currentQuality);
                        };

                        tryCompress(quality); // Start compression attempt
                    };
                    img.onerror = reject; // Handle image loading errors
                    img.src = event.target.result;
                };
                reader.onerror = reject; // Handle file reading errors
                reader.readAsDataURL(file); // Read file as Data URL
            });
        }



        // Function to save settings
        function saveSettings() {
            const classMode = document.querySelector('input[name="classMode"]:checked').value;
            const voiceConfig = document.querySelector('input[name="voiceConfig"]:checked').value;
            const aiModel = document.getElementById('aiModelSelect').value;

            // Store settings (e.g., in localStorage)
            localStorage.setItem('classMode', classMode);
            localStorage.setItem('voiceConfig', voiceConfig);
            localStorage.setItem('aiModel', aiModel);

            // You can also update a global JS object if needed
            // appSettings.classMode = classMode;
            // appSettings.voiceConfig = voiceConfig;
            // appSettings.aiModel = aiModel;

            console.log("Settings saved:", { classMode, voiceConfig, aiModel });

            // Close the modal
            const settingsModal = bootstrap.Modal.getInstance(document.getElementById('settingsModal'));
            settingsModal.hide();

            // Here you would typically re-initialize or adjust your application's behavior
            // based on the new settings.
        }

        // Function to load settings when the page loads (optional, but good for persistence)
        document.addEventListener('DOMContentLoaded', (event) => {
            const savedClassMode = localStorage.getItem('classMode');
            if (savedClassMode) {
                document.querySelector(`input[name="classMode"][value="${savedClassMode}"]`).checked = true;
            }

            const savedVoiceConfig = localStorage.getItem('voiceConfig');
            if (savedVoiceConfig) {
                document.querySelector(`input[name="voiceConfig"][value="${savedVoiceConfig}"]`).checked = true;
            }

            const savedAiModel = localStorage.getItem('aiModel');
            if (savedAiModel) {
                document.getElementById('aiModelSelect').value = savedAiModel;
            }

        });

        function logOut() {
            window.location.href = "/logout";
        }



        const MAX_CHARACTER_LIMIT = 4000; // You can adjust this value as needed

        function updateCharCount() {
            const messageInput = document.getElementById('message-input');
            const charCountDisplay = document.getElementById('char-count-display');

            if (messageInput && charCountDisplay) {
                const currentLength = messageInput.value.length;
                const remainingChars = MAX_CHARACTER_LIMIT - currentLength;

                // Update the display text
                charCountDisplay.textContent = `${currentLength} / ${MAX_CHARACTER_LIMIT} characters`;

                // Optional: Add visual feedback if the limit is exceeded
                if (remainingChars < 0) {
                    charCountDisplay.style.color = 'red';
                    // Optionally, truncate the input if you want to strictly enforce it client-side
                    // messageInput.value = messageInput.value.substring(0, MAX_CHARACTER_LIMIT);
                    // charCountDisplay.textContent = `${MAX_CHARACTER_LIMIT} / ${MAX_CHARACTER_LIMIT} characters (Limit Reached)`;
                } else {
                    charCountDisplay.style.color = '#666'; // Reset to default color
                }
            }
        }

        // Initial call to set the display when the page loads (in case there's pre-filled text)
        document.addEventListener('DOMContentLoaded', updateCharCount);

        // crping modal functions
        let cropper = null;
        let currentFile = null;
        let cropModal = null;

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function () {
            cropModal = document.getElementById('cropModal');

            // Handle file input change event (your existing code with modifications)
            document.getElementById('file-upload').addEventListener('change', handleFileSelected);

            // Crop modal event listeners
            document.getElementById('aspectRatio').addEventListener('change', updateAspectRatio);
            document.getElementById('cropWidth').addEventListener('input', updateCropSize);
            document.getElementById('cropHeight').addEventListener('input', updateCropSize);

            // Close modal when clicking outside
            cropModal.addEventListener('click', function (event) {
                if (event.target === cropModal) {
                    closeCropModal();
                }
            });
        });

        // Modified version of your handleFileSelected function
        async function handleFileSelected(event) {
            let file = event.target.files[0];
            const MAX_FILE_SIZE_MB = 5;
            const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;

            if (!file) {
                return;
            }

            const allowedTypes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg', 'audio/mpeg', 'audio/wav'];
            if (!allowedTypes.includes(file.type)) {
                alert("Only PDF, image, and audio files are allowed.");
                event.target.value = '';
                return;
            }

            if (file.size > MAX_FILE_SIZE_BYTES) {
                alert(`File size is too large. Maximum allowed size is ${MAX_FILE_SIZE_MB}MB.`);
                event.target.value = '';
                return;
            }

            // Check if it's an image file - if so, open crop modal
            if (file.type.startsWith('image/')) {
                currentFile = file;
                openCropModal(file);
                return; // Don't process immediately, wait for crop
            }

            // For non-image files, process normally
            let messageType = 'file';
            if (file.type.startsWith('audio/')) {
                messageType = 'audio';
            }

            addMessage(`You selected a file: ${file.name} (${(file.size / (1024 * 1024)).toFixed(2)} MB)`, 'user');
            sendToBackend(messageType, file);
        }


        // // Crop modal functions

        // let savedCropBoxData = null;
        // let savedCanvasData = null;

        // // Listen to orientation change and window resize
        // window.addEventListener("resize", restoreCropperPosition);
        // window.addEventListener("orientationchange", restoreCropperPosition);

        // function restoreCropperPosition() {
        //     if (!cropper) return;

        //     // Save state before re-render
        //     savedCropBoxData = cropper.getCropBoxData();
        //     savedCanvasData = cropper.getCanvasData();

        //     // Rebuild cropper after layout settle
        //     setTimeout(() => {
        //         cropper.destroy();
        //         const image = document.getElementById('cropImage');

        //         cropper = new Cropper(image, {
        //             aspectRatio: NaN,
        //             viewMode: 1,
        //             autoCropArea: 0.8,
        //             responsive: true,
        //             restore: false,

        //             ready() {
        //                 // Restore saved positions
        //                 if (savedCanvasData) cropper.setCanvasData(savedCanvasData);
        //                 if (savedCropBoxData) cropper.setCropBoxData(savedCropBoxData);
        //             }
        //         });
        //     }, 250); // small delay to allow DOM resize
        // }

        // --- helpers ---
        function waitForStableImageWidth(img, { checkInterval = 60, stableMillis = 180, maxWait = 2000 } = {}) {
            return new Promise((resolve) => {
                let last = img.clientWidth;
                let stableFor = 0;
                let waited = 0;

                const tick = () => {
                    const w = img.clientWidth;
                    if (w !== last) {
                        last = w;
                        stableFor = 0;
                    } else {
                        stableFor += checkInterval;
                    }
                    waited += checkInterval;

                    if (stableFor >= stableMillis || waited >= maxWait) {
                        resolve();
                    } else {
                        setTimeout(tick, checkInterval);
                    }
                };

                tick();
            });
        }

        // --- improved restore function ---
        let savedCropBoxData = null;
        let savedCanvasData = null;
        let restorePending = false;

        function saveCropStateImmediate() {
            if (!cropper) return;
            try {
                savedCropBoxData = cropper.getCropBoxData();
                savedCanvasData = cropper.getCanvasData();
            } catch (e) {
                console.warn('saveCropStateImmediate error', e);
            }
        }

        async function restoreCropperPosition() {
            if (!cropper || restorePending) return;
            restorePending = true;

            // save immediately
            saveCropStateImmediate();

            // The image element that Cropper is using
            const image = document.getElementById('cropImage');

            // If visualViewport exists, wait until it stops resizing
            if (window.visualViewport) {
                // wait for visualViewport to stop changing (debounced)
                await new Promise(resolve => {
                    let vPrevW = window.visualViewport.width;
                    let vPrevH = window.visualViewport.height;
                    let debounce = null;
                    const onVV = () => {
                        clearTimeout(debounce);
                        debounce = setTimeout(() => {
                            // small extra delay to ensure layout settled
                            setTimeout(() => {
                                window.visualViewport.removeEventListener('resize', onVV);
                                resolve();
                            }, 80);
                        }, 120);
                    };
                    window.visualViewport.addEventListener('resize', onVV);
                    // also set a max-wait fallback
                    setTimeout(() => {
                        window.visualViewport.removeEventListener('resize', onVV);
                        resolve();
                    }, 2000);
                    // in case there is no resize event, resolve immediately after microtask
                    setTimeout(() => {
                        if (window.visualViewport.width === vPrevW && window.visualViewport.height === vPrevH) {
                            window.visualViewport.removeEventListener('resize', onVV);
                            resolve();
                        }
                    }, 50);
                });
            }

            // Additionally ensure the actual image width is stable (works for browsers without visualViewport)
            await waitForStableImageWidth(image, { checkInterval: 60, stableMillis: 160, maxWait: 2500 });

            // small extra delay to be safe on some devices
            await new Promise(r => setTimeout(r, 80));

            try {
                // destroy and re-create cropper, then restore
                cropper.destroy();

                cropper = new Cropper(image, {
                    aspectRatio: NaN,
                    viewMode: 1,
                    autoCropArea: 0.8,
                    responsive: true,
                    restore: false,
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                    toggleDragModeOnDblclick: false,
                    minCropBoxWidth: 50,
                    minCropBoxHeight: 50,
                    ready() {
                        try {
                            if (savedCanvasData) cropper.setCanvasData(savedCanvasData);
                            if (savedCropBoxData) cropper.setCropBoxData(savedCropBoxData);
                        } catch (err) {
                            console.warn('restore setCanvas/setCrop error', err);
                        }
                    }
                });
            } catch (err) {
                console.error('restoreCropperPosition error', err);
            } finally {
                // give a little time then allow future restores
                setTimeout(() => { restorePending = false; }, 120);
            }
        }

        // attach listeners — keep BOTH because some browsers fire only one
        window.addEventListener('resize', restoreCropperPosition);
        window.addEventListener('orientationchange', restoreCropperPosition);



        // Open crop modal
        function openCropModal(file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById('cropImage').src = e.target.result;
                cropModal.style.display = 'block';
                document.body.style.overflow = 'hidden'; // Prevent background scroll

                // Initialize cropper after image loads
                setTimeout(() => {
                    initializeCropper();
                    savedCropState = null;   // fresh open = no restore
                }, 100);
            };
            reader.readAsDataURL(file);
        }

        // Close crop modal
        function closeCropModal() {
            cropModal.style.display = 'none';
            document.body.style.overflow = 'auto'; // Restore scroll

            if (cropper) {
                cropper.destroy();
                cropper = null;
            }

            // Clear file input
            document.getElementById('file-upload').value = '';
            currentFile = null;
        }

        // Initialize cropper
        function initializeCropper() {
            if (cropper) {
                cropper.destroy();
            }

            const image = document.getElementById('cropImage');
            cropper = new Cropper(image, {
                aspectRatio: NaN,
                viewMode: 1,
                autoCropArea: 0.8,
                responsive: true,
                restore: false,
                guides: true,
                center: true,
                highlight: false,
                cropBoxMovable: true,
                cropBoxResizable: true,
                toggleDragModeOnDblclick: false,
                minCropBoxWidth: 50,
                minCropBoxHeight: 50,
            });
        }

        // Update aspect ratio
        function updateAspectRatio() {
            if (!cropper) return;

            const ratio = document.getElementById('aspectRatio').value;
            if (ratio === 'free') {
                cropper.setAspectRatio(NaN);
            } else {
                cropper.setAspectRatio(parseFloat(ratio));
            }
        }

        // Update crop size
        function updateCropSize() {
            if (!cropper) return;

            const width = parseInt(document.getElementById('cropWidth').value);
            const height = parseInt(document.getElementById('cropHeight').value);

            if (width && height) {
                cropper.setCropBoxData({
                    width: width,
                    height: height
                });
            }
        }

        // Rotate image
        function rotateImage(degree) {
            if (cropper) {
                cropper.rotate(degree);
            }
        }

        // Flip image
        function flipImage(direction) {
            if (!cropper) return;

            if (direction === 'horizontal') {
                cropper.scaleX(-cropper.getImageData().scaleX);
            } else {
                cropper.scaleY(-cropper.getImageData().scaleY);
            }
        }

        // Reset crop
        function resetCrop() {
            if (cropper) {
                cropper.reset();
            }
        }

        // Apply crop and send to backend
        function applyCropAndSend() {
            if (!cropper || !currentFile) return;

            showCropStatus('Processing image...', 'info');

            const canvas = cropper.getCroppedCanvas({
                width: document.getElementById('cropWidth').value || undefined,
                height: document.getElementById('cropHeight').value || undefined,
                imageSmoothingEnabled: true,
                imageSmoothingQuality: 'high',
            });

            const quality = parseFloat(document.getElementById('quality').value);

            canvas.toBlob((blob) => {
                // Create a new file from the cropped blob
                const croppedFile = new File([blob], `cropped_${currentFile.name}`, {
                    type: 'image/jpeg',
                    lastModified: Date.now()
                });

                // Show preview message
                const previewUrl = URL.createObjectURL(blob);
                addMessage(`<img src="${previewUrl}" style="max-width: 200px; max-height: 200px; object-fit: contain; border-radius: 8px;">`, 'user');
                addMessage(`Cropped image: ${croppedFile.name} (${(croppedFile.size / (1024 * 1024)).toFixed(2)} MB)`, 'user');

                // Send to backend using your existing function
                sendToBackend('file', croppedFile);

                // Close modal
                closeCropModal();

                // Clean up URL
                setTimeout(() => URL.revokeObjectURL(previewUrl), 1000);

            }, 'image/jpeg', quality);
        }

        // Show crop status
        function showCropStatus(message, type) {
            const statusEl = document.getElementById('cropStatus');
            statusEl.textContent = message;
            statusEl.className = `status ${type}`;
            statusEl.style.display = 'block';

            if (type !== 'info') {
                setTimeout(() => {
                    statusEl.style.display = 'none';
                }, 3000);
            }
        }


        function handleFeedback(responseId, type) {
            if (type === 'up') {
                const userFeedback = prompt("What did you like about this response?");
                sendFeedbackToBackend(responseId, type, userFeedback);
            } else {
                sendFeedbackToBackend(responseId, type, null);
            }
        }

        async function sendFeedbackToBackend(responseId, type, comment) {
            const payload = {
                response_id: responseId,
                thumb: type,
                feedback: comment,
                client_id: clientId
            };
            await fetch('/api/feedback', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            alert('Thank you for your feedback!');
        }


        function toggleDrawer() {
            document.getElementById('side-drawer').classList.toggle('open');
        }

        async function loadConversations() {
            const response = await fetch('https://lm.warals.codetorise.com/my/conversations/', {
                headers: {
                    'Authorization': `Bearer ${accessToken}`

                }
            });


            const data = await response.json();
            const list = document.getElementById('conversation-list');
            list.innerHTML = '';
            console.log("Loaded conversations:", data);

            data.forEach(conv => {
                const li = document.createElement('li');
                //    li.innerHTML = `
                //  <i class="fas fa-comments"></i> ${new Date(conv.created_at).toLocaleString()}
                //`;
                li.innerHTML = `
      <div class="d-flex justify-content-between align-items-center">
        <span><i class="fas fa-comments"></i> ${new Date(conv.created_at).toLocaleString()}</span>
        <button class="progress-btn" title="View Progress">
        <i class="fas fa-chart-simple"></i>
        </button>
      </div>
    `;

                li.querySelector('.progress-btn').onclick = (e) => {
                    e.stopPropagation();
                    showProgress(conv.conversation_id);
                    toggleDrawer();
                };

                li.onclick = () => loadConversationMessages(conv.conversation_id);
                list.appendChild(li);
            });
        }

        document.querySelector('.menu-btn').addEventListener('click', loadConversations);

        async function loadConversationMessages(conversationId) {
            toggleDrawer();
            const response = await fetch(`https://lm.warals.codetorise.com/my/conversations/${conversationId}/messages/`, {
                headers: {
                    'Authorization': `Bearer ${accessToken}`
                }
            });

            const messages = await response.json();
            console.log("Loaded messages:", messages);
            const chatContainer = document.getElementById('chat-container');
            chatContainer.innerHTML = '';

            messages.forEach(msg => {
                const sender = msg.sender === 'user' ? 'user' : 'gemini';
                const content = msg.content ? msg.content : '📎 File sent';
                addMessage(content, sender, msg.id);
                console.log("message ${msg}");
            });
        }
        function showLimitModal() {
            document.getElementById('limitModal').style.display = 'block';
        }
        function sendLimitResponse(choice) {
            // sendToBackend('text', choice);
            console.log(choice);
            if (choice === '#No') {
                // window.location.href = '/upgrade';
                clientId = generateClientId(); // NEW session
                console.log("Session reset, new clientId:", clientId);
                document.getElementById('limitModal').style.display = 'none';
                addMessage('Gemini: Ok! Provide New Content', 'gemini');
                return;
            }
            addMessage(`Gemini: Ok let's Continue!`, 'gemini');
            document.getElementById('limitModal').style.display = 'none';
        }


        async function showProgress(conversationId) {
            try {
                const response = await fetch(`https://lm.warals.codetorise.com/progress/?conversation_id=${conversationId}`, {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });

                const data = await response.json();
                console.log("Progress data:", data);

                // Display progress modal
                const modal = document.getElementById('progress-modal');
                const details = document.getElementById('progress-details');

                details.innerHTML = `
      <p><strong>Total Questions:</strong> ${data.total_questions}</p>
      <p><strong>Correct Answers:</strong> ${data.correct_answers}</p>
      <p><strong>Total Score:</strong> ${data.total_score}</p>
      <p><strong>Percentage:</strong> ${data.percentage}%</p>
    `;

                modal.style.display = 'block';

                // Render Chart
                const ctx = document.getElementById('progressChart').getContext('2d');

                // Destroy the old chart instance before creating a new one
                if (progressChartInstance) {
                    progressChartInstance.destroy();
                }

                // Calculate correct vs incorrect
                const correct = data.correct_answers;
                const incorrect = data.total_questions - data.correct_answers;

                progressChartInstance = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels: ['Correct', 'Incorrect'],
                        datasets: [{
                            data: [correct, incorrect],
                            backgroundColor: ['#4CAF50', '#FF5252'], // Green / Red
                            borderWidth: 1
                        }]
                    },
                    options: {
                        plugins: {
                            legend: {
                                position: 'bottom'
                            },
                            tooltip: {
                                callbacks: {
                                    label: function (context) {
                                        const total = correct + incorrect;
                                        const percentage = ((context.parsed / total) * 100).toFixed(1);
                                        return `${context.label}: ${context.parsed} (${percentage}%)`;
                                    }
                                }
                            }
                        }
                    }
                });

            } catch (error) {
                console.error('Error fetching progress:', error);
            }
        }


        function closeProgressModal() {
            const modal = document.getElementById('progress-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        }

        function goToDashboard() {
            // Get token from your app's state/localStorage/cookie
            //const token = localStorage.getItem('accessToken') || window.accessToken;
            const token = accessToken
            if (token) {
                // Store token for dashboard to use
                localStorage.setItem('accessToken', token);

                // Navigate to dashboard
                window.location.href = '/dashboard';
            } else {
                alert('Please login first');
                window.location.href = '/';
            }
        }

        //mobile cropping enhancements
        // --- helpers ---
        let savedImageData = null;
        let savedContainerData = null;

        let resizeTimeout = null;

        function saveCropStateImmediate() {
            if (!cropper) return;
            try {
                savedCropBoxData = cropper.getCropBoxData();
                savedCanvasData = cropper.getCanvasData();
                savedImageData = cropper.getImageData();
                savedContainerData = cropper.getContainerData();
            } catch (e) {
                console.warn('saveCropStateImmediate error', e);
            }
        }

        async function restoreCropperPosition() {
            if (!cropper || restorePending) return;
            restorePending = true;

            // Clear any pending timeout
            clearTimeout(resizeTimeout);

            // save immediately
            saveCropStateImmediate();

            // The image element that Cropper is using
            const image = document.getElementById('cropImage');

            // Wait for orientation change to complete (mobile specific)
            await new Promise(resolve => setTimeout(resolve, 300));

            // If visualViewport exists, wait until it stops resizing
            if (window.visualViewport) {
                await new Promise(resolve => {
                    let debounce = null;
                    const onVV = () => {
                        clearTimeout(debounce);
                        debounce = setTimeout(() => {
                            setTimeout(() => {
                                window.visualViewport.removeEventListener('resize', onVV);
                                resolve();
                            }, 100);
                        }, 150);
                    };
                    window.visualViewport.addEventListener('resize', onVV);

                    // Fallback timeout
                    setTimeout(() => {
                        window.visualViewport.removeEventListener('resize', onVV);
                        resolve();
                    }, 2500);
                });
            }

            // Wait for image dimensions to stabilize
            await waitForStableImageWidth(image, { checkInterval: 80, stableMillis: 200, maxWait: 3000 });

            // Extra delay for mobile orientation
            await new Promise(r => setTimeout(r, 150));

            try {
                const oldImageData = savedImageData;
                const oldContainerData = savedContainerData;

                // Destroy and re-create cropper
                cropper.destroy();

                cropper = new Cropper(image, {
                    aspectRatio: NaN,
                    viewMode: 1,
                    autoCropArea: 0.8,
                    responsive: true,
                    restore: false,
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                    toggleDragModeOnDblclick: false,
                    minCropBoxWidth: 50,
                    minCropBoxHeight: 50,
                    ready() {
                        try {
                            // Get new dimensions after reinitialization
                            const newImageData = cropper.getImageData();
                            const newContainerData = cropper.getContainerData();
                            const newCanvasData = cropper.getCanvasData();

                            // Calculate container scale ratios
                            const containerScaleX = newContainerData.width / oldContainerData.width;
                            const containerScaleY = newContainerData.height / oldContainerData.height;

                            // Calculate the proportional position and size for crop box
                            const scaledCropBox = {
                                left: savedCropBoxData.left * containerScaleX,
                                top: savedCropBoxData.top * containerScaleY,
                                width: savedCropBoxData.width * containerScaleX,
                                height: savedCropBoxData.height * containerScaleY
                            };

                            // Don't restore canvas data - let Cropper.js handle image fitting naturally
                            // Only restore the crop box with adjusted dimensions
                            cropper.setCropBoxData(scaledCropBox);

                        } catch (err) {
                            console.warn('restore setCropBox error', err);
                        }
                    }
                });
            } catch (err) {
                console.error('restoreCropperPosition error', err);
            } finally {
                // Allow future restores after a delay
                setTimeout(() => { restorePending = false; }, 200);
            }
        }

        // Debounced resize handler for better mobile performance
        function handleResize() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                restoreCropperPosition();
            }, 200);
        }

        // attach listeners
        window.addEventListener('resize', handleResize);
        window.addEventListener('orientationchange', () => {
            // Immediate call for orientation change, then debounced
            setTimeout(() => restoreCropperPosition(), 100);
        });

        // Also listen for screen orientation API if available
        if (screen.orientation) {
            screen.orientation.addEventListener('change', () => {
                setTimeout(() => restoreCropperPosition(), 100);
            });
        }
        // mobile cropping enhancements end
    </script>
</body>

</html>