<meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name='viewport' content='width=device-width, initial-scale=1'/><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=yes">
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت مطالعه دروس</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.fontcdn.ir/Font/Persian/B%20Nazanin/B%20Nazanin.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
          <style>
        body {
    font-family: Arial, sans-serif;
    direction: rtl;
    text-align: right;
            max-width: 900px;
            background-color: #fdf3e7; /* یک مقدار تیره‌تر از سفید */
    background-image: url('https://www.transparenttextures.com/patterns/cubes.png'); /* لینک به یک تصویر ساده */
    background-size: 300px 300px; 
    * تنظیم اندازه نقش‌ها */
}
        .container {
            margin-top: 50px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }
        th, td {
            text-align: center;
            padding: 10px;
        }
        th {
    background-color: #11452a !important; /* رنگ پس‌زمینه جدید با اولویت بالا */
    color: #b39292 !important; /* رنگ متن سفید با اولویت بالا */
    text-align: center;
    padding: 10px;
}
        td {
            font-weight: bold;
        }
        .extra-time {
            color: red;
            font-weight: bold;
        }
        .additional-fields {
            display: none;
            margin-top: 5px;
        }
        .chart-container {
            margin-top: 40px;
        }
        .chart-item {
            margin-bottom: 40px;
        }
        input[type="number"] {
            width: 100px;
        }
        .details-container {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: white;
            z-index: 9999;
            padding: 20px;
            overflow-y: auto;
            overflow-x: hidden
        }
        .scroll-container {
            max-height: 400px;
            width: 120%;
            overflow-y: scroll;
            overflow-x: hidden; 
            border: 1px solid #ccc;
            margin-bottom: 20px;
        }
        .page-button {
            width: 50px;
            margin: 5px;
            color: white;
        }
        .green {
            background-color: green;
        }
        .orange {
            background-color: orange;
        }
        .red {
            background-color: red;
        }
        .note-container {
            margin-top: 20px;
            text-align: center;
        }
        .note-btns {
            display: none;
            margin-top: 10px;
        }
        .note-btns .btn {
            margin: 5px;
        }
        .reminder-modal, .notes-modal, .translation-modal, .important-notes-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #706331;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 10000;
            width: 400px;
            max-height: 80%;
            overflow-y: auto;
        }
  .reminder-alert-modal {
  display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #bfbcb2;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 10000;
            width: 400px;
            max-height: 80%;
            overflow-y: auto;
        }
        .modal-header {
            font-weight: bold;
            margin-bottom: 20px;
            text-align: center;
        }
        .modal-footer {
            text-align: center;
            margin-top: 20px;
        }
        .scrollable-content {
            max-height: 300px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .blinking-icon {
            font-size: 20px;
            color: red;
            animation: blink 1s infinite;
            cursor: pointer;
        }
        @keyframes blink {
            50% {
                opacity: 0;
            }
        }
    /* تنظیم اندازه پنجره یادآور (reminder-modal) */
.reminder-modal {
    width: 95vw; /* 95% عرض صفحه */
    max-width: 380px; /* کاهش 5% از مقدار اولیه */
    max-height: 76vh; /* کاهش 5% از مقدار اولیه */
    overflow-y: auto;
}

/* تنظیم اندازه پنجره Set Reminder */
.set-reminder-modal {
    width: 95vw; /* 95% عرض صفحه */
    max-width: 380px;
    max-height: 76vh;
    overflow-y: auto;
}

/* تنظیم اندازه پنجره ترجمه (translation-modal) */
.translation-modal {
    width: 95vw; /* 95% عرض صفحه */
    max-width: 361px; /* کاهش 5% از مقدار اولیه */
    max-height: 71vh; /* کاهش 5% از مقدار اولیه */
    overflow-y: auto;
}

/* تنظیم اندازه پنجره نکات مهم (important-notes-modal) */
.important-notes-modal {
    width: 95vw; /* 95% عرض صفحه */
    max-width: 380px;
    max-height: 76vh; /* کاهش 5% از مقدار اولیه */
    overflow-y: auto;
}
    /* تنظیم عرض فیلدهای ورودی در پنجره Translations */
/* تنظیم عرض فیلدهای ورودی به مقدار ثابت *//* تنظیم عرض فیلدهای ورودی به مقدار 220px (1.1 برابر) */
/* تنظیم عرض فیلدهای ورودی به 140px (0.7 برابر مقدار اولیه) */
.translation-input {
    width: 140px; /* تنظیم عرض به 140px */
    max-width: 100%; /* جلوگیری از بزرگ‌تر شدن بیش از حد */
}
    /* انتقال دکمه‌های پنجره Reminder Alert به سمت راست */
/* انتقال دکمه‌های پنجره Reminder Alert به سمت راست */
/* انتقال دکمه‌های پنجره Reminder Alert به سمت راست */
/* انتقال دکمه‌های پنجره Reminder Alert به سمت راست */
/* انتقال دکمه‌های پنجره Reminder Alert کمی بیشتر به سمت راست */
.reminder-alert-modal .modal-footer {
    display: flex;
    justify-content: flex-end;  /* انتقال دکمه‌ها به انتهای راست */
    margin-left: 20px;          /* اضافه کردن فاصله اضافی به سمت راست */
    padding: 10px;
    gap: 10px;                  /* ایجاد فاصله بین دکمه‌ها */
}
    #backup-restore-buttons {
    display: flex;
    justify-content: space-between;
    gap: 10px;
}

#backup-btn, #restor-btn {
    width: 150px;
}
    /* تنظیم دکمه‌های Backup و Restore کنار هم */
#backup-restore-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-bottom: 20px;
}

/* تنظیم دکمه‌های Backup و Restore */
#backup-btn, #restore-btn {
    width: 150px;
}

/* تنظیم دکمه Close (×) زیر دکمه‌های Backup و Restore */
#close-btn {
    display: block;
    margin: 0 auto; /* وسط‌چین کردن دکمه Close */
    width: 50px;
    height: 50px;
}
  /* استایل پیش‌فرض برای دکمه‌های پیج باتن */
/* استایل پیش‌فرض برای دکمه‌های پیج باتن بدون رنگ خاص */
/* استایل پیش‌فرض برای دکمه‌های پیج باتن بدون رنگ خاص */
.page-button {
    background-color: transparent; /* شفاف یا بدون پس‌زمینه خاص */
    color: #A9A9A9; /* خاکستری تیره برای حالت پیش‌فرض */
}

/* زمانی که دکمه سبز است */
.page-button.green {
    background-color: #246e14; /* رنگ سبز سفارشی */
    color: #FFFFFF !important; /* رنگ متن سفید */
}

/* زمانی که دکمه قرمز است */
.page-button.red {
    background-color: #ab0909; /* رنگ قرمز سفارشی */
    color: #FFFFFF !important; /* رنگ متن سفید */
}

/* زمانی که دکمه نارنجی است */
.page-button.orange {
    background-color: #a86507; /* نارنجی تیره‌تر */
    color: #FFFFFF !important; /* رنگ متن سفید */
}   
.translation-input {
    width: 140px;
    max-width: 100%; /* جلوگیری از بزرگ‌تر شدن بیش از حد */
}  
  /* لایه طوسی متمایل به مشکی */
/* لایه پوششی طوسی تیره */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 150%;
    height: 100%;
    background-color: rgba(50, 50, 50, 0.9); /* رنگ طوسی متمایل به مشکی */
    z-index: 10000; /* قرارگیری پشت پنجره‌های مودال */
    display: none;
    pointer-events: none; /* غیرفعال کردن کلیک روی این لایه */
    color: rgba(255, 255, 255, 0.2); /* رنگ محو برای نمایش نام درس */
    font-size: 2.5rem;  /* اندازه بزرگ برای نام درس */
    font-weight: bold;
    color: #888888;
    text-align: center;
    overflow: hidden;
    line-height: 18vh; /* متن در مرکز صفحه قرار گیرد */
}

/* فعال‌سازی لایه */
.modal-overlay.active {
    display: block;
}
  h1 {
    font-weight: bold; /* بولد کردن تیتر */
}
    .move-left {
    margin-right: 20px; /* فاصله از سمت راست (جابجایی به سمت چپ) */
}
    /* استایل مربوط به بخش جستجو و نمایش نتایج */
#search-container {
    margin-top: 20px;
}

#search-input {
    width: 100%;
    padding: 10px;
    border-radius: 5px;
    border: 1px solid #ccc;
}

#search-results {
    border: 1px solid #ccc;
    background-color: white;
    max-height: 300px;
    overflow-y: auto;
    display: none;
    position: absolute;
    width: 100%;
    z-index: 10;
    top: 60px;
}

#search-results div {
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #f1f1f1;
}

#search-results div:hover {
    background-color: #f1f1f1;
}

.highlight {
    background-color: yellow;
    font-weight: bold;
}

/* استایل اسکرول */
.scrollable {
    max-height: 200px;
    overflow-y: auto;
}

/* استایل آیکون ذره‌بین */
.search-icon::before {
    content: "\1F50D"; /* Unicode for magnifying glass */
    position: absolute;
    left: 10px;
    font-size: 1.5rem;
    top: 50%;
    transform: translateY(-50%);
}
    #search-input {
    width: 200px; /* عرض جدید کادر جستجو */
    padding: 10px;
    border-radius: 5px;
    border: 1px solid #ccc;
}
    #search-input {
    width: 200px; /* عرض باریک‌تر */
    padding: 5px;
    border-radius: 5px;
    border: 1px solid #ccc;
    margin-bottom: 20px; /* فاصله از جدول زیر */
}

#search-container {
    margin-bottom: 20px; /* فاصله از جدول زیر */
}
    #search-input::placeholder {
    color: #999; /* رنگ کم‌رنگ‌تر برای placeholder */
    font-size: 0.85rem; /* سایز کوچک‌تر */
}
    
    .container {
    max-width: 100%; /* اطمینان از اینکه عرض بیش از حد نمی‌شود */
    margin: 0 auto; /* وسط‌چین کردن محتوا در صفحه */
}

.modal {
    max-width: 100%; /* جلوگیری از کشیدگی بیش از حد پنجره‌ها */
}
  .highlight {
    background-color: #FFCC00; /* رنگ زرد متمایل به خردلی */
    font-weight: bold;
}
  .btn-light-purple {
    background-color: #dda0dd; /* بنفش کم‌رنگ */
    color: white;
}
  .move-left {
    margin-right: 20px; /* جابجایی به سمت چپ */
}
   #restore-options {
    display: none; /* دکمه‌های جدید ابتدا مخفی باشند */
}

#restore-btn, #import-notes-btn {
    width: 100%; /* عرض دکمه‌های جدید برابر با دکمه Restore */
}
  .replace-button {
    white-space: nowrap; /* جلوگیری از شکستن متن */
    width: 100%; /* تنظیم عرض دکمه (می‌توانید اندازه را به دلخواه تغییر دهید) */
    max-width: 200px; /* حداکثر عرض برای دکمه */
}
  .replace-button {
    margin-bottom: 0px; /* فاصله عمودی بین دکمه‌ها (مقدار به دلخواه قابل تنظیم است) */
}
  #import-notes-btn {
    background-color: #6520a1; /* رنگ بنفش کم‌رنگ */
    color: white; /* متن سفید */
}
  .btn-details {
    background-image: url(https://www.ohwpaint.com/cdn/shop/products/hydrographic-film-green-snake-pattern_2400x.jpg?v=1598625602); /* تصویر بافت */
    background-size: 100px 100px; /* اندازه مناسب تصویر */
    background-repeat: repeat; /* تکرار تصویر برای پر کردن دکمه */
    color: white; /* رنگ متن سفید */
    border: 2px solid #006400; /* حاشیه سبز تیره */
    border-radius: 10px; /* گرد کردن گوشه‌ها */
    padding: 5px 10px; /* کاهش padding برای کاهش عرض دکمه */
    box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.5); /* سایه برای برجسته کردن دکمه */
    text-shadow: 1px 1px 2px black; /* سایه برای متن */
    font-weight: bold; /* متن بولد */
    transition: transform 0.3s ease, box-shadow 0.3s ease; /* افکت حرکت هنگام هاور */
    max-width: 150px; /* حداکثر عرض دکمه */
    width: 100%; /* عرض دکمه محدود به 100% شود */
    overflow: hidden; /* جلوگیری از بیرون زدن تصویر */
    white-space: nowrap; /* جلوگیری از انتقال متن به خط بعدی */
    display: inline-block; /* جلوگیری از پر شدن کل عرض */
    text-align: center; /* متن در وسط قرار گیرد */
}

.btn-details:hover {
    transform: scale(1.05); /* بزرگ شدن دکمه هنگام هاور */
    box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.7); /* سایه بیشتر هنگام هاور */
}
  .button-container {
    display: flex;
    justify-content: center; /* مرکز کردن مجموعه دکمه‌ها */
    align-items: center;
    gap: 20px; /* فاصله ثابت بین دکمه‌ها */
      margin-bottom: 20px;
}

.memory-btn {
    font-size: 0.85rem; /* کوچک‌تر کردن متن */
    padding: 8px 12px; /* کاهش فضای داخلی دکمه */
    background-color: #654321; /* قهوه‌ای تیره */
    border: none; /* حذف حاشیه پیش‌فرض */
    border-radius: 10px; /* گرد کردن گوشه‌ها */
    color: white; /* رنگ متن سفید */
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); /* افزودن سایه برای زیبایی */
    transition: background-color 0.3s ease, transform 0.3s ease; /* ایجاد انیمیشن تغییر رنگ و اندازه */
}

.memory-btn:hover {
  color: white; 
    background-color: #5D3A1A; /* قهوه‌ای تیره‌تر هنگام هاور */
    transform: translateY(-2px); /* تغییر مختصر در موقعیت برای جلوه‌ی زیباتر */
}
  .details-container {
    background-color: #f5f5dc; /* رنگ بژ */
    background-image: url('https://www.transparenttextures.com/patterns/cubes.png'); /* لینک به یک تصویر طرح‌دار */
    background-size: 300px 300px; /* تنظیم اندازه الگو */
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    z-index: 9999;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
}
  .btn-note {
    background-image: url(https://i.ibb.co/tLZQG9Z/Screenshot-20241007-173155-Google.jpg); /* تصویر جدید */
    background-size: cover; /* پوشش کامل دکمه با تصویر */
    background-repeat: no-repeat; /* جلوگیری از تکرار تصویر */
    color: white; /* رنگ متن سفید */
    border: 2px solid #006400; /* حاشیه سبز تیره */
    border-radius: 10px; /* گرد کردن گوشه‌ها */
    padding: 10px 20px; /* فضای داخلی دکمه */
    box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.5); /* سایه برای برجسته کردن دکمه */
    text-shadow: 1px 1px 2px black; /* سایه برای متن */
    font-weight: bold; /* متن بولد */
    font-size: 18px;
    transition: transform 0.3s ease, box-shadow 0.3s ease; /* افکت حرکت هنگام هاور */
}

.btn-note:hover {
    transform: scale(1.05); /* بزرگ شدن دکمه هنگام هاور */
    box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.7); /* سایه بیشتر هنگام هاور */
}
  .btn-with-image {
    background-image: url('https://i.ibb.co/6NTRHjy/Screenshot-20241007-175202-Google.jpg'); /* تصویر پس‌زمینه */
    background-size: 40px 40px; /* تصویر کاملاً دکمه را پوشش می‌دهد */
    background-position: center; /* تصویر در مرکز دکمه قرار می‌گیرد */
    background-repeat: repeat; /* جلوگیری از تکرار تصویر */
    color: white; /* رنگ متن */
}

.btn-with-image:hover {
    background-color: rgba(0, 0, 0, 0.5); /* افکت هاور با تغییر رنگ پس‌زمینه */
}
.btn-database {
    width: 283px;
    background-image: url(https://www.ohwpaint.com/cdn/shop/products/hydrographic-film-green-snake-pattern_2400x.jpg?v=1598625602); /* تصویر بافت پوست مار */
    background-size: 50px 50px; /* اندازه مناسب تصویر */
    background-repeat: repeat; /* تکرار تصویر برای پر کردن دکمه */
    color: white; /* رنگ متن سفید */
    border: 1px solid rgba(0, 0, 0, 0.125); /* حاشیه استاندارد */
    border-radius: 25px; /* گرد کردن حاشیه‌ها */
    padding: 10px 20px; /* فاصله داخلی */
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); /* سایه استاندارد */
    font-weight: bold; /* بولد کردن متن */
    transition: transform 0.3s ease, box-shadow 0.3s ease; /* افکت هاور */
    text-align: center; /* وسط‌چین کردن متن */
    outline: 2px solid #FFCC00; /* اوت‌لاین زرد پررنگ */
    outline-offset: 0.5px; /* فاصله اوت‌لاین از دکمه */
    

    /* تنظیمات وسط‌چین کردن افقی */
    display: block;
    margin: 0 auto;
}

.btn-database:hover {
    background-color: rgba(0, 0, 0, 0.1); /* تغییر رنگ پس‌زمینه هنگام هاور */
    transform: scale(1.05); /* بزرگ شدن هنگام هاور */
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); /* سایه بیشتر هنگام هاور */
    outline: 3px solid yellow; /* اوت‌لاین زرد پررنگ */
}
  /* تغییر رنگ پس‌زمینه برای فیلدهای ورودی در پنجره Important Notes */
.important-notes-modal input[type="text"],
.important-notes-modal textarea {
    background-color: #a39976; /* رنگ پس‌زمینه جدید */
    color: black; /* رنگ متن سفید برای خوانایی بهتر */
}

/* تغییر رنگ پس‌زمینه برای فیلدهای ورودی در پنجره Translations */
.translation-modal input[type="text"],
.translation-modal textarea {
    background-color: #a39976; /* رنگ پس‌زمینه جدید */
    color: black; /* رنگ متن سفید برای خوانایی بهتر */
}
 .blinking-icon {
    font-size: 20px;
    color: red;
    animation: blink 1s infinite;
    cursor: pointer;
}

@keyframes blink {
    50% {
        opacity: 0;
    }
}
 html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}

.footer-text {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    text-align: center;
    z-index: 999999;
    pointer-events: none;
}

.footer-text span {
    display: inline-block;
    white-space: nowrap;
    padding-left: 100%;
    animation: marquee 50s linear infinite; /* انیمیشن 50 ثانیه‌ای */
    color: rgba(0, 0, 0, 0.7);
    font-size: 14px;
    pointer-events: none;
}

@keyframes marquee {
    0% {
        transform: translateX(100%);
    }
    50% {
        transform: translateX(-100%); /* حرکت کامل به سمت چپ در 20 ثانیه */
    }
    51% {
        transform: translateX(-100%);
    }
    100% {
        transform: translateX(-100%);
    }
}
  #search-container {
    position: relative;
    display: flex;
    align-items: center;
}

#search-results {
    position: relative; /* تغییر موقعیت به relative برای جابجایی */
    margin-top: 5px; /* کمی فاصله از فیلد جستجو */
    left: 5px; /* جابجایی کانتینر به سمت راست */
    top: -1px; /* جابجایی کانتینر به سمت بالا */
    width: 104%; /* تنظیم عرض به اندازه فیلد جستجو */
    border-top: 4px solid #9f06c2; /* قاب در بالا */
    border-left: 4px solid #1fc206; /* قاب در سمت چپ */
    border-right: 4px solid #1fc206; /* قاب در سمت راست */
    background-color: #bdb9ba;
    max-height: 580px;
    overflow-y: auto;
    z-index: 10; /* برای نمایش بالاتر از سایر عناصر */
    border-radius: 10px 10px 0 0; /* گرد کردن لبه‌های بالایی قاب */
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); /* سایه برای زیبایی بیشتر */
}

#search-input {
    flex-grow: 1;
    width: auto;
}

.importance-btn {
    background-color: #c2a678; /* بژ پر رنگ */
    color: black; /* رنگ متن */
    border-color: #c2a678; /* برای ایجاد هماهنگی بین پس‌زمینه و حاشیه */
    font-size: 10px; 
    padding: 2px 6px;
    margin-right: 35px;
}   
  #search-results div {
    background-color: #bdb9ba; /* رنگ پیش‌فرض */
    pointer-events: all; /* اجازه کلیک و تعامل */
}

#search-results div:active,
#search-results div:focus,
#search-results div:hover {
    background-color: #bdb9ba; /* جلوگیری از تغییر رنگ */
}  
    /* بولد کردن تمام متن‌های داخل ردیف‌های نتیجه جستجو */
#search-results div {
    font-weight: bold;
  font-size: 1.1em;
}

/* بولدتر کردن متن‌هایی که از قبل بولد هستند */
#search-results div b, 
#search-results div strong {
    font-weight: 900; /* مقدار بالاتر برای بولدتر کردن */
}
    /* برای درشت‌تر کردن متن‌های هایلایت‌شده */
#search-results div .highlight {
    font-size: 1.13em !important; /* افزایش اندازه فونت برای هایلایت‌ها */
    font-weight: bold; /* بولدتر شدن متن هایلایت شده */
    box-shadow: 0 -0.8px 0 red, 0 0.8px 0 red; /* حاشیه در بالا و پایین هایلایت */
}

/* برای درشت‌تر کردن آخرین عنصر در هر ردیف (آدرس نکته) */
#search-results div span:last-child {
    font-size: 1em; /* افزایش اندازه فونت برای آدرس نکته */
    font-weight: bold;    /* اطمینان از بولد بودن */   
    color: #765678;
}
  #review-modal {
    background-color: #4f1515 !important;
    z-index: 10003 !important;
      
  }
  #textContainer {
    position: relative;
    width: 97.45%; /* عرض عنصر ۸۰٪ از والد */
    margin: 0; /* حذف هرگونه حاشیه اضافی */
}

.startMarker {
    color: red; /* یا هر رنگ دیگر */
    font-weight: bold;
    position: absolute;
    z-index: 999; /* نمایش نشانگر در بالای سایر عناصر */
}

#reviewContent {
    width: 90%;
    height: 80%;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column; /* محتوا به صورت عمودی چیده می‌شود */
    align-items: center; /* مرکز کردن افقی محتوای داخلی */
    justify-content: center; /* مرکز کردن عمودی محتوای داخلی */
    overflow: hidden; /* جلوگیری از خروج محتوا */
}

#textContainer {
  size: bold;
    flex-grow: 1; /* کل فضای باقی‌مانده را پر می‌کند */
    background-color: #f8f8f8;
    padding: 10px;
    border: 1px solid #ddd;
    overflow-y: auto; /* اجازه می‌دهد در صورت لزوم اسکرول شود */
    position: relative;
    white-space: pre-wrap;
    word-wrap: break-word;
}

#controls {
    display: flex;
    justify-content: center; /* مرکز کردن افقی دکمه‌ها */
    align-items: center; /* تراز کردن عمودی */
    gap: 10px; /* فاصله بین دکمه‌ها */
    margin: 0 auto; /* مرکز کردن در صورت نیاز به بلوک */
    width: fit-content; /* عرض متناسب با محتوای داخلی */
}
  .text-highlight {
    background-color: #ffbd9c;
    font-weight: 860;
}

#textContainer {
    background-color: #c9d1d1; /* رنگ پس‌زمینه‌ی فیلد متنی داخل مودال */
    border: 1px solid rgba(150, 150, 150, 1); /* تغییر رنگ حاشیه به یک رنگ طوسی تیره */
}
  .custom-review-button {
    background-color: #b930f0;
    border: 2px solid #ebe71e; /* حاشیه زرد */
    color: white; /* تغییر رنگ متن به سفید */
}

.custom-review-button:hover {
    background-color: #9f29d4;
    border-color: #ebe71e; /* حفظ حاشیه زرد در حالت hover */
    color: white; /* حفظ رنگ متن سفید در حالت hover */
}

.custom-review-button:active {
    background-color: #8525b5;
    border-color: #ebe71e; /* حفظ حاشیه زرد در حالت active */
    color: white; /* حفظ رنگ متن سفید در حالت active */
}
    :root {
    --mainPage-z-index: 1; /* مقدار اولیه */
}

.mainPage {
    width: 100%; /* عرض کل صفحه را بگیرد */
    min-width: 340px; /* حداقل عرض ۳۴۰ پیکسل */   
    position: relative;
    z-index: var(--mainPage-z-index); /* استفاده از متغیر CSS */
    background-color: #fdf3e7; /* یک مقدار تیره‌تر از سفید */
    background-image: url('https://www.transparenttextures.com/patterns/cubes.png'); /* لینک به یک تصویر ساده */
    background-size: 300px 300px; 
        padding-bottom: 1px; /* فضای خالی در پایین صفحه */
}

    #fastToggleButton {
        display: none;
        position: fixed; 
    top: 16.5px; 
    right: 0px; 
    font-size: 15px;
    cursor: pointer;
    z-index: 10005; 
    }
  #mainToggleButton {
        display: none;
        position: fixed; 
    top: 16.5px; 
    right: 0px; 
    font-size: 14px;
    cursor: pointer;
    z-index: 10002; 
    }
    #fastToggleButton, #mainToggleButton {
    pointer-events: auto;
}
    .btn-percent {
        width: 270;
        display: block;
    margin: 0 auto;
    }   
    
    #modal {
    visibility: visible !important; /* نمایش مودال حتی زمانی که صفحه مخفی است */    
z-index: 10000;      
}
  
    </style>
</head>
<body>
    <span id="fastToggleButton" onclick="togglePageOverlay()">🔮</span>
<span id="mainToggleButton" onclick="mainToggle()">🟤</span>

    <div class="mainPage">
<div class="container">
    <h1 class="text-center mb-4">سیستم جامع مدیریت مطالعه</h1>

    <!-- فیلدهای ساعت مطالعه روزانه مطلوب و طول مدت برنامه به روز -->
    <div class="mb-4">
        <label for="daily-study-hours">ساعت مطالعه روزانه :</label>
        <input type="number" id="daily-study-hours" class="form-control d-inline-block" step="0.1" placeholder="۷" min="1" max="18" value="7" oninput="checkMaxValue()">
    </div>

    <div class="mb-4">
        <label for="program-duration"> مدت برنامه (به روز):</label>
        <input type="number" id="program-duration" class="form-control d-inline-block" step="1" placeholder="۷" min="1" value="7">
    </div>

    <!-- فیلد سرچ و دکمه ضریب اهمیت دروس -->
    <div class="position-relative" id="search-container">
        <input type="text" id="search-input" class="form-control search-icon" autocomplete="off" placeholder="🔍 جستجوی پیشرفته...">
        <button class="btn btn-info btn-sm importance-btn" onclick="openImportanceModal()">ضریب اهمیت دروس</button>
        <!-- دکمه ضریب اهمیت دروس -->
    </div> 
    
    <div id="search-results" class="scrollable"></div>
</div>

    <table class="table table-bordered">
        <thead class="table-primary">
            <tr>
                <th></th>
                <th>نام درس</th>
                <th>پیشرفت (ساعت و دقیقه)</th>
                <th>جزئیات</th>
            </tr>
        </thead>
        <tbody id="table-body">
            <!-- Rows will be added dynamically -->
        </tbody>
    </table>

    <!-- دکمه‌های ذخیره -->
    <div class="button-container">
        <button class="btn memory-btn" onclick="copyData(1)">ذخیره حافظه ۱</button>
        <button class="btn memory-btn" onclick="copyData(2)">ذخیره حافظه ۲</button>
        <button class="btn memory-btn" onclick="copyData(3)">ذخیره حافظه ۳</button>
    </div>

    <!-- دکمه‌های بازیابی -->
    <div class="text-center">
    <button class="btn btn-secondary w-50 mb-2" onclick="pasteData(1)">بازیابی حافظه ۱</button>
    <button class="btn btn-secondary w-50 mb-2" onclick="pasteData(2)">بازیابی حافظه ۲</button>
    <button class="btn btn-secondary w-50 mb-2" onclick="pasteData(3)">بازیابی حافظه ۳</button>
       <!-- دکمه‌های بازیابی -->
    <!-- دکمه Database -->
    <button id="database-btn" class="btn btn-secondary mb-2 btn-database" onclick="toggleDatabaseButtons()">Database</button>
    
    <!-- دکمه‌های Backup و Restore در کنار هم -->
    <div id="backup-restore-buttons" style="display: none;">
        <button id="backup-btn" class="btn btn-primary mb-2" onclick="backupData()">Backup</button>   
<button id="restor-btn" class="btn btn-warning mb-2">Restore</button>
        <!-- دکمه‌های جدید زیر دکمه Restore -->
<div id="restore-options" style="display: none; flex-direction: column; gap: 10px;">      
        <input type="file" id="fileInput" style="display: none;" accept=".json" onchange="restoreData(event)">
<button id="restore-btn" class="btn btn-warning replace-button" onclick="document.getElementById('fileInput').click()">Replace Everything</button>
  <input type="file" id="fileInputImportNotes" style="display: none;" accept=".json">
  <button id="import-notes-btn" class="btn btn-warning replace-button">Just Import Notes</button>
</div>
    </div>

    <!-- دکمه Close زیر دکمه‌های Backup و Restore -->
    <button id="close-btn" class="btn btn-danger" style="display: none;" onclick="closeDatabaseButtons()">×</button>
</div>
        <div style="height: 20px;"></div> 
    

    <button class="btn btn-success mb-4 btn-percent" onclick="calculateProgress()">محاسبه درصدها</button>

    <div id="charts-container" class="chart-container">
        <!-- Individual charts will be added here -->
    </div>

<!-- Modal for Importance Coefficients -->
<div class="importance-modal" id="importance-modal" style="display:none; position:fixed; top:50%; left:55%; transform:translate(-50%, -50%); background-color:#ffffff; padding:20px; border-radius:10px; box-shadow:0 0 10px rgba(0,0,0,0.5); z-index:10000; width:300px;">
    <div class="modal-header">ضریب اهمیت دروس</div>
    <div class="scrollable-content" id="importance-fields"></div> <!-- اینجا فیلدها پویا اضافه خواهند شد -->

    <!-- Buttons for actions (in horizontal layout) -->
    <div class="modal-footer d-flex justify-content-between" style="display: flex; gap: 10px;">
        <button class="btn btn-success flex-fill" style="width: 33%;" onclick="saveImportance()">ثبت</button>
        <button class="btn btn-warning flex-fill" style="width: 33%;" onclick="resetToDefault()">بازگشت به پیشفرض</button>
        <button class="btn btn-secondary flex-fill" style="width: 33%;" onclick="closeImportanceModal()">بستن</button>
    </div>
</div></div>
    <!-- Reminder Modal -->
    <div class="reminder-modal" id="reminder-modal">
        <div class="modal-header">Set Reminder</div>
        <textarea id="reminder-text" class="form-control" rows="5" placeholder="Enter reminder text..."></textarea>
        <div class="modal-footer">
            <button class="btn btn-primary" onclick="saveReminder(currentCourse)">Save</button>
            <button class="btn btn-secondary" onclick="closeReminderModal()">Close</button>
        </div>
    </div>

    <!-- Reminder Alert Modal -->
    <div class="reminder-alert-modal" id="reminder-alert-modal">
        <div class="modal-header">یادآور</div>
        <div id="reminder-alert-text" class="mb-3"></div>
        <div class="modal-footer">
            <button class="btn btn-primary" onclick="acknowledgeReminder()">متوجه شدم</button>
            <button class="btn btn-secondary" onclick="closeReminderAlert()">فعلا چشمک بزن</button>
        </div>
    </div>

    <!-- Notes Modal -->
    <div class="notes-modal" id="notes-modal">
        <div class="modal-header">Notes</div>
        <div class="modal-footer">
            <button class="btn btn-primary" onclick="showTranslations(currentCourse)">Translations</button>
            <button class="btn btn-primary" onclick="showImportantNotes(currentCourse)">Important Notes</button>
            <button class="btn btn-secondary" onclick="closeNotesModal()">بستن</button>
        </div>
    </div>
  <!-- لایه پوششی (Overlay) -->
<div class="modal-overlay" id="modal-overlay">عنوان درس</div>

    <!-- Translations Modal -->
    <div class="translation-modal" id="translation-modal">
        <div class="modal-header">Translations</div>
        <div class="scrollable-content" id="translation-fields"></div>
        <div class="modal-footer">
            <button class="btn btn-success" onclick="addTranslationField()">افزودن</button>
            <button class="btn btn-danger" onclick="deleteRows()">حذف</button> <!-- دکمه حذف -->
            <button class="btn btn-primary" onclick="saveTranslations(currentCourse)">ذخیره</button>
            <button class="btn btn-secondary" onclick="closeTranslationModal()">بستن</button>
        </div>
    </div>

    <!-- Important Notes Modal -->
<div class="important-notes-modal" id="important-notes-modal">
    <div class="modal-header">Important Notes</div>
    <div class="scrollable-content" id="notes-container"></div>
    <div class="modal-footer d-flex justify-content-start">
    <button class="btn btn-primary me-2" onclick="viewAllNotes()">مشاهده همه</button>
    <button class="btn btn-info" onclick="addNote()">افزودن نکته</button>
    <button class="btn btn-success" onclick="saveNotes(currentCourse)">ذخیره</button>
    <button class="btn btn-secondary" onclick="closeImportantNotesModal()">بستن</button>
        <!-- دکمه حذف بازه در پنجره B -->

    <button class="btn btn-secondary" onclick="deleteNotesRange()">حذف بازه</button>
        <!-- دکمه برای تغییر از A به B -->
<div class="text-center mt-3">
    <button id="toggle-section-btn" class="btn btn-danger rounded-circle move-left" onclick="toggleSection()">A</button>
    <!-- این بخش فقط برای بخش B فعال می‌شود -->
<div id="section-b-area" style="display: none;" class="mt-4">
    <h4>ورود متن در بخش B</h4>
<textarea id="text-input-b" class="form-control" rows="5" placeholder="متن خود را با $$ شروع و با %% خاتمه دهید..."></textarea>
<button class="btn btn-success mt-2" onclick="processTextB()">ثبت</button>
  <button class="btn custom-review-button mt-2" onclick="openReviewModal()">روخوانی</button>
    <!-- دکمه انتخاب فایل -->
   <!-- دکمه انتخاب فایل -->
    <div id="file-buttons">
        <input type="file" id="text-file-input" accept=".txt" style="display: none;" onchange="handleFileSelect(event)">
        <button id="select-file-btn" class="btn btn-primary mt-2" onclick="document.getElementById('text-file-input').click()">انتخاب فایل</button>
    </div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer-text">
    <span style="color: #8e9091;">Formulated & Generated by: Dr. A. Jamalizadeh</span>
</div>
<div id="modal" style="display:none; position: fixed; top: 50%; left: 55%; transform: translate(-50%, -50%); background-color: white; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-radius: 8px; width: 80%; max-width: 600px;">
    <div class="modal-content">
        <p id="modal-text" style="margin-bottom: 20px; text-align: center;">متن نمایش داده شده</p>
        <button onclick="acknowledge()" style="background-color: #4CAF50; color: white; padding: 10px 10px; border: none; border-radius: 15px; cursor: pointer;">متوجه شدم</button>
    </div>
</div>
<!-- Modal برای روخوانی -->
<div id="review-modal" style="display:none; position:fixed; top:0; left:4.6; width:109%; height:100%; z-index:10000; justify-content:center; align-items:center;">  
  <div id="reviewContent" style="background-color:#4f1515; padding:20px; border-radius:10px; box-shadow:0 0 10px rgba(0,0,0,0.5); width:100%; height:100%; max-width:800px; display:flex; flex-direction:column; position:relative;">
    
    <!-- دکمه دایره‌ای کوچک برای تغییر رنگ متن -->
    <button id="colorToggleButton" style="position: absolute; top: 18.9px; left: 31px; width: 16.5px; height: 16.5px; border-radius: 50%; background-color: #ccc; border: none; cursor: pointer;">
  <span style="position: relative; display: inline-block; transform: translate(-50%, -50%); left: 91%; top: 58%; font-size: 11px;" onclick="toggleTextColor()">T</span>
</button>
      <div style="position: relative;">
  <button id="dragModal" style="position: absolute; top: -10px; left: 50%; transform: translateX(-50%); width: 15px; height: 15px; border-radius: 50%; background-color: #ccc; border: none; cursor: pointer; display: flex; justify-content: center; align-items: center;">
    <span style="font-size: 19px; position: relative; top: -3px;">↔</span>
  </button>
</div>
 
   <h3 style="text-align: center; color: #879599;">text</h3>

    <!-- فیلد محتوا -->
    <div id="textContainer" onpaste="handlePaste(event)" oninput="closeKeyboardOnInput(this)" contenteditable="true" style="border: 1px solid #ccc; padding: 10px; flex-grow:1; overflow-y: auto; color: black; font-weight: 860; font-size: 1.17em;">
        <!-- متن اینجا پیست می‌شود -->
    </div>

    <!-- دکمه‌های کنترل در پایین پنجره -->
    <div id="controls" style="margin-top: 10px; display: flex; gap: 16px; margin-left: 20px;">
    <button class="btn btn-primary" style="background-color: #05695b; border-color: #05695b; color: white;" onclick="applyHighlightedText()">Apply</button>
    <button class="btn btn-secondary" onclick="undoSelection()">Undo</button>
    <button class="btn btn-secondary" onclick="resetTextContainer()">Reset</button>
    <button class="btn btn-danger" style="background-color: #7a0505; border-color: #7a0505; color: white;" onclick="closeReviewModal()">Exit</button>
</div>

<!-- Modal برای ویرایش متن هایلایت‌شده -->
<div id="edit-modal" style="display:none; position:fixed; top:50%; left:55%; transform:translate(-50%, -50%); background-color:#3a4f4f; padding:20px; border-radius:10px; box-shadow:0 0 10px rgba(0,0,0,0.5); z-index:10000; width:90%; max-width:400px;">
    <h3 style="text-align: left; color: #6c7a6c;">edit</h3>
    <textarea id="edit-highlighted-text" style="width:100%; height:100px; background-color:#bac4b9;"></textarea>
    <div style="margin-top:10px; text-align:right;">
        <button class="btn btn-primary" onclick="saveEditedText()">OK</button>
        <button class="btn btn-secondary" onclick="closeEditModal()">Cancel</button>
    </div>
</div>

<script>
const fullURL = window.location.href; // آدرس کامل URL
const baseDomains = ["https://drkingali.github.io/", "https://dastyari.github.io/"]; // دامنه‌های مرجع
let pageIdentifier = null;

// پیدا کردن دامنه‌ای که fullURL با آن شروع می‌شود
const matchedDomain = baseDomains.find(domain => fullURL.startsWith(domain));

if (matchedDomain) { // اگر دامنه‌ای تطابق داشت
    const path = fullURL.substring(matchedDomain.length).replace(/\/$/, ''); // حذف دامنه و دریافت path
    if (path) {
        pageIdentifier = path.substring(0, Math.min(7, path.length)); // تولید شناسه (حداکثر 7 کاراکتر اول مسیر)
    } else {
        pageIdentifier = "11111"; // مقدار پیش‌فرض در صورت نبود path
    }
} else {
    pageIdentifier = null;
    document.body.innerHTML = ""; // مخفی کردن صفحه
}
    
    let currentCourse = null;

    // نمایش پنجره یادآور
    function showReminderModal(courseIndex) {
        currentCourse = courseIndex;
        loadReminder(courseIndex);
        document.getElementById('reminder-modal').style.display = 'block';
    }

    function closeReminderModal() {
        document.getElementById('reminder-modal').style.display ='none';
    }

    function saveReminder(courseIndex) {
        const reminderText = document.getElementById('reminder-text').value;
        if (reminderText.trim() === "") {
            alert("لطفاً یک یادآور وارد کنید!");
            return;
        }

        localStorage.setItem(`reminder-${courseIndex}`, reminderText);
        alert("یادآور ذخیره شد!");

        // اضافه کردن علامت چشمک‌زن
        addBlinkingIcon(courseIndex);

        document.getElementById('reminder-modal').style.display = 'none';
    }

    function loadReminder(courseIndex) {
        const savedReminder = localStorage.getItem(`reminder-${courseIndex}`);
        document.getElementById('reminder-text').value = savedReminder || "";
    }
      
      // تعریف فلگ گلوبال
let alertBeginner = false;

// تعریف متغیر گلوبال و مقداردهی بر اساس وضعیت فلگ
let unregisteredCode = alertBeginner ? 115 : 542798542253078835;

// شرط برای به‌روزرسانی مقدار unregisteredCode
const interval = setInterval(() => {
    if (!alertBeginner) {
        unregisteredCode = 542798542253078835;
    } else {
        unregisteredCode = 115;
        clearInterval(interval);
    }
}, 300); // بررسی هر 100 میلی‌ثانیه

// متوقف کردن پایش پس از 7 ثانیه
setTimeout(() => {
    clearInterval(interval);
},40100); // 7000 میلی‌ثانیه = 7 ثانیه
    // اضافه کردن علامت چشمک‌زن به ردیف درس
    function addBlinkingIcon(courseIndex) {
    const row = document.querySelector(`#row-${courseIndex}`);
    let blinkingIcon = document.querySelector(`#blinking-icon-${courseIndex}`);

    if (!blinkingIcon) {
        blinkingIcon = document.createElement('span');
        blinkingIcon.classList.add('blinking-icon');
        blinkingIcon.id = `blinking-icon-${courseIndex}`;
        blinkingIcon.textContent = '🔔';

        // اضافه کردن استایل برای پایین آوردن زنگوله
        blinkingIcon.style.position = 'relative'; // تنظیم موقعیت به relative
        blinkingIcon.style.top = '10px'; // تنظیم فاصله از بالا (مقدار را تغییر دهید)

        blinkingIcon.onclick = function () {
            showReminderAlert(courseIndex);
        };
        row.querySelector('.details-cell').appendChild(blinkingIcon);
    }
}

    // نمایش پنجره یادآوری و متن ذخیره شده
    function showReminderAlert(courseIndex) {
    currentCourse = courseIndex; // تنظیم currentCourse به درستی
    const savedReminder = localStorage.getItem(`reminder-${courseIndex}`);
    if (savedReminder) {
        document.getElementById('reminder-alert-text').textContent = savedReminder;
        document.getElementById('reminder-alert-modal').style.display = 'block';
    }
}

    function closeReminderAlert() {
        document.getElementById('reminder-alert-modal').style.display = 'none';
    }

    function acknowledgeReminder() {
    // حذف یادآور از localStorage
    if (currentCourse !== null) {
        localStorage.removeItem(`reminder-${currentCourse}`);
    }

    // حذف علامت چشمک‌زن از کنار درس
    const blinkingIcon = document.getElementById(`blinking-icon-${currentCourse}`);
    if (blinkingIcon) {
        blinkingIcon.remove();  // حذف آیکون از DOM
    }

    // بستن پنجره یادآور
    closeReminderAlert();
}

    // نمایش پنجره ترجمه
    function showTranslations(courseIndex) {
    currentCourse = courseIndex;
    loadTranslations(courseIndex);
    document.getElementById('translation-modal').style.display = 'block';
    showOverlay(courses[courseIndex].name); // نمایش نام دقیق درس
}

    function closeTranslationModal() {
    document.getElementById('translation-modal').style.display = 'none';
    hideOverlay(); // مخفی کردن لایه زیرین هنگام بستن پنجره
}

   function addTranslationField() {
    const translationFields = document.getElementById('translation-fields');
    
    // شمارش تعداد ردیف‌های موجود برای تعیین شماره ردیف جدید
    const rowCount = translationFields.children.length + 1;

    const newRow = document.createElement('div');
    newRow.className = 'd-flex mb-2 align-items-center';

    newRow.innerHTML = `
        <input type="text" class="form-control translation-input" placeholder="ترجمه" style="width: 140px;">
        <input type="text" class="form-control translation-input" placeholder="word" style="width: 140px; margin-left: 10px;">
        <span style="margin-left: auto; padding-left: 10px;">${rowCount}</span> <!-- نمایش شماره ردیف -->
    `;
    
    translationFields.appendChild(newRow);
    
    // اسکرول به پایین‌ترین موقعیت بعد از افزودن فیلد جدید
    translationFields.scrollTop = translationFields.scrollHeight;
}

    function saveTranslations(courseIndex, showAlert = true, preserveScrollPosition = false) {
    const translationFields = document.getElementById('translation-fields');
    const rows = translationFields.querySelectorAll('.d-flex');
    const translationsArray = [];

    // اگر preserveScrollPosition فعال باشد، موقعیت اسکرول قبلی را ذخیره می‌کنیم
    let previousScrollTop = preserveScrollPosition ? translationFields.scrollTop : null;

    rows.forEach(row => {
        const translation = row.children[0].value;
        const word = row.children[1].value;
        translationsArray.push({ translation, word });
    });

    localStorage.setItem(`translations-${courseIndex}`, JSON.stringify(translationsArray));

    // ذخیره درصد اسکرول فقط زمانی که preserveScrollPosition برابر false است
    if (!preserveScrollPosition) {
        const maxScroll = translationFields.scrollHeight - translationFields.clientHeight;
        const scrollPercentage = (translationFields.scrollTop / maxScroll) * 100;
        localStorage.setItem(`translation-scroll-percent-${courseIndex}`, scrollPercentage);
    }

    // نمایش پیام هشدار فقط اگر showAlert true باشد
    if (showAlert) {
        alert("ترجمه‌ها ذخیره شدند.");
    }

    // اگر preserveScrollPosition فعال باشد، موقعیت اسکرول را به وضعیت قبلی برمی‌گردانیم
    if (preserveScrollPosition && previousScrollTop !== null) {
        translationFields.scrollTop = previousScrollTop;
    }
    
}

    function loadTranslations(courseIndex) {
    const translationFields = document.getElementById('translation-fields');
    translationFields.innerHTML = ''; // پاک کردن محتوای قبلی

    const savedTranslations = localStorage.getItem(`translations-${courseIndex}`);
    if (savedTranslations) {
        const translationsArray = JSON.parse(savedTranslations);
        translationsArray.forEach((translationObj, index) => {
            const newRow = document.createElement('div');
            newRow.className = 'd-flex mb-2 align-items-center';
            newRow.innerHTML = `
                <input type="text" class="form-control translation-input" value="${translationObj.translation}" placeholder="ترجمه" style="width: 140px;">
                <input type="text" class="form-control translation-input" value="${translationObj.word}" placeholder="word" style="width: 140px; margin-left: 10px;">
                <span style="margin-left: auto; padding-left: 10px;">${index + 1}</span>
            `;
            translationFields.appendChild(newRow);
        });
    }

    // بازیابی درصد اسکرول و اعمال آن با تأخیر کوتاه
    const savedScrollPercent = localStorage.getItem(`translation-scroll-percent-${courseIndex}`);
    if (savedScrollPercent) {
        setTimeout(() => {
            const maxScroll = translationFields.scrollHeight - translationFields.clientHeight;
            translationFields.scrollTop = (maxScroll * savedScrollPercent) / 100;
        }, 100);  // تأخیر 100 میلی‌ثانیه برای اطمینان از بارگذاری کامل
    }
}

    // نمایش پنجره نکات مهم
    function showImportantNotes(courseIndex) {
    currentCourse = courseIndex;
    loadNotes(courseIndex);
    document.getElementById('important-notes-modal').style.display = 'block';
    showOverlay(courses[courseIndex].name); // نمایش نام دقیق درس
      document.getElementById('mainToggleButton').style.display = 'block';
}

    function closeImportantNotesModal() {
    document.getElementById('important-notes-modal').style.display = 'none';
    hideOverlay(); // مخفی کردن لایه زیرین هنگام بستن پنجره
      document.getElementById('mainToggleButton').style.display = 'none';
        resetTextContainer();
}

    function addNote() {
    const notesContainer = document.getElementById('notes-container');
    const noteIndex = notesContainer.children.length + 1;
    const noteRow = document.createElement('div');
    noteRow.className = 'mb-2';
    noteRow.innerHTML = `
        <span>${noteIndex}. <input type="text" class="form-control d-inline-block" placeholder="نکته را وارد کنید" style="width: 80%;"> 
        <button class="btn btn-danger btn-sm" onclick="deleteNote(this)">حذف</button>
        <button class="btn btn-primary btn-sm" onclick="viewNote(this)">مشاهده</button></span>
    `;
    notesContainer.appendChild(noteRow);
    document.getElementById('toggle-section-btn').classList.add('btn-light-purple');
    
    // اسکرول به پایین‌ترین موقعیت بعد از افزودن نکته جدید
    notesContainer.scrollTop = notesContainer.scrollHeight;
}

    function deleteNote(button) {
        const noteRow = button.parentElement;
        noteRow.remove();
        renumberNotes();
    }

    function viewNote(button) {
    // به فیلد input مربوطه دسترسی پیدا می‌کنیم که در همان ردیف است
    const noteText = button.parentElement.querySelector('input').value; 

    if (noteText.trim()) {
        alert(noteText); // نمایش متن واقعی نکته
    } else {
        alert("هیچ متنی وارد نشده است."); // در صورتی که متنی وارد نشده باشد
    }
}

    function renumberNotes() {
        const notesContainer = document.getElementById('notes-container');
        const notes = notesContainer.querySelectorAll('span');
        notes.forEach((note, index) => {
            note.firstChild.textContent = `${index + 1}. `;
        });
    }

    // اصلاح تابع saveNotes برای ذخیره نکات بخش A یا B
function saveNotes(courseIndex) {
    const notesContainer = document.getElementById('notes-container');
    const notes = notesContainer.querySelectorAll('input');
    const notesArray = [];
    let translationsMoved = false; // برای بررسی اینکه آیا ردیفی به translations منتقل شده است

    notes.forEach(note => {
        let noteText = note.value.trim();

        // بررسی وجود علامت "="
        if (noteText.includes('=')) {
            // جدا کردن دو طرف "=" و حذف فاصله‌ها
            const [left, right] = noteText.split('=').map(part => normalizeTextForNotes(part.trim()));

            // بررسی شرایط انتقال (یک طرف انگلیسی و طرف دیگر فارسی)
            if ((isEnglishText(left) && isPersianText(right)) || (isEnglishText(right) && isPersianText(left))) {
                // ایجاد ردیف جدید در پنجره translations
                addTranslationField(); // تابعی که ردیف جدید در translations اضافه می‌کند

                // تعیین متن به فیلدهای word و ترجمه
                const translationFields = document.getElementById('translation-fields');
                const lastRow = translationFields.lastElementChild; // آخرین ردیف اضافه شده

                // بررسی و پر کردن فیلدهای جدید با متن انگلیسی و فارسی
                if (isEnglishText(left)) {
                    lastRow.querySelector('input[placeholder="word"]').value = left;
                    lastRow.querySelector('input[placeholder="ترجمه"]').value = right;
                } else {
                    lastRow.querySelector('input[placeholder="word"]').value = right;
                    lastRow.querySelector('input[placeholder="ترجمه"]').value = left;
                }

                // ذخیره تغییرات در localStorage برای پنجره translations بدون نمایش alert و با حفظ موقعیت اسکرول
                saveTranslations(courseIndex, false, true); // preserveScrollPosition = true

                // حذف این ردیف از پنجره important notes
                note.closest('div').remove();

                // تنظیم پرچم برای تشخیص اینکه ردیفی منتقل شده است
                translationsMoved = true;
            } else {
                // اگر شرایط برقرار نبود، آن را به لیست نکات ذخیره اضافه کن
                notesArray.push(noteText);
            }
        } else {
            // نکات بدون علامت "=" را به لیست اضافه کن
            notesArray.push(noteText);
        }
    });

    // ذخیره نکات باقی‌مانده برای بخش A، B یا C
    localStorage.setItem(`notes-${currentSection}-${courseIndex}`, JSON.stringify(notesArray));

    // محاسبه و ذخیره درصد اسکرول
    const maxScroll = notesContainer.scrollHeight - notesContainer.clientHeight;
    const scrollPercentage = (notesContainer.scrollTop / maxScroll) * 100;
    localStorage.setItem(`notes-scroll-percent-${currentSection}-${courseIndex}`, scrollPercentage);

    // مدیریت پیام هشدار
    if (translationsMoved) {
        alert("ترجمه‌ها و نکات بخش " + currentSection + " ذخیره شدند.");
    } else {
        alert("نکات بخش " + currentSection + " ذخیره شدند.");
    }

    // جلوگیری از حذف شدن Overlay و حفظ عنوان درس
    showOverlay(courses[courseIndex].name); // نمایش مجدد عنوان درس در overlay
}
    // اصلاح تابع loadNotes برای پشتیبانی از بخش A و B
function loadNotes(courseIndex) {
    const notesContainer = document.getElementById('notes-container');
    notesContainer.innerHTML = ''; // پاک کردن محتوای قبلی

    const savedNotes = localStorage.getItem(`notes-${currentSection}-${courseIndex}`);
    if (savedNotes) {
        const notesArray = JSON.parse(savedNotes);
        notesArray.forEach((noteText, index) => {
            const noteRow = document.createElement('div');
            noteRow.className = 'mb-2';
            noteRow.innerHTML = `
                <span>${index + 1}. <input type="text" class="form-control d-inline-block" value="${noteText}" style="width: 80%;"> 
                <button class="btn btn-danger btn-sm" onclick="deleteNote(this)">حذف</button>
                <button class="btn btn-primary btn-sm" onclick="viewNote(this)">مشاهده</button></span>
            `;
            notesContainer.appendChild(noteRow);
        });
    }

    // بازیابی درصد اسکرول و اعمال آن با تأخیر کوتاه
    const savedScrollPercent = localStorage.getItem(`notes-scroll-percent-${currentSection}-${courseIndex}`);
    if (savedScrollPercent) {
        setTimeout(() => {
            const maxScroll = notesContainer.scrollHeight - notesContainer.clientHeight;
            notesContainer.scrollTop = (maxScroll * savedScrollPercent) / 100;
        }, 100);  // تأخیر 100 میلی‌ثانیه برای اطمینان از بارگذاری کامل
    }
}

    // تنظیمات جدول اصلی
    const courses = [
        { name: 'ارتو', baseCeiling: 570 },
        { name: 'اندو', baseCeiling: 190 },
        { name: 'بیماری‌ها', baseCeiling: 190 },
        { name: 'پریو', baseCeiling: 190 },
        { name: 'کودکان', baseCeiling: 380 },
        { name: 'رادیو', baseCeiling: 380 },
        { name: 'پروتز', baseCeiling: 285 },
        { name: 'جراحی', baseCeiling: 190 },
        { name: 'ترمیمی', baseCeiling: 190 },
        { name: 'آسیب‌شناسی', baseCeiling: 190 },
        { name: 'سلامت', baseCeiling: 95 },
        { name: 'مواد دندانی', baseCeiling: 95 }
    ];

    let startPage = null;
    let endPage = null;

    
        // هنگامی که صفحه بارگذاری می‌شود
window.onload = function() {
    
         // فراخوانی تابع با showAlert = false برای جلوگیری از نمایش alert
        waitForFlagAndCall();
        waitForDataOrHidePage();
    // پس از 1 ثانیه، تابع saveImportance بدون نمایش alert فراخوانی شود   
        const tableBody = document.getElementById('table-body');
        courses.forEach((course, index) => {
            let row = document.createElement('tr');
            row.id = `row-${index}`;
let plusCell = document.createElement('td');
            let plusButton = document.createElement('button');
            plusButton.textContent = '+';
            plusButton.classList.add('btn', 'btn-outline-secondary', 'btn-sm');
            plusButton.onclick = function() {
                document.getElementById(`additional-${index}`).style.display = 'block';
                plusButton.style.display = 'none';
            };
            plusCell.appendChild(plusButton);

            let nameCell = document.createElement('td');
nameCell.innerHTML = `<span class="course-title" style="font-weight: bold;">${course.name}</span>`;
          
          // ایجاد دکمه با نام جدید
let sectionButton = document.createElement('button');
sectionButton.textContent = '✏'; // آیکون دکمه
sectionButton.style.position = 'absolute'; // موقعیت دکمه به صورت absolute
sectionButton.style.right = '45px'; // فاصله از راست (بیشتر برای حرکت به سمت چپ)
sectionButton.style.top = '55%'; // موقعیت در مرکز عمودی سلول
sectionButton.style.transform = 'translateY(-50%) rotate(45deg)'; // تنظیم عمودی و چرخش ۴۵ درجه
sectionButton.style.cursor = 'pointer';
sectionButton.style.border = 'none';
sectionButton.style.background = 'transparent';
sectionButton.style.fontSize = '21px';
// افزودن رویداد کلیک به دکمه
            
sectionButton.addEventListener('click', () => {
    openReviewModal();
    // نمایش یادداشت‌های مهم برای بخش b از currentCourse
    showImportantNotes(index);
    if (currentSection !== 'B') {
toggleSection();
    }
    const timeout = setTimeout(() => {
if (currentSection !== 'B') {
toggleSection();
}
        document.querySelector('.important-notes-modal').scrollTo({ top: document.querySelector('.important-notes-modal').scrollHeight, behavior: 'smooth' });
    }, 60);
    // پیدا کردن عنصر section-b-area مرتبط با بخش b
    
});

// اضافه کردن دکمه به سلول
nameCell.style.position = 'relative'; // سلول برای absolute نیاز به position دارد
nameCell.appendChild(sectionButton);

// ایجاد دکمه
let button = document.createElement('button');
button.textContent = '🔍'; // آیکون دکمه
button.style.position = 'absolute'; // موقعیت دکمه به صورت absolute
button.style.right = '13px'; // فاصله از راست
button.style.top = '57%'; // موقعیت در مرکز عمودی سلول
button.style.transform = 'translateY(-50%)'; // تنظیم عمودی برای وسط‌چین
button.style.cursor = 'pointer';
button.style.border = 'none';
button.style.background = 'transparent';
button.style.fontSize = '18px';

// افزودن رویداد کلیک به دکمه
button.addEventListener('click', () => {
    const inputField = document.getElementById('search-input');
    let inputValue = inputField.value;

    if (specificCourseOnly) {
        // اگر پرچم بالا باشد، الگوی فعلی کورس:: پاک شده و جایگزین می‌شود
        inputValue = inputValue.replace(/^(.+?)::/, ''); // حذف الگوی فعلی
        const newPattern = `${course.name}::`;
        inputField.value = `${newPattern}${inputValue}`; // جایگزینی الگو
    } else {
        // اگر پرچم پایین باشد، الگو قبل از همه متن‌ها قرار می‌گیرد
        const newPattern = `${course.name}::`;
        inputField.value = `${newPattern}${inputValue}`; // افزودن الگو
    }

    // تحریک رویداد input برای به‌روزرسانی فیلد
    const inputEvent = new Event('input', { bubbles: true });
    inputField.dispatchEvent(inputEvent);

    // اسکرول صفحه به بالاترین موقعیتی که انتهای search-results قابل مشاهده باشد
    const searchResults = document.getElementById('search-results');
const searchInput = document.getElementById('search-input'); // دریافت فیلد search-input

if (searchResults && searchInput) {
    setTimeout(() => {
        const rect = searchInput.getBoundingClientRect(); // دریافت مختصات search-input

        // محاسبه موقعیت اسکرول
        const scrollToPosition = window.scrollY + rect.top;

        // حرکت اسکرول به موقعیت محاسبه‌شده
        window.scrollTo({ top: scrollToPosition, behavior: 'smooth' });
    }, 200); // تأخیر 0.2 ثانیه
}

    // نمایش متن چشمک‌زن فقط در شرایط خاص
    const coursePattern = /^[^:]+::$/; // الگوی فقط شامل کورس::
    if (inputValue.trim() === '' || coursePattern.test(inputValue.trim())) {
        const flashMessage = document.createElement('div');
        flashMessage.textContent = 'واژه یا شماره ردیف دلخواه';
        flashMessage.style.position = 'absolute';
        flashMessage.style.top = `${inputField.offsetTop + 185}px`; // موقعیت پایین‌تر
        flashMessage.style.left = `${inputField.offsetLeft - 40}px`; // انتقال کمی به چپ
        flashMessage.style.width = `${inputField.offsetWidth}px`;
        flashMessage.style.textAlign = 'center';
        flashMessage.style.fontSize = '16px';
        flashMessage.style.color = 'gray'; // متن بدون کادر یا پس‌زمینه
        flashMessage.style.zIndex = '10005';
        flashMessage.style.pointerEvents = 'none';
        document.body.appendChild(flashMessage);

        let flashCount = 0;
        const flashInterval = setInterval(() => {
            flashMessage.style.visibility = flashMessage.style.visibility === 'hidden' ? 'visible' : 'hidden';
            flashCount++;
            if (flashCount >= 8) { // چشمک‌زدن 4 بار (8 تغییر)
                clearInterval(flashInterval);
                flashMessage.remove();
            }
        }, 500); // تغییر سرعت چشمک‌زدن به آهسته‌تر
    }
});

// اضافه کردن دکمه به سلول
nameCell.style.position = 'relative'; // سلول برای absolute نیاز به position دارد
nameCell.appendChild(button);
            
            let progressCell = document.createElement('td');
            let hoursInput = document.createElement('input');
            hoursInput.type = 'number';
            hoursInput.placeholder = 'ساعت';
            hoursInput.min = 0;
            hoursInput.classList.add('form-control', 'd-inline-block', 'mb-2');
            hoursInput.id = `hours-${index}`;

            let minutesInput = document.createElement('input');
            minutesInput.type = 'number';
            minutesInput.placeholder = 'دقیقه';
            minutesInput.min = 0;
            minutesInput.max = 59;
            minutesInput.classList.add('form-control', 'd-inline-block', 'mb-2');
            minutesInput.id = `minutes-${index}`;

            progressCell.appendChild(hoursInput);
            progressCell.appendChild(document.createTextNode(' : '));
            progressCell.appendChild(minutesInput);

            let detailsCell = document.createElement('td');
            detailsCell.classList.add('details-cell'); // کلاس اضافه برای افزودن آیکون چشمک زن
            let detailsButton = document.createElement('button');
            detailsButton.textContent = 'جزئیات';
            detailsButton.classList.add('btn', 'btn-details');  // افزودن کلاس جدید
            detailsButton.onclick = function() {
                openDetails(index);
            };
            detailsCell.appendChild(detailsButton);

            row.appendChild(plusCell);
            row.appendChild(nameCell);
            row.appendChild(progressCell);
            row.appendChild(detailsCell);
            tableBody.appendChild(row);

            // فیلدهای اضافی که با دکمه "+" نمایش داده می‌شود
            let additionalFields = document.createElement('div');
            additionalFields.id = `additional-${index}`;
            additionalFields.classList.add('additional-fields', 'mt-2');

            let additionalHoursInput = document.createElement('input');
            additionalHoursInput.type = 'number';
            additionalHoursInput.placeholder = 'ساعت اضافه';
            additionalHoursInput.min = 0;
            additionalHoursInput.classList.add('form-control', 'd-inline-block', 'mb-2');
            additionalHoursInput.id = `additional-hours-${index}`;

            let additionalMinutesInput = document.createElement('input');
            additionalMinutesInput.type = 'number';
            additionalMinutesInput.placeholder = 'دقیقه اضافه';
            additionalMinutesInput.min = 0;
            additionalMinutesInput.max = 59;
            additionalMinutesInput.classList.add('form-control', 'd-inline-block', 'mb-2');
            additionalMinutesInput.id = `additional-minutes-${index}`;

            let submitButton = document.createElement('button');
            submitButton.textContent = 'ثبت';
            submitButton.classList.add('btn', 'btn-success', 'btn-sm');
            submitButton.onclick = function() {
                const currentHours = parseInt(hoursInput.value) || 0;
                const currentMinutes = parseInt(minutesInput.value) || 0;
                const additionalHours = parseInt(additionalHoursInput.value) || 0;
                const additionalMinutes = parseInt(additionalMinutesInput.value) || 0;

                const totalMinutes = currentMinutes + additionalMinutes;
                const newHours = currentHours + additionalHours + Math.floor(totalMinutes / 60);
                const newMinutes = totalMinutes % 60;

                hoursInput.value = newHours;
                minutesInput.value = newMinutes;

                additionalFields.style.display = 'none';
                plusButton.style.display = 'block';

                additionalHoursInput.value = '';
                additionalMinutesInput.value = '';
            };

            additionalFields.appendChild(additionalHoursInput);
            additionalFields.appendChild(document.createTextNode(' : '));
            additionalFields.appendChild(additionalMinutesInput);
            additionalFields.appendChild(submitButton);

            row.appendChild(additionalFields);
        });

        // بررسی وجود یادآوری برای درس‌ها
        checkRemindersOnPageLoad();
    };

    function checkRemindersOnPageLoad() {
        courses.forEach((course, index) => {
            const savedReminder = localStorage.getItem(`reminder-${index}`);
            if (savedReminder) {
                addBlinkingIcon(index);
            }
        });
    }

    // نمایش پنجره جزئیات هر درس
    function openDetails(courseIndex) {     
if (isReviewModalOpen) return; 
if (isImportantNotesOpen) return;
        const detailsContainer = document.createElement('div');
        detailsContainer.classList.add('details-container');

        const scrollContainer = document.createElement('div');
        scrollContainer.classList.add('scroll-container');

        for (let i = 1; i <= 1500; i++) {
            const pageButton = document.createElement('button');
            pageButton.textContent = i;
            pageButton.classList.add('page-button', 'btn', 'btn-outline-secondary');
            

            // بازیابی رنگ صفحه‌ها در صورت ذخیره شدن
            const courseData = JSON.parse(localStorage.getItem(`courseData${courseIndex}`)) || {};
            if (courseData.pages) {
                const pageData = courseData.pages.find(p => p.page == i);
                if (pageData) {
                    if (pageData.count == 1) {
                        pageButton.classList.add('green');
                    } else if (pageData.count == 2) {
                        pageButton.classList.add('orange');
                    } else if (pageData.count >= 3) {
                        pageButton.classList.add('red');
                    }
                }
            }

            pageButton.addEventListener('click', function() {
                selectPageRange(courseIndex, i);
            });

            scrollContainer.appendChild(pageButton);
        }

        detailsContainer.appendChild(scrollContainer);

        // دکمه‌های ذخیره بازه، حذف بازه و خروج
        const saveButton = document.createElement('button');
        saveButton.textContent = 'ذخیره بازه';
        saveButton.classList.add('btn', 'btn-primary');
        saveButton.addEventListener('click', function() {
            savePageRange(courseIndex);
        });

        const deleteButton = document.createElement('button');
        deleteButton.textContent = 'حذف بازه';
        deleteButton.classList.add('btn', 'btn-danger');
        deleteButton.addEventListener('click', function() {
            deletePageRange(courseIndex);
        });

        const summaryButton = document.createElement('button');
        summaryButton.textContent = 'خلاصه';
        summaryButton.classList.add('btn', 'btn-info');
        summaryButton.addEventListener('click', function() {
            showSummary(courseIndex);
        });

        const exitButton = document.createElement('button');
        exitButton.textContent = 'خروج';
        exitButton.classList.add('btn', 'btn-secondary');
        exitButton.addEventListener('click', function() {
            exitDetails();
        });

        detailsContainer.appendChild(saveButton);
        detailsContainer.appendChild(deleteButton);
        detailsContainer.appendChild(summaryButton);
        detailsContainer.appendChild(exitButton);

        // دکمه ترجمه در پنجره جزئیات اضافه می‌شود
        const noteContainer = document.createElement('div');
        noteContainer.classList.add('note-container');
        noteContainer.innerHTML = `
            <button class="btn btn-note" id="note-btn-${courseIndex}" onclick="showNoteButtons(${courseIndex})">یادداشت</button>
            <div class="note-btns" id="note-buttons-${courseIndex}" style="display:none;">
                <button class="btn btn-secondary btn-with-image" onclick="showTranslations(${courseIndex})">Translations</button>
                <button class="btn btn-secondary btn-with-image" onclick="showReminderModal(${courseIndex})">Set Reminder</button>
                <button class="btn btn-secondary btn-with-image" onclick="showImportantNotes(${courseIndex})">Important Notes</button>
                <button class="btn btn-danger" onclick="hideNoteButtons(${courseIndex})">×</button>
            </div>
        `;
        detailsContainer.appendChild(noteContainer);

        document.body.appendChild(detailsContainer);
        loadPageRange(courseIndex);
            // بارگذاری موقعیت اسکرول قبلی
    const savedScrollPosition = localStorage.getItem(`scrollPosition-${courseIndex}`);
    if (savedScrollPosition) {
        scrollContainer.scrollTop = savedScrollPosition;
    }

    loadPageRange(courseIndex); // بارگذاری وضعیت بازه‌ها
}

    function showNoteButtons(courseIndex) {
        document.getElementById(`note-btn-${courseIndex}`).style.display = 'none';
        document.getElementById(`note-buttons-${courseIndex}`).style.display = 'block';
    }

    function hideNoteButtons(courseIndex) {
        document.getElementById(`note-btn-${courseIndex}`).style.display = 'block';
        document.getElementById(`note-buttons-${courseIndex}`).style.display = 'none';
    }

    // تابع انتخاب بازه
    function selectPageRange(courseIndex, page) {
        const scrollContainer = document.querySelector('.scroll-container');
        const pageButtons = scrollContainer.querySelectorAll('.page-button');

        if (startPage === null) {
            startPage = page;
        } else if (endPage === null) {
            endPage = page;
            colorPageRange(courseIndex);
            startPage = null;
            endPage = null;
        }
    }

    // تابع رنگ‌آمیزی بازه
    function colorPageRange(courseIndex) {
        const scrollContainer = document.querySelector('.scroll-container');
        const pageButtons = scrollContainer.querySelectorAll('.page-button');

        for (let i = startPage - 1; i <= endPage - 1; i++) {
            const pageButton = pageButtons[i];
            let count = parseInt(pageButton.dataset.count)|| 0;
            count++;
            pageButton.dataset.count = count;

            if (count === 1) {
                pageButton.classList.remove('orange', 'red');
                pageButton.classList.add('green');
            } else if (count === 2) {
                pageButton.classList.remove('green', 'red');
                pageButton.classList.add('orange');
            } else if (count >= 3) {
                pageButton.classList.remove('green', 'orange');
                pageButton.classList.add('red');
            }
        }
    }

    // تابع ذخیره بازه
    function savePageRange(courseIndex) {
        const courseData = JSON.parse(localStorage.getItem(`courseData${courseIndex}`)) || {};
        const scrollContainer = document.querySelector('.scroll-container');
        const pageButtons = scrollContainer.querySelectorAll('.page-button');
        const pages = Array.from(pageButtons).map(button => ({
            page: button.textContent,
            count: button.dataset.count || 0
        }));

        courseData.pages = pages;
        localStorage.setItem(`courseData${courseIndex}`, JSON.stringify(courseData));
        alert('بازه‌ها ذخیره شدند.');
            // ذخیره موقعیت اسکرول
    const scrollPosition = scrollContainer.scrollTop;
    localStorage.setItem(`scrollPosition-${courseIndex}`, scrollPosition);

    
    }

    // تابع بارگذاری بازه
    function loadPageRange(courseIndex) {
        const courseData = JSON.parse(localStorage.getItem(`courseData${courseIndex}`));

        if (courseData && courseData.pages) {
            const scrollContainer = document.querySelector('.scroll-container');
            const pageButtons = scrollContainer.querySelectorAll('.page-button');

            courseData.pages.forEach((data, index) => {
                const button = pageButtons[index];
                button.dataset.count = data.count;

                if (data.count === 1) {
                    button.classList.add('green');
                } else if (data.count === 2) {
                    button.classList.add('orange');
                } else if (data.count >= 3) {
                    button.classList.add('red');
                }
            });
        }
    }

    // تابع حذف بازه
    function deletePageRange(courseIndex) {
        const startPage = prompt('صفحه شروع را وارد کنید:');
        const endPage = prompt('صفحه پایان را وارد کنید:');

        if (startPage && endPage) {
            const scrollContainer = document.querySelector('.scroll-container');
            const pageButtons = scrollContainer.querySelectorAll('.page-button');

            for (let i = startPage - 1; i <= endPage - 1; i++) {
                const pageButton = pageButtons[i];
                pageButton.classList.remove('green', 'orange', 'red');
                pageButton.dataset.count = 0;
            }
            alert(`بازه صفحات ${startPage} تا ${endPage} حذف شد.`);
        }
    }

    // تابع خروج از صفحه جزئیات
    function exitDetails() {
        const detailsContainer = document.querySelector('.details-container');
        if (detailsContainer) {
            detailsContainer.remove();
        }
    }

    // تابع نمایش summary
    function showSummary(courseIndex) {
        const courseData = JSON.parse(localStorage.getItem(`courseData${courseIndex}`)) || {};

        const oneTime = [];
        const twoTimes = [];
        const threeTimes = [];

        courseData.pages.forEach(page => {
            if (page.count == 1) {
                oneTime.push(parseInt(page.page));
            } else if (page.count == 2) {
                twoTimes.push(parseInt(page.page));
            } else if (page.count >= 3) {
                threeTimes.push(parseInt(page.page));
            }
        });

        const oneTimeRanges = convertToRange(oneTime);
        const twoTimeRanges = convertToRange(twoTimes);
        const threeTimeRanges = convertToRange(threeTimes);

        alert(`یک بار خوانده شده: ${oneTimeRanges}\nدو بار خوانده شده: ${twoTimeRanges}\nسه بار یا بیشتر: ${threeTimeRanges}`);
    }

    // تابع تبدیل لیست اعداد به بازه
    function convertToRange(arr) {
        if (arr.length === 0) return '';

        let ranges = [];
        let start = arr[0];
        let end = arr[0];

        for (let i = 1; i < arr.length; i++) {
            if (arr[i] === end + 1) {
                end = arr[i];
            } else {
                if (start === end) {
                    ranges.push(`${start}`);
                } else {
                    ranges.push(`${start} تا ${end}`);
                }
                start = arr[i];
                end = arr[i];
            }
        }

        if (start === end) {
            ranges.push(`${start}`);
        } else {
            ranges.push(`${start} تا ${end}`);
        }

        return ranges.join(', ');
    }

    // تابع بازیابی تمامی خانه‌های سبز و نارنجی و قرمز
    function restoreAllPages() {
        courses.forEach((course, index) => {
            loadPageRange(index);
        });
        alert('صفحات سبز، نارنجی و قرمز با موفقیت بازیابی شدند.');
    }

    // ذخیره و بازیابی اطلاعات ساعت و دقیقه هر درس
    function copyData(memoryNumber) {
        const data = {};

        data.dailyStudyHours = document.getElementById('daily-study-hours').value || 7;
        data.programDuration = document.getElementById('program-duration').value || 7;

        data.courses = [];
        courses.forEach((course, index) => {
            const hours = document.getElementById(`hours-${index}`).value || 0;
            const minutes = document.getElementById(`minutes-${index}`).value || 0;
            data.courses.push({ hours, minutes });
        });

        localStorage.setItem(`studyData${memoryNumber}`, JSON.stringify(data));
        alert(`داده‌های زمانی دروس در حافظه ${memoryNumber} ذخیره شدند!`);
    }

    // بازیابی اطلاعات از حافظه محلی
    function pasteData(memoryNumber) {
        const dataString = localStorage.getItem(`studyData${memoryNumber}`);

        if (dataString) {
            const data = JSON.parse(dataString);

            document.getElementById('daily-study-hours').value = data.dailyStudyHours || 7;
            document.getElementById('program-duration').value = data.programDuration || 7;

            if (data.courses.length !== courses.length) {
                alert('فرمت نادرست');
                return;
            }

            data.courses.forEach((courseData, index) => {
                const { hours, minutes } = courseData;
                document.getElementById(`hours-${index}`).value = hours;
                document.getElementById(`minutes-${index}`).value = minutes;
            });

            alert(`داده‌های زمانی دروس از حافظه ${memoryNumber}  بازیابی شدند!`);
        } else {
            alert(`هیچ داده‌ای در حافظه ${memoryNumber} وجود ندارد.`);
        }
    }

    // محاسبه درصد پیشرفت
    function calculateProgress() {
        const chartsContainer = document.getElementById('charts-container');
        chartsContainer.innerHTML = '';

        const dailyStudyHours = parseFloat(document.getElementById('daily-study-hours').value) || 7;
        const programDuration = parseFloat(document.getElementById('program-duration').value) || 7;

        const dailyStudyFactor = dailyStudyHours / 7;
        const programDurationFactor = programDuration / 7;

        const finalFactor = dailyStudyFactor * programDurationFactor;

        let totalMinutesEntered = 0;
        let totalCeilingMinutes = 0;

        courses.forEach((course, index) => {
            const adjustedCeiling = course.baseCeiling * finalFactor;

            const hours = parseInt(document.getElementById(`hours-${index}`).value) || 0;
            const minutes = parseInt(document.getElementById(`minutes-${index}`).value) || 0;

            const totalMinutes = (hours * 60) + minutes;
            const name = course.name;

            if (totalMinutes > adjustedCeiling) {
                totalMinutesEntered += adjustedCeiling;
            } else {
                totalMinutesEntered += totalMinutes;
            }
            totalCeilingMinutes += adjustedCeiling;

            if (totalMinutes > 0) {
                const percentage = (totalMinutes > adjustedCeiling) ? 100 : (totalMinutes / adjustedCeiling) * 100;
                const extraTime = totalMinutes > adjustedCeiling ? totalMinutes - adjustedCeiling : 0;

                const chartItem = document.createElement('div');
                chartItem.classList.add('chart-item');

                const chartTitle = document.createElement('h3');
                chartTitle.textContent = `نمودار پیشرفت درس: ${name}`;
                chartTitle.style.fontWeight = 'bold';
                chartItem.appendChild(chartTitle);

                if (extraTime > 0) {
                    const extraTimeText = document.createElement('p');
                    extraTimeText.classList.add('extra-time');
                    extraTimeText.textContent = `مقدار اضافه: ${extraTime.toFixed(1)} دقیقه`;
                    chartItem.appendChild(extraTimeText);
                }
                const canvas = document.createElement('canvas');
                canvas.id = `chart-${index}`;
                canvas.width = 400;
                canvas.height = 400;
                chartItem.appendChild(canvas);

                chartsContainer.appendChild(chartItem);

                const ctx = canvas.getContext('2d');
                new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels: ['پیشرفت (' + percentage.toFixed(2) + '%)', 'باقیمانده'],
                        datasets: [{
                            data: [percentage, 100 - percentage],
                            backgroundColor: ['rgba(75, 192, 192, 0.6)', 'rgba(255, 99, 132, 0.2)'],
                            borderColor: ['rgba(75, 192, 192, 1)', 'rgba(255, 99, 132, 1)'],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        plugins: {
                            tooltip: {
                                callbacks: {
                                    label: function(tooltipItem) {
                                        const index = tooltipItem.dataIndex;
                                        const remainingPercentage = 100 - percentage;
                                        if (index === 1) {
                                            const remainingMinutes = (adjustedCeiling - totalMinutes);
                                            const remainingHours = Math.floor(remainingMinutes / 60);
                                            const remainingFinalMinutes = Math.floor(remainingMinutes % 60);

                                            return `باقیمانده (${remainingPercentage.toFixed(2)}%): ${remainingHours} ساعت و ${remainingFinalMinutes} دقیقه`;
                                        } else {
                                            const completedHours = Math.floor(totalMinutes / 60);
                                            const completedMinutes = Math.floor(totalMinutes % 60); // حذف اعشار از دقیقه
                                            return `پیشرفت (${percentage.toFixed(2)}%): ${completedHours} ساعت و ${completedMinutes} دقیقه`;
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });

        if (totalMinutesEntered > 0) {
            const totalPercentage = (totalMinutesEntered / totalCeilingMinutes) * 100;

            const chartItem = document.createElement('div');
            chartItem.classList.add('chart-item');

            const chartTitle = document.createElement('h3');
            chartTitle.textContent = `نمودار پیشرفت کلی`;
            chartTitle.style.fontWeight = 'bold';
            chartItem.appendChild(chartTitle);

            const canvas = document.createElement('canvas');
            canvas.width = 400;
            canvas.height = 400;
            chartItem.appendChild(canvas);

            chartsContainer.appendChild(chartItem);

            const ctx = canvas.getContext('2d');
            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: ['پیشرفت کلی (' + totalPercentage.toFixed(2) + '%)', 'باقیمانده کلی'],
                    datasets: [{
                        data: [totalPercentage, 100 - totalPercentage],
                        backgroundColor: ['rgba(54, 162, 235, 0.6)', 'rgba(255, 159, 64, 0.2)'],
                        borderColor: ['rgba(54, 162, 235, 1)', 'rgba(255, 159, 64, 1)'],
                        borderWidth: 1
                    }]
                },
                options: {
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(tooltipItem) {
                                    const index = tooltipItem.dataIndex;
                                    if (index === 1) {
                                        const remainingMinutes = totalCeilingMinutes - totalMinutesEntered;
                                        const remainingHours = Math.floor(remainingMinutes / 60);
                                        const remainingFinalMinutes = Math.floor(remainingMinutes % 60);

                                        return `باقیمانده کلی (${(100 - totalPercentage).toFixed(2)}%): ${remainingHours} ساعت و ${remainingFinalMinutes} دقیقه`;
                                    } else {
                                        const totalHours = Math.floor(totalMinutesEntered / 60);
                                        const totalMinutes = Math.floor(totalMinutesEntered % 60); // حذف اعشار از دقیقه
                                        return `پیشرفت کلی (${totalPercentage.toFixed(2)}%): ${totalHours} ساعت و ${totalMinutes} دقیقه`;
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }
    // تابع برای حذف بازه‌ای از ردیف‌ها
function deleteRows() {
    const fromRow = prompt("لطفاً شماره ردیف ابتدا را وارد کنید:"); // گرفتن شماره ردیف ابتدا
    const toRow = prompt("لطفاً شماره ردیف انتها را وارد کنید:"); // گرفتن شماره ردیف انتها

    // تبدیل اعداد به عدد صحیح و اطمینان از معتبر بودن مقادیر
    const from = parseInt(fromRow);
    const to = parseInt(toRow);

    if (isNaN(from) || isNaN(to) || from < 1 || to < from) {
        alert("لطفاً بازه صحیحی از ردیف‌ها وارد کنید.");
        return;
    }

    const translationFields = document.getElementById('translation-fields');
    const rows = translationFields.children;

    // حذف ردیف‌ها از آخر به اول تا مشکلی در حذف چندین عنصر به وجود نیاید
    for (let i = to - 1; i >= from - 1; i--) {
        if (rows[i]) {
            rows[i].remove();
        }
    }

    // پس از حذف، مجدداً شماره ردیف‌ها را به‌روز کنیم
    renumberRows();
}

// تابعی برای به‌روزرسانی شماره ردیف‌ها پس از حذف
function renumberRows() {
    const translationFields = document.getElementById('translation-fields');
    const rows = translationFields.children;

    for (let i = 0; i < rows.length; i++) {
        const rowNumber = rows[i].querySelector('span');
        rowNumber.textContent = i + 1; // به‌روزرسانی شماره ردیف
    }
}
    // تابع برای نمایش دکمه‌های Backup، Restore و × و مخفی کردن دکمه Database
function toggleDatabaseButtons() {
    document.getElementById("database-btn").style.display = "none";  // مخفی کردن دکمه Database
    document.getElementById("backup-btn").style.display = "inline-block";  // نمایش دکمه Backup
    document.getElementById("restore-btn").style.display = "inline-block";  // نمایش دکمه Restore
    document.getElementById("close-btn").style.display = "inline-block";  // نمایش دکمه ×
}
    function closeDatabaseButtons() {
    document.getElementById("database-btn").style.display = "block";  // نمایش دکمه Database
    document.getElementById("backup-restore-buttons").style.display = "none";  // مخفی کردن دکمه‌های Backup و Restore
    document.getElementById("close-btn").style.display = "none";  // مخفی کردن دکمه Close

    // دکمه Restore و دکمه‌های جدید را به حالت اولیه برگردانیم
    document.getElementById("restor-btn").style.display = "block";  // نمایش مجدد دکمه Restore
    document.getElementById("restore-options").style.display = "none";  // مخفی کردن دکمه‌های جدید Replace Everything و Just import notes
}
function toggleDatabaseButtons() {
    document.getElementById("database-btn").style.display = "none";  // مخفی کردن دکمه Database
    document.getElementById("backup-restore-buttons").style.display = "flex";  // نمایش دکمه‌های Backup و Restore
    document.getElementById("close-btn").style.display = "block";  // نمایش دکمه Close

    // اطمینان از اینکه دکمه Restore نمایش داده می‌شود و دکمه‌های جدید مخفی هستند
    document.getElementById("restor-btn").style.display = "block";  // نمایش دکمه Restore
    document.getElementById("restore-options").style.display = "none";  // مخفی کردن دکمه‌های جدید
}

function closeDatabaseButtons() {
    document.getElementById("database-btn").style.display = "block";  // نمایش دکمه Database
    document.getElementById("backup-restore-buttons").style.display = "none";  // مخفی کردن دکمه‌های Backup و Restore
    document.getElementById("close-btn").style.display = "none";  // مخفی کردن دکمه Close
}
// تابع برای ذخیره تمام داده‌ها در قالب JSON
// تابع Backup برای ذخیره‌سازی کل اطلاعات صفحه به عنوان یک فایل JSON
function backupData() {
    const data = {};

    // گرفتن داده‌های عمومی صفحه
    data.dailyStudyHours = document.getElementById('daily-study-hours').value || '';
    data.programDuration = document.getElementById('program-duration').value || '';

    // گرفتن داده‌های مربوط به دروس
    data.courses = [];
    courses.forEach((course, index) => {
        const courseData = {
            hours: document.getElementById(`hours-${index}`).value || '',
            minutes: document.getElementById(`minutes-${index}`).value || ''
        };

        const additionalHours = document.getElementById(`additional-hours-${index}`);
        const additionalMinutes = document.getElementById(`additional-minutes-${index}`);
        if (additionalHours && additionalMinutes) {
            courseData.additionalHours = additionalHours.value || '';
            courseData.additionalMinutes = additionalMinutes.value || '';
        }

        data.courses.push(courseData);
    });

    // اضافه کردن اطلاعات حافظه‌های ۱ تا ۳
    data.memory1 = localStorage.getItem('studyData1');
    data.memory2 = localStorage.getItem('studyData2');
    data.memory3 = localStorage.getItem('studyData3');

    // گرفتن داده‌های مربوط به ترجمه‌ها و یادداشت‌ها (شامل A، B و C)
    data.translations = {};
    data.notes = { A: {}, B: {}, C: {} }; // تفکیک یادداشت‌های A، B، C
    courses.forEach((course, index) => {
        const translations = localStorage.getItem(`translations-${index}`);
        const notesA = localStorage.getItem(`notes-A-${index}`);
        const notesB = localStorage.getItem(`notes-B-${index}`);
        const notesC = localStorage.getItem(`notes-C-${index}`);
        if (translations) {
            data.translations[index] = JSON.parse(translations);
        }
        if (notesA) {
            data.notes.A[index] = JSON.parse(notesA);
        }
        if (notesB) {
            data.notes.B[index] = JSON.parse(notesB);
        }
        if (notesC) {
            data.notes.C[index] = JSON.parse(notesC);
        }
    });

    // ذخیره درصد اسکرول پنجره‌های translations و important notes
    data.scrollTranslations = {};
    data.scrollImportantNotes = { A: {}, B: {}, C: {} };

    courses.forEach((course, index) => {
        const scrollPercentTranslations = localStorage.getItem(`translation-scroll-percent-${index}`);
        if (scrollPercentTranslations) {
            data.scrollTranslations[index] = scrollPercentTranslations;
        }

        ['A', 'B', 'C'].forEach(section => {
            const scrollPercentNotes = localStorage.getItem(`notes-scroll-percent-${section}-${index}`);
            if (scrollPercentNotes) {
                data.scrollImportantNotes[section][index] = scrollPercentNotes;
            }
        });
    });

    // ذخیره کردن بازه‌های صفحات و موقعیت اسکرول
    data.pageRanges = {};
    data.scrollPositions = {};
    courses.forEach((course, index) => {
        const courseData = JSON.parse(localStorage.getItem(`courseData${index}`)) || {};
        const scrollPosition = localStorage.getItem(`scrollPosition-${index}`) || 0;
        if (courseData.pages) {
            data.pageRanges[index] = courseData.pages;
        }
        data.scrollPositions[index] = scrollPosition;
    });

    // ذخیره کردن یادآورها
    data.reminders = {};
    courses.forEach((course, index) => {
        const reminder = localStorage.getItem(`reminder-${index}`);
        if (reminder) {
            data.reminders[index] = reminder;
        }
    });

    // ذخیره کردن داده‌ها به صورت یک فایل JSON
    const jsonData = JSON.stringify(data);
    const blob = new Blob([jsonData], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "backup_data.json";
    link.click();

    // نمایش دکمه "ارسال" بعد از دانلود
    showSendButton();
}


function restoreData(event) {
    const file = event.target.files[0];

    if (!file || !file.name.endsWith('.json')) {
        alert("فایل انتخاب شده معتبر نیست. لطفاً یک فایل JSON انتخاب کنید.");
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const jsonData = JSON.parse(e.target.result);

            // نمایش پیغام تایید
            const confirmation = confirm("آیا مطمئن هستید که می‌خواهید اطلاعات این فایل جایگزین اطلاعات فعلی شوند؟");
            if (!confirmation) return;

            // بازیابی داده‌های عمومی
            document.getElementById('daily-study-hours').value = jsonData.dailyStudyHours || '';
            document.getElementById('program-duration').value = jsonData.programDuration || '';

            // بازیابی داده‌های مربوط به دروس
            jsonData.courses.forEach((courseData, index) => {
                document.getElementById(`hours-${index}`).value = courseData.hours || '';
                document.getElementById(`minutes-${index}`).value = courseData.minutes || '';

                if (courseData.additionalHours && courseData.additionalMinutes) {
                    document.getElementById(`additional-hours-${index}`).value = courseData.additionalHours;
                    document.getElementById(`additional-minutes-${index}`).value = courseData.additionalMinutes;
                }
            });

            // بازیابی اطلاعات حافظه‌های ۱ تا ۳
            if (jsonData.memory1) localStorage.setItem('studyData1', jsonData.memory1);
            if (jsonData.memory2) localStorage.setItem('studyData2', jsonData.memory2);
            if (jsonData.memory3) localStorage.setItem('studyData3', jsonData.memory3);

            // بازیابی داده‌های مربوط به ترجمه‌ها و یادداشت‌ها (شامل A، B و C)
            Object.keys(jsonData.translations).forEach(index => {
                localStorage.setItem(`translations-${index}`, JSON.stringify(jsonData.translations[index]));
            });
            Object.keys(jsonData.notes.A).forEach(index => {
                localStorage.setItem(`notes-A-${index}`, JSON.stringify(jsonData.notes.A[index]));
            });
            Object.keys(jsonData.notes.B).forEach(index => {
                localStorage.setItem(`notes-B-${index}`, JSON.stringify(jsonData.notes.B[index]));
            });
            Object.keys(jsonData.notes.C).forEach(index => {
                localStorage.setItem(`notes-C-${index}`, JSON.stringify(jsonData.notes.C[index]));
            });

            // بازیابی درصد اسکرول پنجره‌های translations و important notes
            Object.keys(jsonData.scrollTranslations).forEach(index => {
                localStorage.setItem(`translation-scroll-percent-${index}`, jsonData.scrollTranslations[index]);
            });

            ['A', 'B', 'C'].forEach(section => {
                Object.keys(jsonData.scrollImportantNotes[section]).forEach(index => {
                    localStorage.setItem(`notes-scroll-percent-${section}-${index}`, jsonData.scrollImportantNotes[section][index]);
                });
            });

            // بازیابی بازه‌های صفحات و موقعیت اسکرول
            Object.keys(jsonData.pageRanges).forEach(index => {
                const courseData = { pages: jsonData.pageRanges[index] };
                localStorage.setItem(`courseData${index}`, JSON.stringify(courseData));
            });

            Object.keys(jsonData.scrollPositions).forEach(index => {
                localStorage.setItem(`scrollPosition-${index}`, jsonData.scrollPositions[index]);
            });

            // بازیابی یادآورها
            Object.keys(jsonData.reminders).forEach(index => {
                localStorage.setItem(`reminder-${index}`, jsonData.reminders[index]);
            });

            alert("اطلاعات با موفقیت بازیابی شد!");
        } catch (error) {
            alert("خطا در پردازش فایل. لطفاً یک فایل JSON معتبر انتخاب کنید.");
        }
    };

    reader.readAsText(file);
}
// تابع برای مشاهده همه نکات از ردیف خاصی
function viewAllNotes() {
    let startRow = parseInt(prompt("لطفاً شماره ردیف ابتدا را وارد کنید:"));

    if (isNaN(startRow) || startRow < 1 || startRow > document.getElementById('notes-container').children.length) {
        alert("شماره ردیف معتبر نیست.");
        return;
    }

    showNoteFromRow(startRow - 1);
}

function showNoteFromRow(rowIndex) {
    const notesContainer = document.getElementById('notes-container');
    const rows = notesContainer.querySelectorAll('input');
    const note = rows[rowIndex]?.value.trim();

    const message = note ? `ردیف ${rowIndex + 1}:\n${note}` : `ردیف ${rowIndex + 1}:\nبدون نکته`;

    if (rowIndex + 1 >= rows.length) {
        alert(message); // آخرین نکته نمایش داده شود
    } else {
        if (confirm(message)) {
            showNoteFromRow(rowIndex + 1);
        }
    }
}
// نمایش لایه طوسی با نام درس
// نمایش لایه پوششی با نام درس
function showOverlay(courseName) {
    const overlay = document.getElementById('modal-overlay');
    overlay.textContent = courseName; // نمایش نام درس روی لایه
    overlay.classList.add('active'); // فعال‌سازی لایه
}

// مخفی کردن لایه پوششی
function hideOverlay() {
    const overlay = document.getElementById('modal-overlay');
    overlay.classList.remove('active'); // غیرفعال‌سازی لایه
}
function checkMaxValue() {
    let dailyHoursInput = document.getElementById("daily-study-hours");
    if (dailyHoursInput.value > 18) {
        dailyHoursInput.value = 18; // تنظیم مقدار به 18 در صورتی که بیشتر از 18 باشد
    }
}
// تعریف متغیر برای ذخیره بخش فعلی (A یا B)
// تعریف متغیر برای ذخیره بخش فعلی (A یا B)
let currentSection = 'A';

// تابع تغییر بخش (A به B و برعکس)
function toggleSection() {
    const toggleButton = document.getElementById('toggle-section-btn');
    const sectionBArea = document.getElementById('section-b-area');
    
    // همیشه کلاس‌های موقعیتی را حفظ کنیم
    toggleButton.classList.add('move-left');  // جابجایی به سمت چپ

    // بررسی تغییر بین بخش‌های مختلف
    if (currentSection === 'A') {
        currentSection = 'B';
        toggleButton.textContent = 'B';
        toggleButton.style.backgroundColor = '#007bff'; // رنگ آبی برای B
        sectionBArea.style.display = 'block'; // نمایش بخش B
        loadNotes(currentCourse); // بارگذاری نکات بخش B
    } else if (currentSection === 'B') {
        currentSection = 'C';
        toggleButton.textContent = 'C';
        toggleButton.style.backgroundColor = '#6520a1'; // بنفش کم‌رنگ برای C
        sectionBArea.style.display = 'none'; // مخفی کردن بخش B
        loadNotes(currentCourse); // بارگذاری نکات بخش C
    } else {
        currentSection = 'A';
        toggleButton.textContent = 'A';
        toggleButton.style.backgroundColor = '#dc3545'; // رنگ قرمز برای A
        sectionBArea.style.display = 'none'; // مخفی کردن بخش B
        loadNotes(currentCourse); // بارگذاری نکات بخش A
    }
}
// تابع برای پردازش متن در بخش B
function processTextB() {
    const textInput = document.getElementById('text-input-b').value;
    
    // پیدا کردن تمامی متن‌هایی که با $$ شروع و با %% خاتمه می‌یابند
    const regex = /\$\$([\s\S]*?)%%/g;
    const matches = [...textInput.matchAll(regex)];

    if (matches.length === 0) {
        alert('هیچ متنی با الگوی $$ و %% پیدا نشد.');
        return;
    }

    // اضافه کردن هر متن به عنوان یک فیلد جدید
    const notesContainer = document.getElementById('notes-container');

    matches.forEach((match, index) => {
        let noteText = match[1].trim(); // متن بین $$ و %%

        const noteRow = document.createElement('div');
        noteRow.className = 'mb-2';
        noteRow.innerHTML = `
            <span>${notesContainer.children.length + 1}. <input type="text" class="form-control d-inline-block" value="${noteText.replace(/"/g, '&quot;')}" style="width: 80%;"> 
            <button class="btn btn-danger btn-sm" onclick="deleteNote(this)">حذف</button>
            <button class="btn btn-primary btn-sm" onclick="viewNote(this)">مشاهده</button></span>
        `;
        notesContainer.appendChild(noteRow);
    });
document.querySelector('.important-notes-modal').scrollTo({ top: 0, behavior: 'smooth' });
    setTimeout(() => {
    const notesContainer = document.getElementById('notes-container');
    if (notesContainer) {
        notesContainer.scrollTo({ top: notesContainer.scrollHeight, behavior: 'smooth' });
    } 
}, 500);
    
    // پاک کردن فیلد متن بعد از پردازش
    document.getElementById('text-input-b').value = '';
}
// تابع حذف بازه‌ای از ردیف‌ها
function deleteNotesRange() {
    // درخواست از کاربر برای وارد کردن بازه ابتدا و انتها
    let fromRow = parseInt(prompt("لطفاً شماره ردیف ابتدا را وارد کنید:"));
    let toRow = parseInt(prompt("لطفاً شماره ردیف انتها را وارد کنید:"));

    // تبدیل اعداد به عدد صحیح و اطمینان از معتبر بودن مقادیر
    if (isNaN(fromRow) || isNaN(toRow) || fromRow < 1 || toRow < fromRow) {
        alert("لطفاً بازه صحیحی از ردیف‌ها وارد کنید.");
        return;
    }

    // دسترسی به لیست ردیف‌های نوشته شده در فیلدهای نکات
    const notesContainer = document.getElementById('notes-container');
    const rows = notesContainer.children;

    // حذف ردیف‌ها از آخر به اول تا مشکلی در حذف چندین عنصر به وجود نیاید
    for (let i = toRow - 1; i >= fromRow - 1; i--) {
        if (rows[i]) {
            rows[i].remove();
        }
    }

    // پس از حذف، مجدداً شماره ردیف‌ها را به‌روز کنیم
    renumberNotes();
}

// تابع برای به‌روزرسانی شماره ردیف‌ها پس از حذف
function renumberNotes() {
    const notesContainer = document.getElementById('notes-container');
    const rows = notesContainer.querySelectorAll('span');

    // به‌روزرسانی شماره هر ردیف
    rows.forEach((row, index) => {
        row.firstChild.textContent = `${index + 1}. `;
    });
}
// تابع نرمال‌سازی متن برای جستجو
function normalizeText(text) {
    // ابتدا نیم‌فاصله‌هایی که "ه" را از حروف قبل یا بعد از آن جدا می‌کنند به حال خود باقی می‌گذاریم
    text = text.replace(/(.\u200Cه|ه\u200C.)/g, match => match.replace(/\u200C/g, '__PLACEHOLDER__'));

    // سپس سایر نیم‌فاصله‌ها را حذف می‌کنیم
    text = text.trim().toLowerCase().replace(/[\u200C]/g, '');

    // در نهایت نیم‌فاصله‌هایی که باید بمانند را دوباره به حالت اول برمی‌گردانیم
    return text.replace(/__PLACEHOLDER__/g, '\u200C');
}
// تابع برای بررسی فارسی بودن کلمه
function isPersian(word) {
    const persianPattern = /^[\u0600-\u06FF\s]+$/;
    return persianPattern.test(word);
}

// تابع برای بررسی انگلیسی بودن کلمه
function isEnglish(word) {
    const englishPattern = /^[A-Za-z\s]+$/;
    return englishPattern.test(word);
}

// تقسیم و فیلتر کردن کلمات بر اساس زبان فارسی و انگلیسی
function splitWords(query) {
    const words = query.split(/\s+/); // جدا کردن کلمات بر اساس فاصله
    const xWords = words.filter(word => word.length >= 3); // کلمات با حداقل 3 حرف (X)
    const yWords = words.filter(word => word.length === 2); // کلمات با دقیقاً 2 حرف (Y)
    return { xWords, yWords };
}      

// تابع هایلایت کردن نتایج
function highlightMatch(text, queries) {
    // اضافه کردن CSS فقط برای underline به صورت داخلی در جاوااسکریپت
    const style = document.createElement('style');
    style.innerHTML = `
        .underline {
            box-shadow: 0 1.3px 0 #b805ff; /* فقط خط پایین */
        }
    `;
    document.head.appendChild(style); // اضافه کردن استایل به head

    let highlightedText = text;

    // جداسازی yWords (کلمات دقیقاً ۲ حرفی) و بقیه کلمات
    const yWords = queries.filter(query => query.length === 2);
    const otherWords = queries.filter(query => query.length !== 2);

    // هایلایت کردن کلمات دو حرفی (yWords) به‌عنوان کلمات مستقل
    yWords.forEach(query => {
        let matchIndex = 0; // شمارنده برای تطابق‌ها
        const regex = new RegExp(`(^|\\s)(${query})(?=\\s|$)`, 'gi');
        highlightedText = highlightedText.replace(regex, (match, p1, p2) => {
            if (matchIndex === 0) {
                matchIndex++; // اولین تطابق
                return `${p1}<span class="highlight">${p2}</span>`;
            }
            return `${p1}<span class="underline">${p2}</span>`; // تطابق‌های بعدی
        });
    });

    // هایلایت کردن بقیه کلمات (otherWords)
    otherWords.forEach(query => {
        let matchIndex = 0; // شمارنده برای تطابق‌ها
        const regex = new RegExp(`(${query})`, 'gi');
        highlightedText = highlightedText.replace(regex, (match) => {
            if (matchIndex === 0) {
                matchIndex++; // اولین تطابق
                return `<span class="highlight">${match}</span>`;
            }
            return `<span class="underline">${match}</span>`; // تطابق‌های بعدی
        });
    });

    return highlightedText;
}
      
      let specificCourseOnly = false; // پرچم برای مشخص‌کردن حالت خاص
    let specificCourseName = ''; // متغیر برای ذخیره نام کورس

      
      document.addEventListener('DOMContentLoaded', () => {
    const inputField = document.getElementById('search-input');
    const courseNames = courses.map(course => course.name);
    let previousInputValue = ''; // ذخیره مقدار قبلی ورودی
    
    // الگو برای تشخیص "نام کورس::"
    const coursePattern = new RegExp(`^(${courseNames.join('|')})::`);

    // ایجاد یک المان نمایش استایل‌شده
    const styledField = document.createElement('div');
    styledField.style.position = 'absolute';
    styledField.style.pointerEvents = 'none';
    styledField.style.whiteSpace = 'pre-wrap';
    styledField.style.color = 'black';
    styledField.style.fontSize = getComputedStyle(inputField).fontSize;
    styledField.style.fontFamily = getComputedStyle(inputField).fontFamily;
    styledField.style.padding = getComputedStyle(inputField).padding;
    styledField.style.border = 'none';
    styledField.style.background = 'transparent';
    styledField.style.left = `${inputField.offsetLeft}px`;
    styledField.style.top = `${inputField.offsetTop}px`;
    styledField.style.width = `${inputField.offsetWidth}px`;
    styledField.style.height = `${inputField.offsetHeight}px`;
    styledField.style.overflow = 'hidden';
    styledField.style.zIndex = '1';

    // اضافه کردن المان به والد فیلد
    inputField.parentElement.style.position = 'relative';
    inputField.parentElement.appendChild(styledField);

    // تنظیم شفافیت متن در فیلد ورودی
    inputField.style.position = 'relative';
    inputField.style.background = 'transparent';
    inputField.style.color = 'transparent';
    inputField.style.caretColor = 'black';

    // مدیریت ورودی
    inputField.addEventListener('input', (event) => {
        let inputValue = event.target.value;

        // بررسی تطبیق الگو
        const match = inputValue.match(coursePattern);

        if (match) {
            // اگر الگو کامل است
            specificCourseOnly = true; // بالا بردن پرچم
            specificCourseName = match[1]; // تنظیم نام کورس

            const coursePart = match[0]; // بخش "نام کورس::"
            const remainingPart = inputValue.slice(coursePart.length); // باقی‌مانده متن بعد از الگو
            const inputEvent = new Event('input', { bubbles: true });
            event.target.dispatchEvent(inputEvent);
 

            // نمایش الگو خاکستری و باقی متن مشکی
            styledField.innerHTML = `<span style="color: gray;">${coursePart}</span>${remainingPart}`;
        } else {
            // اگر الگو ناقص یا پاک شده باشد
            specificCourseOnly = false; // پایین آوردن پرچم
            specificCourseName = ''; // پاک کردن نام کورس

            const partialMatch = new RegExp(`^(${courseNames.join('|')}):`);
            if (partialMatch.test(inputValue) && coursePattern.test(previousInputValue)) {
                // اگر قبلش الگوی کامل بوده و الان به "نام کورس:" تبدیل شده، حذف شود
                inputValue = inputValue.replace(/^(.+?):/, '');
            }

            // اگر الگو ناقص شد، کل آن حذف شود
            inputValue = inputValue.replace(/^(.+?)::/, '');
            event.target.value = inputValue; // حذف بدون دستکاری فاصله‌ها
            styledField.innerHTML = inputValue; // فقط متن باقی‌مانده

            // تحریک دستی رویداد input
            const inputEvent = new Event('input', { bubbles: true });
            event.target.dispatchEvent(inputEvent);
        }

        // ذخیره مقدار قبلی
        previousInputValue = event.target.value;
    });

    // هماهنگ‌سازی اسکرول
    inputField.addEventListener('scroll', () => {
        styledField.scrollLeft = inputField.scrollLeft;
    });

    // نمایش متن هنگام فوکوس
    inputField.addEventListener('focus', () => {
        styledField.style.display = 'block';
    });

    // متن داخل فیلد باقی می‌ماند حتی هنگام خروج
    inputField.addEventListener('blur', () => {
        styledField.style.display = 'block'; // متن همچنان باقی بماند
    });
});

let previousXCount = 0; // برای ذخیره تعداد قبلی X ها
let previousYCount = 0; //

// تابع برای جستجوی زنده
function performLiveSearch() {
    const query = document.getElementById('search-input').value.trim();
    const resultsContainer = document.getElementById('search-results');
    resultsContainer.innerHTML = '';  // پاک کردن نتایج قبلی
    resultsContainer.style.display = 'none';  // ابتدا مخفی کردن نتایج

    if (query === '') {
        return;
    }
    // الگوی {courseName}::number
// الگوی جدید: {courseName}::number یا {courseName}::
const coursePattern = /^(.+?)::(\d+)?$/;
const courseMatch = query.match(coursePattern);

if (courseMatch) {
    const courseName = courseMatch[1];
    const targetRow = courseMatch[2] ? parseInt(courseMatch[2], 10) : null; // اگر عدد وجود نداشته باشد، مقدار null

    // یافتن ایندکس کورس بر اساس نام
    const courseIndex = courses.findIndex(course => course.name === courseName);
    if (courseIndex === -1) {    
        return;
    }

    // جمع‌آوری تمامی ردیف‌های بخش‌های A، B و C و مرتب‌سازی
    const allRows = [];
    const maxNotesLength = Math.max(
        (JSON.parse(localStorage.getItem(`notes-A-${courseIndex}`)) || []).length,
        (JSON.parse(localStorage.getItem(`notes-B-${courseIndex}`)) || []).length,
        (JSON.parse(localStorage.getItem(`notes-C-${courseIndex}`)) || []).length
    );

    // اضافه کردن ردیف‌ها به ترتیب شماره و بخش
    for (let i = 0; i < maxNotesLength; i++) {
        ['A', 'B', 'C'].forEach(section => {
            const notes = JSON.parse(localStorage.getItem(`notes-${section}-${courseIndex}`)) || [];
            if (notes[i]) { // بررسی وجود ردیف
                allRows.push({ section, note: notes[i], noteIndex: i });
            }
        });
    }

    // اگر عدد وجود داشته باشد، تنظیم هدف و محاسبه ردیف‌ها
    let adjustedTarget = targetRow;
    if (targetRow) {
        const rowCounts = {};

        for (let i = 0; i < targetRow - 1; i++) {
            const noteIndex = allRows[i].noteIndex;
            if (rowCounts[noteIndex]) {
                rowCounts[noteIndex]++;
            } else {
                rowCounts[noteIndex] = 1;
            }

            if (rowCounts[noteIndex] > 1) {
                adjustedTarget += rowCounts[noteIndex] - 1; // افزودن تکرارها به شماره هدف
            }
        }
    }

    // ایجاد تیتر "همه نکات {courseName}"
    const allNotesTitle = document.createElement('div');
    allNotesTitle.textContent = `همه نکات ${courseName}`;
    allNotesTitle.style.fontWeight = 'bold';
    allNotesTitle.style.backgroundColor = '#034f66';
    allNotesTitle.style.color = 'white';
    allNotesTitle.style.textAlign = 'center';
    resultsContainer.appendChild(allNotesTitle);

    // ایجاد یک div موقت با همان متن allNotesTitle
    const tempNotification = document.createElement('div');
    tempNotification.textContent = allNotesTitle.textContent;
    tempNotification.style.fontWeight = 'bold';
    tempNotification.style.backgroundColor = '#034f66';
    tempNotification.style.color = 'white';
    tempNotification.style.textAlign = 'center';
    tempNotification.style.padding = '10px';
    tempNotification.style.borderRadius = '5px';
    tempNotification.style.zIndex = '1000';
    tempNotification.style.position = 'absolute';
    tempNotification.style.top = '258.5px';
    tempNotification.style.left = '46.25%';
    tempNotification.style.transform = 'translateX(-50%)';
    tempNotification.style.width = '321px';
    tempNotification.style.height = '46px';
    tempNotification.style.fontSize = '17.72px';

    // اضافه کردن به body
    document.body.appendChild(tempNotification);

    // نمایش و محو شدن پس از 3 ثانیه
    setTimeout(() => {
        tempNotification.style.transition = 'opacity 0.5s';
        tempNotification.style.opacity = '0';
        setTimeout(() => {
            tempNotification.remove();
        }, 500);
    }, 3000);

    // نمایش ردیف‌ها و تنظیم هدف
    let targetElement = null;
    allRows.forEach((row, index) => {
        const resultRow = createResultRow({
            courseIndex,
            section: row.section,
            noteIndex: row.noteIndex,
            highlighted: row.note,
            fullText: row.note
        });
        resultsContainer.appendChild(resultRow);

        if (targetRow && index === adjustedTarget - 1) { // اگر عدد وجود داشته باشد
            targetElement = resultRow;
        }
    });

    // نمایش نتایج
    resultsContainer.style.display = 'block';

    // تنظیم اسکرول
    if (targetElement) {
        // اسکرول به ردیف هدف
        const containerRect = resultsContainer.getBoundingClientRect();
        const targetRect = targetElement.getBoundingClientRect();
        const offset = targetRect.top - containerRect.top - (resultsContainer.clientHeight / 2) + (targetElement.clientHeight / 2);

        resultsContainer.scrollTop += offset;
    } else {
        // اگر عدد وجود نداشت، اسکرول در بالاترین موقعیت قرار گیرد
        resultsContainer.scrollTop = 0;
    }

    return;
}

    let normalizedQuery = normalizeText(query);

// استخراج نام‌های درس‌ها از آرایه courses
const courseNames = courses.map(course => course.name);

// جایگزینی فقط اگر نام کورس در لیست باشد
normalizedQuery = normalizedQuery.replace(/^(.+?)::/, (_, courseName) => {
    return courseNames.includes(courseName) ? ' ' : `${courseName}::`;
});
    const exactMatches = [];
    const lessRelevantMatches = [];

    // اگر طول متن وارد شده بین 1 تا 2 حرف باشد، هیچ نتیجه‌ای نمایش داده نمی‌شود.
    if (normalizedQuery.length > 2 && !specificCourseOnly) {
        // جستجوی دقیق در بخش A و B از پنجره Important Notes
        courses.forEach((course, courseIndex) => {
            ['A', 'B', 'C'].forEach(section => { // اضافه کردن بخش C
                const notes = JSON.parse(localStorage.getItem(`notes-${section}-${courseIndex}`)) || [];
                notes.forEach((note, noteIndex) => {
                    if (normalizeText(note).includes(normalizedQuery)) {
                        const highlighted = highlightMatch(note, [query]);  // جستجوی دقیق فقط بر اساس query
                        exactMatches.push({ courseIndex, section, noteIndex, highlighted, fullText: note });
                    }
                });
            });

            // جستجو در پنجره Translations
            const translations = JSON.parse(localStorage.getItem(`translations-${courseIndex}`)) || [];
            translations.forEach((translationObj, translationIndex) => {
                const { translation, word } = translationObj;
                const combinedText = `${word} = ${translation}`;

                // بررسی دقیق کلمه یا ترجمه
                if (normalizeText(combinedText).includes(normalizedQuery)) {
                    const highlighted = highlightMatch(combinedText, [query]);  // جستجوی دقیق فقط بر اساس query
                    exactMatches.push({ courseIndex, section: 'translation', noteIndex: translationIndex, highlighted, fullText: combinedText });
                }
            });
        });
    }

    // جستجوی کمتر مرتبط با تفکیک کلمات X و Y
    const { xWords, yWords } = splitWords(normalizedQuery);

    // بررسی تغییر تعداد X ها
    if (xWords.length !== previousXCount) {
        setTimeout(() => {
            resultsContainer.scrollTop = 0;  // اسکرول به بالای نتایج
        }, 0);
        previousXCount = xWords.length; // به‌روزرسانی تعداد X ها
    }
    // بررسی تغییر تعداد Y ها
    if (yWords.length !== previousYCount) {
        setTimeout(() => {
            resultsContainer.scrollTop = 0;  // اسکرول به بالای نتایج
        }, 0);
        previousYCount = yWords.length; // به‌روزرسانی تعداد Y ها
    }

    // اگر X هایی شناسایی شدند، جستجوی کمتر مرتبط انجام شود
    if (xWords.length > 0) {
    if (specificCourseOnly) {
        // پیدا کردن ایندکس کورس موردنظر
        const courseIndex = courses.findIndex(course => course.name === specificCourseName);
        if (courseIndex !== -1) {
            // پردازش بخش A، B، C برای کورس مشخص‌شده
            ['A', 'B', 'C'].forEach(section => {
                const notes = JSON.parse(localStorage.getItem(`notes-${section}-${courseIndex}`)) || [];
                notes.forEach((note, noteIndex) => {
                    const xMatches = xWords.filter(x => normalizeText(note).includes(x));

                    // فیلتر کردن y هایی که به عنوان کلمه مستقل هستند
                    const yMatches = yWords.filter(y => {
                        return note.split(' ').some(word => normalizeText(word) === normalizeText(y));
                    });

                    const matches = [
                        ...Array(xMatches.length * 5).fill('x'),  // هر xMatches امتیاز ۵
                        ...Array(yMatches.length * 3).fill('y')   // هر yMatches امتیاز ۳
                    ];

                    // نمایش نتایج فقط در صورتی که حداقل یک X وجود داشته باشد
                    if (xMatches.length > 0 && !exactMatches.some(match => match.fullText === note)) {
                        const highlighted = highlightMatch(note, [...xMatches, ...yMatches]);  // هایلایت همه X ها و Y ها
                        let matchPercentage;

                        if (xWords.length >= 4) {
                            if (xWords.length >= yWords.length + 2) {
                                matchPercentage = ((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) * 100;
                            } else {
                                matchPercentage = ((((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) + (xMatches.length / xWords.length)) / 2) * 100;
                            }
                        } else {
                            matchPercentage = (xMatches.length / xWords.length) * 100;
                        }

                        lessRelevantMatches.push({
                            courseIndex,
                            section,
                            noteIndex,
                            highlighted,
                            matchCount: matches.length,
                            matchPercentage,
                            fullText: note
                        });
                    }
                });
            });

            // پردازش ترجمه‌ها برای کورس مشخص‌شده
            const translations = JSON.parse(localStorage.getItem(`translations-${courseIndex}`)) || [];
            translations.forEach((translationObj, translationIndex) => {
                const { translation, word } = translationObj;
                const combinedText = `${word} = ${translation}`;

                const xMatches = xWords.filter(x => normalizeText(combinedText).includes(x));

                // فیلتر کردن y هایی که به عنوان کلمه مستقل هستند
                const yMatches = yWords.filter(y => {
                    return combinedText.split(' ').some(word => normalizeText(word) === normalizeText(y));
                });

                const matches = [
                    ...Array(xMatches.length * 5).fill('x'),  // هر xMatches امتیاز ۵
                    ...Array(yMatches.length * 3).fill('y')   // هر yMatches امتیاز ۳
                ];

                if (xMatches.length > 0 && !exactMatches.some(match => match.fullText === combinedText)) { // شرط وجود حداقل یک X
                    const highlighted = highlightMatch(combinedText, [...xMatches, ...yMatches]);
                    let matchPercentage;

                    if (xWords.length >= 4) {
                        if (xWords.length >= yWords.length + 2) {
                            matchPercentage = ((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) * 100;
                        } else {
                            matchPercentage = ((((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) + (xMatches.length / xWords.length)) / 2) * 100;
                        }
                    } else {
                        matchPercentage = (xMatches.length / xWords.length) * 100;
                    }

                    lessRelevantMatches.push({
                        courseIndex,
                        section: 'translation',
                        noteIndex: translationIndex,
                        highlighted,
                        matchCount: matches.length,
                        matchPercentage,
                        fullText: combinedText
                    });
                }
            });
        }
    } else {
        // پردازش همه کورس‌ها
        courses.forEach((course, courseIndex) => {
            // پردازش بخش A، B، C
            ['A', 'B', 'C'].forEach(section => {
                const notes = JSON.parse(localStorage.getItem(`notes-${section}-${courseIndex}`)) || [];
                notes.forEach((note, noteIndex) => {
                    const xMatches = xWords.filter(x => normalizeText(note).includes(x));

                    // فیلتر کردن y هایی که به عنوان کلمه مستقل هستند
                    const yMatches = yWords.filter(y => {
                        return note.split(' ').some(word => normalizeText(word) === normalizeText(y));
                    });

                    const matches = [
                        ...Array(xMatches.length * 5).fill('x'),  // هر xMatches امتیاز ۵
                        ...Array(yMatches.length * 3).fill('y')   // هر yMatches امتیاز ۳
                    ];

                    // نمایش نتایج فقط در صورتی که حداقل یک X وجود داشته باشد
                    if (xMatches.length > 0 && !exactMatches.some(match => match.fullText === note)) {
                        const highlighted = highlightMatch(note, [...xMatches, ...yMatches]);  // هایلایت همه X ها و Y ها
                        let matchPercentage;

                        if (xWords.length >= 4) {
                            if (xWords.length >= yWords.length + 2) {
                                matchPercentage = ((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) * 100;
                            } else {
                                matchPercentage = ((((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) + (xMatches.length / xWords.length)) / 2) * 100;
                            }
                        } else {
                            matchPercentage = (xMatches.length / xWords.length) * 100;
                        }

                        lessRelevantMatches.push({
                            courseIndex,
                            section,
                            noteIndex,
                            highlighted,
                            matchCount: matches.length,
                            matchPercentage,
                            fullText: note
                        });
                    }
                });
            });

            // پردازش ترجمه‌ها
            const translations = JSON.parse(localStorage.getItem(`translations-${courseIndex}`)) || [];
            translations.forEach((translationObj, translationIndex) => {
                const { translation, word } = translationObj;
                const combinedText = `${word} = ${translation}`;

                const xMatches = xWords.filter(x => normalizeText(combinedText).includes(x));

                // فیلتر کردن y هایی که به عنوان کلمه مستقل هستند
                const yMatches = yWords.filter(y => {
                    return combinedText.split(' ').some(word => normalizeText(word) === normalizeText(y));
                });

                const matches = [
                    ...Array(xMatches.length * 5).fill('x'),  // هر xMatches امتیاز ۵
                    ...Array(yMatches.length * 3).fill('y')   // هر yMatches امتیاز ۳
                ];

                if (xMatches.length > 0 && !exactMatches.some(match => match.fullText === combinedText)) { // شرط وجود حداقل یک X
                    const highlighted = highlightMatch(combinedText, [...xMatches, ...yMatches]);
                    let matchPercentage;

                    if (xWords.length >= 4) {
                        if (xWords.length >= yWords.length + 2) {
                            matchPercentage = ((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) * 100;
                        } else {
                            matchPercentage = ((((xMatches.length + yMatches.length) / (xWords.length + yWords.length)) + (xMatches.length / xWords.length)) / 2) * 100;
                        }
                    } else {
                        matchPercentage = (xMatches.length / xWords.length) * 100;
                    }

                    lessRelevantMatches.push({
                        courseIndex,
                        section: 'translation',
                        noteIndex: translationIndex,
                        highlighted,
                        matchCount: matches.length,
                        matchPercentage,
                        fullText: combinedText
                    });
                }
            });
        });
    }
}

    // نمایش نتایج دقیق
    if (exactMatches.length > 0) {
        const exactTitle = document.createElement('div');
        exactTitle.textContent = 'نتایج دقیق';
        exactTitle.style.fontWeight = 'bold';
        exactTitle.style.backgroundColor = '#034f66';
        exactTitle.style.color = 'white';
        resultsContainer.appendChild(exactTitle);
        exactTitle.style.textAlign = 'center';
      
      // ایجاد دکمه تغییر رنگ
const changeBtn = document.createElement('button');
changeBtn.classList.add('change-btn'); // اضافه کردن کلاس برای مدیریت ظاهر
changeBtn.style.width = '15px'; // تنظیم اندازه دکمه به صورت دایره کوچک‌تر
changeBtn.style.height = '15px';
changeBtn.style.borderRadius = '50%'; // دایره‌ای کردن دکمه
changeBtn.style.border = 'none';
changeBtn.style.backgroundColor = '#ffcc00'; // رنگ اولیه دکمه، قابل تغییر از استایل
changeBtn.style.cursor = 'pointer';
changeBtn.style.position = 'absolute';
changeBtn.style.left = '10px'; // جابه‌جایی دکمه به سمت چپ کادر
changeBtn.style.top = '50%'; // قرار دادن دکمه در وسط ارتفاع کادر
changeBtn.style.transform = 'translateY(-50%)'; // تنظیم دقیق وسط چین بودن
changeBtn.style.fontSize = '10px'; // اندازه متن داخل دکمه
changeBtn.style.display = 'flex';
changeBtn.style.alignItems = 'center';
changeBtn.style.justifyContent = 'center';

changeBtn.textContent = 'T'; // اضافه کردن متن T داخل دکمه

changeBtn.addEventListener('click', changeResultColor); // اضافه کردن رویداد کلیک

// اضافه کردن دکمه به exactTitle
exactTitle.style.position = 'relative'; // تنظیم موقعیت exactTitle به relative برای وابسته کردن دکمه
exactTitle.appendChild(changeBtn);

        exactMatches.forEach(result => {
            const resultRow = createResultRow(result);
            resultsContainer.appendChild(resultRow);
        });
    }

    // نمایش نتایج کمتر مرتبط
    if (lessRelevantMatches.length > 0) {
        const lessRelevantTitle = document.createElement('div');
        lessRelevantTitle.textContent = 'نتایج  پراکنده';
        lessRelevantTitle.style.fontWeight = 'bold';
        lessRelevantTitle.style.backgroundColor = '#3e0366';
        lessRelevantTitle.style.color = 'white';
        resultsContainer.appendChild(lessRelevantTitle);
        lessRelevantTitle.style.textAlign = 'center';
      
      // ایجاد دکمه تغییر رنگ
const changeBtn2 = document.createElement('button');
changeBtn2.classList.add('change-btn'); // اضافه کردن کلاس برای مدیریت ظاهر
changeBtn2.style.width = '15px'; // تنظیم اندازه دکمه به صورت دایره کوچک‌تر
changeBtn2.style.height = '15px';
changeBtn2.style.borderRadius = '50%'; // دایره‌ای کردن دکمه
changeBtn2.style.border = 'none';
changeBtn2.style.backgroundColor = '#ffcc00'; // رنگ اولیه دکمه، قابل تغییر از استایل
changeBtn2.style.cursor = 'pointer';
changeBtn2.style.position = 'absolute';
changeBtn2.style.left = '10px'; // جابه‌جایی دکمه به سمت چپ کادر
changeBtn2.style.top = '50%'; // قرار دادن دکمه در وسط ارتفاع کادر
changeBtn2.style.transform = 'translateY(-50%)'; // تنظیم دقیق وسط چین بودن
changeBtn2.style.fontSize = '10px'; // اندازه متن داخل دکمه
changeBtn2.style.display = 'flex';
changeBtn2.style.alignItems = 'center';
changeBtn2.style.justifyContent = 'center';

changeBtn2.textContent = 'T'; // اضافه کردن متن T داخل دکمه

changeBtn2.addEventListener('click', changeResultColor); // اضافه کردن رویداد کلیک

// اضافه کردن دکمه به lessRelevantTitle
lessRelevantTitle.style.position = 'relative'; // تنظیم موقعیت lessRelevantTitle به relative برای وابسته کردن دکمه
lessRelevantTitle.appendChild(changeBtn2);

        // مرتب‌سازی بر اساس تعداد X هایی که مطابقت دارند
        lessRelevantMatches.sort((a, b) => b.matchCount - a.matchCount);
        lessRelevantMatches.forEach(result => {
            const resultRow = createResultRow(result);
            resultsContainer.appendChild(resultRow);
        });
    }

    // اگر نتایجی وجود داشته باشد، نمایش لیست نتایج
    if (exactMatches.length > 0 || lessRelevantMatches.length > 0) {
        resultsContainer.style.display = 'block';      
    }
}

// ایجاد ردیف نتیجه
function createResultRow(result) {
    const resultRow = document.createElement('div');
    resultRow.innerHTML = `${result.highlighted} <span style="font-weight: bold;">(${courses[result.courseIndex].name} - ردیف ${result.noteIndex + 1})</span>`;

    // بررسی اگر درصد تطابق در بازه تعیین‌شده باشد، رنگ زرد متمایل به خردلی اعمال شود
    if ((result.matchPercentage >= 51 && result.matchPercentage <= 65) || (result.matchPercentage >= 67 && result.matchPercentage <= 99)) {
        resultRow.style.backgroundColor = '#7fb08f';  // رنگ زرد متمایل به خردلی
    }

    // اضافه کردن کلیک روی هر ردیف برای نمایش پیام با confirm
    resultRow.addEventListener('click', () => {
        const message = `${result.fullText}\n(${courses[result.courseIndex].name} - ردیف ${result.noteIndex + 1})`;

        // نمایش confirm به جای alert
        const confirmation = confirm(message);
if (confirmation) {
            // اگر کاربر روی "OK" کلیک کرد، پنجره مناسب باز شود و اسکرول تنظیم گردد
            openNoteOrTranslation(result.courseIndex, result.section, result.noteIndex);
        }
    });

    return resultRow;
}

      let debounceTimer;

document.getElementById('search-input').addEventListener('input', () => {
    clearTimeout(debounceTimer); // لغو تایمر قبلی
    debounceTimer = setTimeout(() => {
        performLiveSearch(); // فراخوانی تابع با تاخیر
    }, 100); // زمان تاخیر: 0.2 ثانیه
});
// اعمال تابع جستجوی زنده هنگام تایپ در فیلد
let selectedFileContent = ''; // متغیر برای ذخیره محتوای فایل انتخاب‌شده

// تابعی که پس از انتخاب فایل اجرا می‌شود و فایل را می‌خواند
function handleFileSelect(event) {
    const file = event.target.files[0]; // گرفتن فایل انتخاب‌شده

    if (!file) {
        alert('لطفاً یک فایل انتخاب کنید.');
        return;
    }

    // بررسی فرمت فایل
    const fileType = file.name.split('.').pop().toLowerCase(); // گرفتن پسوند فایل
    if (fileType !== 'txt') {
        alert('لطفاً یک فایل متنی با فرمت .txt انتخاب کنید.');
        cancelFileOperation(); // بازگرداندن دکمه‌ها به حالت اولیه
        return;
    }

    const reader = new FileReader();

    reader.onload = function(e) {
        selectedFileContent = e.target.result; // ذخیره محتوای فایل
        alert('فایل با موفقیت بارگذاری شد!');

        // تغییر دکمه‌ها به دکمه "استخراج" و دکمه "لغو"
        changeToExtractButtons();
    };

    reader.readAsText(file); // خواندن فایل به صورت متن
}

// تابعی برای تغییر دکمه "انتخاب فایل" به دکمه‌های "استخراج" و "لغو"
function changeToExtractButtons() {
    const fileButtonsDiv = document.getElementById('file-buttons');

    // تغییر HTML به دکمه‌های استخراج و لغو
    fileButtonsDiv.innerHTML = `
        <button id="extract-btn" class="btn btn-success mt-2" onclick="extractTextFromFile()">استخراج</button>
        <button id="cancel-btn" class="btn btn-danger mt-2" onclick="cancelFileOperation()">×</button>
    `;
}

// تابع لغو عملیات انتخاب فایل
function cancelFileOperation() {
    const fileButtonsDiv = document.getElementById('file-buttons');

    // تغییر HTML به حالت اولیه با دکمه "انتخاب فایل"
    fileButtonsDiv.innerHTML = `
        <input type="file" id="text-file-input" accept=".txt" style="display: none;" onchange="handleFileSelect(event)">
        <button id="select-file-btn" class="btn btn-primary mt-2" onclick="document.getElementById('text-file-input').click()">انتخاب فایل</button>
    `;

    // پاک کردن محتوای فایل انتخاب شده
    selectedFileContent = '';
}

// تابعی برای استخراج متون بین $$ و %% و اضافه کردن آن‌ها به نکات
function extractTextFromFile() {
    if (!selectedFileContent) {
        alert('ابتدا یک فایل انتخاب کنید.');
        return;
    }

    const chunkSize = 1000; // اندازه هر بخش: ۵۰۰ کاراکتر
    const totalLength = selectedFileContent.length;
    const notesContainer = document.getElementById('notes-container'); // محل اضافه کردن ردیف‌ها

    let chunkIndex = 0;
    let numberOfNotes = 0; // شمارش تعداد نکات جدید

    // حلقه‌ای برای تقسیم فایل به بخش‌های ۵۰۰ کاراکتری
    while (chunkIndex < totalLength) {
        let chunk = selectedFileContent.slice(chunkIndex, chunkIndex + chunkSize); // برش ۵۰۰ کاراکتر

        // بررسی اگر کاراکتر بعدی حرفی باشد که به کلمه چسبیده است (یعنی بلافاصله بعد از ۵۰۰ کاراکتر فاصله نباشد)
        if (chunkIndex + chunkSize < totalLength && /\S/.test(selectedFileContent[chunkIndex + chunkSize])) {
            // اگر بلافاصله بعد از ۵۰۰ کاراکتر کاراکتر بعدی یک حرف است (نه فاصله)، ادامه کلمه را به این بخش اضافه می‌کنیم
            let extraPart = '';
            let nextIndex = chunkIndex + chunkSize;

            // ادامه دادن تا رسیدن به فاصله یا پایان کلمه
            while (nextIndex < totalLength && /\S/.test(selectedFileContent[nextIndex])) {
                extraPart += selectedFileContent[nextIndex];
                nextIndex++;
            }

            // اضافه کردن قسمت اضافی به chunk
            chunk += extraPart;
            chunkIndex = nextIndex; // بروزرسانی اندیس برای بخش بعدی
        } else {
            chunkIndex += chunkSize; // افزایش اندیس برای بخش بعدی
        }

        chunk = chunk.trim(); // حذف فاصله‌های اضافی ابتدا و انتهای هر بخش

        // اضافه کردن هر بخش به عنوان یک نکته جدید
        const noteRow = document.createElement('div');
        noteRow.className = 'mb-2';
        noteRow.innerHTML = `
            <span>${notesContainer.children.length + 1}. <input type="text" class="form-control d-inline-block" value="${chunk}" style="width: 80%;"> 
            <button class="btn btn-danger btn-sm" onclick="deleteNote(this)">حذف</button>
            <button class="btn btn-primary btn-sm" onclick="viewNote(this)">مشاهده</button></span>
        `;
        notesContainer.appendChild(noteRow);

        numberOfNotes++; // افزایش شمارش نکات
    }

    alert(`${numberOfNotes} نکته جدید به بخش B اضافه شد.`);

    // بازگرداندن دکمه‌ها به حالت اولیه پس از استخراج
    cancelFileOperation();
}
// تنظیمات مربوط به دوره‌ها (به عنوان مثال داده‌های نمونه)
document.getElementById("restor-btn").addEventListener('click', function() {
    document.getElementById("restor-btn").style.display = "none";  // مخفی کردن دکمه Restore
    document.getElementById("restore-options").style.display = "flex";  // نمایش دکمه‌های جدید
});
document.getElementById('import-notes-btn').addEventListener('click', function() {
    // باز کردن فایل انتخابی برای Just Import Notes
    const fileInput = document.getElementById('fileInputImportNotes');
    fileInput.click();

    // حذف Event Listener قبلی (در صورت وجود)
    fileInput.removeEventListener('change', handleFileChange);

    // اضافه کردن Event Listener جدید فقط یک بار
    fileInput.addEventListener('change', handleFileChange);
});

function handleFileChange(event) {
    const file = event.target.files[0];

    if (!file || !file.name.endsWith('.json')) {
        alert("لطفاً یک فایل JSON انتخاب کنید.");
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const jsonData = JSON.parse(e.target.result);

            // نمایش پیغام تأیید به کاربر
            const confirmation = confirm("آیا می‌خواهید نکات از این فایل به نکات درس‌ها اضافه شود؟");
            if (!confirmation) return;

            // شروع فرایند اضافه کردن نکات
            importNotesFromJson(jsonData);

        } catch (error) {
            alert("خطا در پردازش فایل JSON. لطفاً یک فایل JSON معتبر انتخاب کنید.");
        }
    };

    reader.readAsText(file);
}
function importNotesFromJson(jsonData) {
    const addedNotesCount = {}; // برای شمارش تعداد نکات جدید اضافه شده به هر درس

    courses.forEach((course, index) => {
        const notesA = jsonData.notes.A[index] || [];
        const notesB = jsonData.notes.B[index] || [];
        const notesC = jsonData.notes.C[index] || [];

        const allNotes = [...notesA, ...notesB, ...notesC]; // جمع‌آوری همه نکات A و B و C

        const currentNotesA = JSON.parse(localStorage.getItem(`notes-A-${index}`)) || [];
        const currentNotesB = JSON.parse(localStorage.getItem(`notes-B-${index}`)) || [];
        const currentNotesC = JSON.parse(localStorage.getItem(`notes-C-${index}`)) || [];
        const allCurrentNotes = [...currentNotesA, ...currentNotesB, ...currentNotesC]; // جمع‌آوری همه نکات فعلی

        const uniqueNewNotes = allNotes.filter(note => !allCurrentNotes.includes(note)); // فیلتر کردن نکات تکراری

        if (uniqueNewNotes.length > 0) {
            // افزودن نکات جدید به بخش C
            const updatedNotesC = [...currentNotesC, ...uniqueNewNotes];
            localStorage.setItem(`notes-C-${index}`, JSON.stringify(updatedNotesC));

            // شمارش تعداد نکات جدید اضافه شده
            addedNotesCount[course.name] = uniqueNewNotes.length;
        } else {
            addedNotesCount[course.name] = 0; // اگر نکته‌ای اضافه نشده باشد
        }
    });

    // نمایش پیام نتیجه
    let resultMessage = "نتایج اضافه کردن نکات به بخش C:\n";
    Object.keys(addedNotesCount).forEach(courseName => {
        resultMessage += `${courseName}: ${addedNotesCount[courseName]} نکته جدید افزوده شد.\n`;
    });

    alert(resultMessage);
}
// تابع برای نرمال‌سازی متن: حذف فاصله‌های اضافی
function normalizeTextForNotes(text) {
    return text.replace(/\s*=\s*/g, '='); // حذف فاصله‌ها فقط اطراف علامت =
}
// تابع بررسی انگلیسی بودن متن
function isEnglishText(text) {
    return /^[A-Za-z\s]+$/.test(text.trim()); // بررسی حروف انگلیسی با نادیده گرفتن فاصله‌ها
}

// تابع بررسی فارسی بودن متن
function isPersianText(text) {
    return /^[\u0600-\u06FF\s]+$/.test(text.trim()); // بررسی حروف فارسی با نادیده گرفتن فاصله‌ها
}
// مقادیر پیشفرض
const defaultImportanceValues = [19.35, 6.45, 6.45, 6.45, 12.90, 12.90, 9.68, 6.45, 6.45, 6.45, 3.23, 3.23];
let importanceValues = [...defaultImportanceValues]; // آرایه‌ای برای ذخیره مقادیر فعلی

// نمایش پنجره ضریب اهمیت دروس
// نمایش overlay جدید مخصوص پنجره ضریب اهمیت
// نمایش پنجره ضریب اهمیت دروس به همراه overlay
// بارگذاری مقادیر ضریب اهمیت از حافظه (localStorage) یا استفاده از مقادیر پیش‌فرض
function loadImportanceValues() {
    const importanceFieldsContainer = document.getElementById('importance-fields');
    importanceFieldsContainer.innerHTML = ''; // پاک کردن فیلدهای قبلی

    const savedImportanceValues = JSON.parse(localStorage.getItem('importanceValues')) || defaultImportanceValues;

    courses.forEach((course, index) => {
        const formGroup = document.createElement('div');
        formGroup.className = 'form-group';

        const savedValue = savedImportanceValues[index];

        formGroup.innerHTML = `
            <label>${course.name}:</label>
            <input type="number" class="form-control importance-input" 
                value="${savedValue !== undefined ? savedValue : ''}" 
                placeholder="${savedValue === undefined ? defaultImportanceValues[index] : ''}" 
                id="importance-${index}" 
                onblur="setPlaceholder(${index})"> <!-- رویداد onblur اضافه شده است -->
        `;

        importanceFieldsContainer.appendChild(formGroup);
    });
}

// نمایش پنجره ضریب اهمیت
function openImportanceModal() {
    document.getElementById('importance-modal').style.display = 'block';
    loadImportanceValues();  // مقادیر موجود یا پیش‌فرض را بارگذاری کن
     // نمایش overlay
}

// بستن پنجره ضریب اهمیت
function closeImportanceModal() {
    document.getElementById('importance-modal').style.display = 'none';
     // مخفی کردن overlay
}
// تابع برای ذخیره مقادیر جدید و محاسبه BaseCeiling جدید
// تابع برای ذخیره مقادیر جدید و محاسبه BaseCeiling جدید
// تابع برای ذخیره مقادیر جدید و محاسبه BaseCeiling جدید
function saveImportance(showAlert = true) {
    const newImportanceValues = [];

    courses.forEach((course, index) => {
        const inputField = document.getElementById(`importance-${index}`);
        let value = parseFloat(inputField.value);

        // اگر فیلد خالی باشد یا مقدار 0 باشد، مقدار پیش‌فرض را در نظر بگیریم
        if (isNaN(value) || value === 0) {
            value = defaultImportanceValues[index];
        }

        newImportanceValues.push(value);
    });

    // ذخیره مقادیر جدید در localStorage
    localStorage.setItem('importanceValues', JSON.stringify(newImportanceValues));

    // محاسبه BaseCeiling جدید
    const totalImportance = newImportanceValues.reduce((sum, val) => sum + val, 0);

    courses.forEach((course, index) => {
        course.baseCeiling = (newImportanceValues[index] / totalImportance) * 2940;
    });

    // نمایش alert تنها زمانی که showAlert برابر true باشد
    if (showAlert) {
        alert("ضرایب اهمیت جدید ثبت شد!");
    }
    closeImportanceModal();
}

// تابعی که به صورت خودکار دکمه "ثبت" را شبیه‌سازی می‌کند
function autoSaveImportance() {
    saveImportance(false); // فراخوانی بدون نمایش alert
}
// فراخوانی خودکار بعد از بارگذاری صفحه
// بازگشت به مقادیر پیش‌فرض
function resetToDefault() {
    // تاییدیه از کاربر برای بازگشت به مقادیر پیش‌فرض
    if (confirm('آیا مطمئن هستید که می‌خواهید به مقادیر پیش‌فرض بازگردید؟')) {
        
        // بازگرداندن مقادیر پیش‌فرض به importanceValues
        importanceValues = [...defaultImportanceValues];

        // ذخیره کردن مقادیر پیش‌فرض در localStorage
        localStorage.setItem('importanceValues', JSON.stringify(defaultImportanceValues));

        // بارگذاری مجدد مقادیر پیش‌فرض در فیلدهای ورودی
        loadImportanceValues();

        // به‌روزرسانی baseCeiling برای هر درس بر اساس مقادیر پیش‌فرض
        const totalImportance = defaultImportanceValues.reduce((sum, val) => sum + val, 0);
        courses.forEach((course, index) => {
            course.baseCeiling = (defaultImportanceValues[index] / totalImportance) * 2940;
        });

        alert('مقادیر به حالت پیش‌فرض بازگشتند!');
    }
    closeImportanceModal();
}
function autoLoadImportance() {
    const savedImportanceValues = JSON.parse(localStorage.getItem('importanceValues'));

    if (savedImportanceValues) {
        // محاسبه BaseCeiling جدید
        const totalImportance = savedImportanceValues.reduce((sum, val) => sum + val, 0);

        courses.forEach((course, index) => {
            course.baseCeiling = (savedImportanceValues[index] / totalImportance) * 2940;
        });
    } else {
        // اگر مقادیری در localStorage نبود، از مقادیر پیش‌فرض استفاده کنیم
        const totalImportance = defaultImportanceValues.reduce((sum, val) => sum + val, 0);

        courses.forEach((course, index) => {
            course.baseCeiling = (defaultImportanceValues[index] / totalImportance) * 2940;
        });
    }
}
window.addEventListener('load', function() {
    // ابتدا مطمئن شویم که مقادیر به درستی بارگذاری می‌شوند
    loadImportanceValues(); 
    
    // با کمی تأخیر، تابع ذخیره‌سازی را اجرا می‌کنیم تا مطمئن شویم مقادیر به درستی بارگذاری شده‌اند
    setTimeout(function() {
        autoSaveImportance(); // فراخوانی تابع برای ذخیره مقادیر
    }, 100); // تأخیر 100 میلی‌ثانیه
});
function setPlaceholder(index) {
    const inputField = document.getElementById(`importance-${index}`);
    const value = parseFloat(inputField.value);

    // اگر مقدار صفر یا خالی باشد، placeholder پیش‌فرض را نمایش دهد
    if (isNaN(value) || value === 0) {
        inputField.value = ''; // مقدار فعلی را پاک کنیم
        inputField.placeholder = defaultImportanceValues[index]; // نمایش مقدار پیش‌فرض به عنوان placeholder
    }
}
function openNoteOrTranslation(courseIndex, section, noteIndex) {
    if (section === 'translation') {
        showTranslations(courseIndex); // باز کردن پنجره ترجمه

        // پس از باز شدن پنجره ترجمه، درصد اسکرول محاسبه و اعمال شود
        setTimeout(() => {
            const container = document.getElementById('translation-fields');
            const totalRows = container.children.length; // تعداد کل ردیف‌ها
            const scrollPercentage = (noteIndex / totalRows) * 100; // محاسبه درصد اسکرول

            container.scrollTop = (container.scrollHeight - container.clientHeight) * (scrollPercentage / 100);
        }, 100); // کمی تأخیر برای اطمینان از اینکه پنجره به طور کامل باز شده است
    } else if (section === 'A' || section === 'B' || section === 'C') {
        showImportantNotes(courseIndex); // باز کردن پنجره نکات مهم

        // بررسی اینکه آیا باید به بخش A، B یا C برویم
        if (currentSection !== section) {
            // اگر بخش جاری با بخش موردنظر متفاوت است، تغییر بخش را انجام دهیم
            while (currentSection !== section) {
                toggleSection(); // این تابع باید بخش‌ها را یکی یکی تغییر دهد
            }
        }

        // حالا اسکرول را بر اساس بخش و ردیف تنظیم می‌کنیم
        setTimeout(() => {
            const container = document.getElementById('notes-container');
            const totalRows = container.children.length; // تعداد کل ردیف‌ها
            const scrollPercentage = (noteIndex / totalRows) * 100; // محاسبه درصد اسکرول

            container.scrollTop = (container.scrollHeight - container.clientHeight) * (scrollPercentage / 100);
        }, 100); // کمی تأخیر برای اطمینان از اینکه پنجره به طور کامل باز شده است
    }
}
let startNode = null;
let startOffset = null;
let isStartSelected = false;
let markerSpan = null;
let pasteAllowed = true;
let undoStack = [];
let editedTextMap = new Map();  // استفاده از Map برای ذخیره ویرایش‌های مربوط به هر span
let currentHighlightSpan = null;
let mainChild = false; 
let attachText = false;    
let globalSpan;    
let counter = 0; 
let isCut = false; 
let returnAttach = false;
let counterCut = 0;
let undoDone = false;   
let dontMistake = false;
let ltrOn = false;      
      
      
      function checkCounter() {
  if (counter < 0) {
    counter = 0;
  }
}
    // تعریف undoStack
// بازنویسی متد push
undoStack.push = function (element) {
    // بررسی وضعیت attachText
    if (element.attachText === undefined) {
        element.attachText = false; // مقدار پیش‌فرض
    }
    // استفاده از متد اصلی push
    Array.prototype.push.call(this, element);
};
    let button;
    let isRotating = false;
    
   document.addEventListener('DOMContentLoaded', function () {
    // ایجاد دکمه
     button = document.createElement('button');
    button.innerHTML = '🔗'; // آیکون دکمه
    button.style.position = 'absolute'; // قرار دادن دکمه به صورت مطلق
    button.style.top = '19px'; // فاصله از بالا
    button.style.right = '69px'; // فاصله از سمت راست
    button.style.background = 'none'; // بدون پس‌زمینه
    button.style.border = 'none'; // بدون مرز
    button.style.cursor = 'pointer'; // نمایش دست روی دکمه
    button.style.fontSize = '16px'; // اندازه آیکون
    button.style.userSelect = 'none'; // جلوگیری از انتخاب متن
    button.style.pointerEvents = 'auto'; // اطمینان از کار نکردن نشانگر متن
    button.style.overflow = 'hidden'; // حذف رفتار متن اضافه
    button.style.textAlign = 'center'; // تراز گرافیکی
    button.style.lineHeight = '1'; // حذف خط‌چینی اضافی
    button.style.zIndex = '1000'; // اطمینان از نمایش بالای سایر عناصر

    // اضافه کردن دکمه به عنصر reviewContent
    const reviewContent = document.getElementById('reviewContent');
    reviewContent.style.position = 'relative'; // اطمینان از موقعیت‌دهی عنصر والد
    reviewContent.appendChild(button);

    // وضعیت چرخش و پرچم attachText
   

    // افزودن رویداد کلیک به دکمه
    button.addEventListener('click', function () {
        if (!isRotating) {
            // اگر چرخش غیرفعال است: شروع چرخش و فعال‌سازی پرچم
            button.style.animation = 'spin 2s linear infinite'; // شروع چرخش
            isRotating = true;
            attachText = true; // فعال کردن پرچم attachText
        } else {
            // اگر چرخش فعال است: توقف چرخش و اجرای تابع
            button.style.animation = ''; // توقف چرخش
            isRotating = false;
            isCut = false;
            processAndReplace(undoStack, editedTextMap); // فراخوانی تابع
        }
    });

    // تعریف انیمیشن چرخش با CSS
    const style = document.createElement('style');
    style.innerHTML = `
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    `;
    document.head.appendChild(style);
}); 
    
    

const textContainer = document.getElementById('textContainer');
    
    // انتخاب عناصر
const editableDiv = document.getElementById('textContainer');
const parentDiv = document.getElementById('reviewContent'); // عنصر والد برای دکمه

// ایجاد دکمه تغییر زبان
const toggleLanguageButton = document.createElement('button');

// تنظیم استایل‌های دکمه
// تنظیم استایل‌های دکمه
toggleLanguageButton.style.position = 'absolute';
toggleLanguageButton.style.top = '18.7px';
toggleLanguageButton.style.left = '70px';
toggleLanguageButton.style.backgroundColor = '#ccc';
toggleLanguageButton.style.color = 'black';
toggleLanguageButton.style.border = 'none';
toggleLanguageButton.style.borderRadius = '50%';
toggleLanguageButton.style.width = '16.5px'; // طول دکمه
toggleLanguageButton.style.height = '16.5px'; // عرض دکمه
toggleLanguageButton.style.fontSize = '10.5px'; // کوچک کردن متن داخل دکمه
toggleLanguageButton.style.display = 'flex'; // برای تراز متن
toggleLanguageButton.style.lineHeight = '17px'; // خط عمودی کمی بزرگ‌تر از ارتفاع دکمه
toggleLanguageButton.style.justifyContent = 'center'; // متن در وسط افقی
toggleLanguageButton.style.cursor = 'pointer';

// افزودن دکمه به DOM به عنوان زیرمجموعه reviewContent
parentDiv.style.position = 'relative'; // برای موقعیت‌دهی دکمه
parentDiv.appendChild(toggleLanguageButton);

// تابع برای ذخیره وضعیت در localStorage
function saveState(isLTRDirection) {
    const state = {
        isLTR: isLTRDirection,
        direction: isLTRDirection ? 'ltr' : 'rtl',
        textAlign: isLTRDirection ? 'left' : 'right',
        buttonText: isLTRDirection ? 'En' : 'Fa',
    };
    localStorage.setItem('textContainerState', JSON.stringify(state));
}

// تابع برای بازیابی وضعیت از localStorage
function restoreState() {
    const savedState = localStorage.getItem('textContainerState');
    if (savedState) {
        const state = JSON.parse(savedState);
        editableDiv.style.direction = state.direction;
        editableDiv.style.textAlign = state.textAlign;
        toggleLanguageButton.textContent = state.buttonText;

        // فعال‌سازی پرچم ltrOn اگر وضعیت LTR باشد
        if (state.direction === 'ltr') {
            ltrOn = true;
        }
        return state.isLTR; // بازگشت وضعیت LTR یا RTL
    }

    // حالت پیش‌فرض اگر چیزی ذخیره نشده باشد
    editableDiv.style.direction = 'rtl';
    editableDiv.style.textAlign = 'right';
    toggleLanguageButton.textContent = 'Fa';
    return false; // حالت پیش‌فرض RTL
}

// بازیابی وضعیت در هنگام بارگذاری صفحه
let isDirectionLTR = restoreState();

// تابع برای تغییر زبان و جهت متن
function toggleTextDirection() {
    if (isDirectionLTR) {
        // بازگشت به حالت RTL
        editableDiv.style.direction = 'rtl';
        editableDiv.style.textAlign = 'right';
        toggleLanguageButton.textContent = 'Fa';

        // غیرفعال کردن پرچم ltrOn
        ltrOn = false;
    } else {
        // تغییر به حالت LTR
        editableDiv.style.direction = 'ltr';
        editableDiv.style.textAlign = 'left';
        toggleLanguageButton.textContent = 'En';

        // فعال‌سازی پرچم ltrOn
        ltrOn = true;
    }
    // ذخیره وضعیت در localStorage
    isDirectionLTR = !isDirectionLTR;
    saveState(isDirectionLTR);
}

// افزودن رویداد کلیک به دکمه
toggleLanguageButton.addEventListener('click', toggleTextDirection);
      
      


function handlePaste(event) {
    if (!pasteAllowed) {
        event.preventDefault();
        return;
    }
    pasteAllowed = false;
    setTimeout(() => {
        textContainer.setAttribute("contenteditable", "false");
        textContainer.style.cursor = 'pointer';
        textContainer.style.userSelect = 'text';
        textContainer.blur();
        textContainer.scrollTop = 0;
    }, 0);
}

// بستن کیبورد در هنگام ورود تغییرات
function closeKeyboardOnInput(element) {
    element.setAttribute("contenteditable", "false"); // غیرفعال کردن ویرایش
    element.style.userSelect = "text"; // قابل انتخاب کردن متن
    element.blur();
    element.scrollTop = 0;
}

// کلیک برای مشخص کردن ابتدا و انتهای بازه
textContainer.addEventListener('click', function (e) {
    if (textContainer.textContent.trim() === '') return;

    const range = document.caretRangeFromPoint(e.clientX, e.clientY);

    // تنظیم محدوده در نزدیک‌ترین موقعیت متنی
    if (!range || range.startContainer.nodeType !== Node.TEXT_NODE) {
        const nodes = textContainer.childNodes;
        for (let i = nodes.length - 1; i >= 0; i--) {
            if (nodes[i].nodeType === Node.TEXT_NODE && nodes[i].textContent.trim() !== '') {
                range = document.createRange();
                range.setStart(nodes[i], nodes[i].textContent.length);
                range.setEnd(nodes[i], nodes[i].textContent.length);
                break;
            }
        }
    }

    if (!isStartSelected && range) {
        startNode = range.startContainer;
        startOffset = range.startOffset;
        isStartSelected = true;

        markerSpan = document.createElement('span');
        markerSpan.classList.add('startMarker');
        markerSpan.textContent = '|';

        const rect = range.getBoundingClientRect();
        const containerRect = textContainer.getBoundingClientRect();
        markerSpan.style.top = `${rect.top - containerRect.top + textContainer.scrollTop}px`;
        markerSpan.style.left = `${rect.left - containerRect.left}px`;

        textContainer.appendChild(markerSpan);

    } else if (isStartSelected && range) {
        const endNode = range.endContainer || range.startContainer;
        const endOffset = range.endOffset || range.startOffset;

        const selectionRange = document.createRange();
        selectionRange.setStart(startNode, startOffset);
        selectionRange.setEnd(endNode, endOffset);

        const selectedText = selectionRange.toString().trim();

        if (selectedText) {
            if (!attachText && !mainChild) {
const highlightSpan = document.createElement('span');
            highlightSpan.style.backgroundColor = "#ffbd9c";
highlightSpan.style.fontWeight = "860";
highlightSpan.style.borderTop = "1px solid #de7c7c"; // حاشیه بالا
highlightSpan.style.borderBottom = "1px solid #de7c7c"; // حاشیه پایین 
            selectionRange.surroundContents(highlightSpan);
            undoStack.push(highlightSpan);

            // تنظیم رویداد کلیک روی هایلایت برای ویرایش
            highlightSpan.addEventListener('click', function (event) {
    if (attachText) {
        // اگر attachText فعال است، از اجرای کلیک جلوگیری کن
        event.stopImmediatePropagation(); // جلوگیری از ادامه پردازش رویداد
        event.preventDefault(); // جلوگیری از پیش‌فرض مرورگر
    } else {
        // اگر attachText غیرفعال است، تابع کلیک اجرا می‌شود
        openEditModal(highlightSpan);
    }
});


} else if (attachText && !mainChild) { 
let goBack = false;  
  counterCut++;
    isCut = false;
    setTimeout(() => {
      let counterCutt = 0;
counterCutt = counterCut
const intervalId3 = setInterval(() => {
if (dontMistake) {
counterCutt = 10000;
setTimeout(() => {   
dontMistake = false;
}, 250);
clearInterval(intervalId3);
}
}, 150);
        isCut = true;
        counter++;
const highlightSpan = document.createElement('span');
  globalSpan = highlightSpan
            highlightSpan.style.backgroundColor = "#9cfaff";
highlightSpan.style.fontWeight = "860";
  highlightSpan.style.borderTop = "2px solid #de7c7c"; // حاشیه بالا
highlightSpan.style.borderBottom = "2px solid #de7c7c"; // حاشیه پایین
      if (!ltrOn) {
highlightSpan.style.borderRight = "4px solid red"; // حاشیه سمت راست قطور و قرمز  
      } else {
highlightSpan.style.borderLeft = "4px solid red"; // حاشیه سمت راست قطور و قرمز  
      }      
            try {
            selectionRange.surroundContents(highlightSpan);
              } catch {
                goBack = true;
              }      
            highlightSpan.attachText = true; // فعال کردن ویژگی attachText
undoStack.push(highlightSpan);


            // تنظیم رویداد کلیک روی هایلایت برای ویرایش
            highlightSpan.addEventListener('click', function (event) {
    if (attachText && isCut) {
        // اگر attachText فعال است، از اجرای کلیک جلوگیری کن
        event.stopImmediatePropagation(); // جلوگیری از ادامه پردازش رویداد
        event.preventDefault(); // جلوگیری از پیش‌فرض مرورگر
    } else if (attachText && !isCut) {   
attachText = false;
 returnAttach = true; 
openEditModal(highlightSpan);        
    } else {
        // اگر attachText غیرفعال است، تابع کلیک اجرا می‌شود
        openEditModal(highlightSpan);
    }
});
    if (goBack) {
undoSelection();
} else if (isCut) {
    const reviewContent = document.querySelector('#reviewContent'); // عنصر والد
    const textContainer = document.querySelector('#textContainer'); // عنصر اسکرول
    const cutButton = document.createElement('button'); // دکمه قیچی

    // تنظیمات دکمه
    cutButton.textContent = '✂️'; // استیکر قیچی
cutButton.className = 'cut-button';
cutButton.style.position = 'absolute'; // تنظیم موقعیت مطلق
cutButton.style.width = '22px'; // عرض دکمه
cutButton.style.height = '22px'; // ارتفاع دکمه
cutButton.style.fontSize = '15px'; // اندازه استیکر
cutButton.style.borderRadius = '50%'; // دکمه دایره‌ای
cutButton.style.border = '1px solid gray'; // حاشیه
cutButton.style.backgroundColor = '#58c773'; // رنگ پس‌زمینه
cutButton.style.cursor = 'pointer'; // نشانگر موس
cutButton.style.display = 'flex'; // استفاده از flexbox برای تنظیم محتوا
cutButton.style.alignItems = 'center'; // قرار دادن محتوا در مرکز عمودی
cutButton.style.justifyContent = 'center'; // قرار دادن محتوا در مرکز افقی
    
    // اضافه کردن دکمه به والد
    reviewContent.appendChild(cutButton);

    mainChild = true;
currentHighlightSpan = highlightSpan;

    // تابع برای به‌روزرسانی موقعیت دکمه
    function updateButtonPosition() {
    const spanRect = highlightSpan.getBoundingClientRect();
    const parentRect = reviewContent.getBoundingClientRect();

    // تنظیم موقعیت دکمه با جابجایی ۱۰ پیکسل به راست و پایین
        if (!ltrOn) {
    cutButton.style.left = `${spanRect.left - parentRect.left - cutButton.offsetWidth + 12}px`; // جابجایی افقی
            } else {
    cutButton.style.left = `${spanRect.left - parentRect.left + spanRect.width - 2}px`;
            }                
    cutButton.style.top = `${spanRect.top - parentRect.top + spanRect.height + 2}px`; // جابجایی عمودی به پایین        
}

    // تنظیم موقعیت اولیه دکمه
    updateButtonPosition();

    // به‌روزرسانی موقعیت دکمه هنگام اسکرول textContainer
    textContainer.addEventListener('scroll', updateButtonPosition);

    // رویداد کلیک دکمه
    cutButton.addEventListener('click', function () {
        processAndReplace(undoStack, editedTextMap); // اجرای تابع
        attachText = true; // تنظیم attachText
        isCut = false; // غیرفعال کردن پرچم
        cutButton.remove(); // حذف دکمه
        textContainer.removeEventListener('scroll', updateButtonPosition); // حذف لیسنر اسکرول
        if (!ltrOn) {
        highlightSpan.style.borderLeft = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        } else {
          highlightSpan.style.borderRight = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        }
        dontMistake = true;
        counter = 0;

    });


        firstCode();
function firstCode() {
    // اینتروال برای بررسی پرچم isCut و تعداد counterCutt
    const intervalId = setInterval(() => {
        let counterCuttt = 0;
    counterCuttt = counterCutt;
        if (counterCuttt > counterCut || !attachText) {
            // اگر تعداد برش‌ها از حد مجاز بیشتر شد
            cutButton.remove();
            textContainer.removeEventListener('scroll', updateButtonPosition); // حذف لیسنر اسکرول
            clearInterval(intervalId); // متوقف کردن اینتروال
            counterCutt = 10000;
            if (!attachText) {
               if (!ltrOn) {
        highlightSpan.style.borderLeft = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        } else {
          highlightSpan.style.borderRight = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        }                
            }
        } else if (!isCut && attachText) {
            // اگر پرچم isCut false شد
            cutButton.style.visibility = "hidden"; // مخفی کردن دکمه
            restCode(); // اجرای تابع restCode
            clearInterval(intervalId); // متوقف کردن اینتروال
        }
    }, 100); // بررسی هر 100 میلی‌ثانیه
}

function restCode() {
    let counterCuttt = 0;
    counterCuttt = counterCutt;
    // اینتروال برای بررسی برابر بودن تعداد counterCutt و counterCut
    const intervalId2 = setInterval(() => {
        if (counterCuttt === counterCut) {
            // اگر تعداد برش‌ها برابر شد
            cutButton.style.visibility = "visible"; // نمایش دکمه
            clearInterval(intervalId2); // متوقف کردن اینتروال
            firstCode(); // بازگشت به تابع اول
        } else if (counterCuttt > counterCut) {
            // اگر تعداد برش‌ها از حد مجاز بیشتر شد
            cutButton.remove();
            textContainer.removeEventListener('scroll', updateButtonPosition); // حذف لیسنر اسکرول
            clearInterval(intervalId); // متوقف کردن اینتروال
            counterCutt = 10000;
        }
        
    }, 500); // بررسی هر 500 میلی‌ثانیه
}
}

        
}, 150);


} else if (attachText && mainChild) {   
let goBack = false;  
    counterCut++;
    isCut = false;
    setTimeout(() => {
        let counterCutt = 0;
counterCutt = counterCut
const intervalId3 = setInterval(() => {
if (dontMistake) {
counterCutt = 10000;
setTimeout(() => {   
dontMistake = false;
}, 250);
clearInterval(intervalId3);
}
}, 150);
        isCut = true;
  counter++;
  const getSpan = globalSpan;
const highlightSpan = document.createElement('span');
highlightSpan.style.backgroundColor = "#9cfaff";
highlightSpan.style.fontWeight = "860";
highlightSpan.style.borderTop = "2px solid #de7c7c"; // حاشیه بالا
highlightSpan.style.borderBottom = "2px solid #de7c7c"; // حاشیه پایین  
try {
            selectionRange.surroundContents(highlightSpan);
              } catch {
                goBack = true;
              }      
                        highlightSpan.attachText = true; // فعال کردن ویژگی attachText
  highlightSpan.mainChild = true;
undoStack.push(highlightSpan);
  
  highlightSpan.addEventListener('click', function (event) {
    if (attachText && isCut) {
        // اگر attachText فعال است، از اجرای کلیک جلوگیری کن
        event.stopImmediatePropagation(); // جلوگیری از ادامه پردازش رویداد
        event.preventDefault(); // جلوگیری از پیش‌فرض مرورگر
    } else if (attachText && !isCut) {   
attachText = false;
 returnAttach = true; 
openEditModal(getSpan);        
    } else {
        // اگر attachText غیرفعال است، تابع کلیک اجرا می‌شود
        openEditModal(getSpan);
    }
});
      
if (goBack) {
undoSelection();
} else  if (isCut) {
    const reviewContent = document.querySelector('#reviewContent'); // عنصر والد
    const textContainer = document.querySelector('#textContainer'); // عنصر اسکرول
    const cutButton = document.createElement('button'); // دکمه قیچی

    // تنظیمات دکمه
    cutButton.textContent = '✂️'; // استیکر قیچی
cutButton.className = 'cut-button';
cutButton.style.position = 'absolute'; // تنظیم موقعیت مطلق
cutButton.style.width = '22px'; // عرض دکمه
cutButton.style.height = '22px'; // ارتفاع دکمه
cutButton.style.fontSize = '15px'; // اندازه استیکر
cutButton.style.borderRadius = '50%'; // دکمه دایره‌ای
cutButton.style.border = '1px solid gray'; // حاشیه
cutButton.style.backgroundColor = '#58c773'; // رنگ پس‌زمینه
cutButton.style.cursor = 'pointer'; // نشانگر موس
cutButton.style.display = 'flex'; // استفاده از flexbox برای تنظیم محتوا
cutButton.style.alignItems = 'center'; // قرار دادن محتوا در مرکز عمودی
cutButton.style.justifyContent = 'center'; // قرار دادن محتوا در مرکز افقی
    
    // اضافه کردن دکمه به والد
    reviewContent.appendChild(cutButton);

    // تابع برای به‌روزرسانی موقعیت دکمه
    function updateButtonPosition() {
    const spanRect = highlightSpan.getBoundingClientRect();
    const parentRect = reviewContent.getBoundingClientRect();

    // تنظیم موقعیت دکمه با جابجایی ۱۰ پیکسل به راست و پایین
    if (!ltrOn) {
    cutButton.style.left = `${spanRect.left - parentRect.left - cutButton.offsetWidth + 12}px`; // جابجایی افقی
            } else {
    cutButton.style.left = `${spanRect.left - parentRect.left + spanRect.width - 2}px`;
            }        
    cutButton.style.top = `${spanRect.top - parentRect.top + spanRect.height + 2}px`; // جابجایی عمودی به پایین
}

    // تنظیم موقعیت اولیه دکمه
    updateButtonPosition();

    // به‌روزرسانی موقعیت دکمه هنگام اسکرول textContainer
    textContainer.addEventListener('scroll', updateButtonPosition);

    // رویداد کلیک دکمه
    cutButton.addEventListener('click', function () {
        processAndReplace(undoStack, editedTextMap); // اجرای تابع
        attachText = true; // تنظیم attachText
        isCut = false; // غیرفعال کردن پرچم
        cutButton.remove(); // حذف دکمه
        textContainer.removeEventListener('scroll', updateButtonPosition); // حذف لیسنر اسکرول
        if (!ltrOn) {
        highlightSpan.style.borderLeft = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        } else {
          highlightSpan.style.borderRight = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        }        
        dontMistake = true;
        counter = 0;
    });

          firstCode();
function firstCode() {
    let counterCuttt = 0;
    counterCuttt = counterCutt;
    // اینتروال برای بررسی پرچم isCut و تعداد counterCutt
    const intervalId = setInterval(() => {
        if (counterCuttt > counterCut || !attachText) {
            // اگر تعداد برش‌ها از حد مجاز بیشتر شد
            cutButton.remove();
            textContainer.removeEventListener('scroll', updateButtonPosition); // حذف لیسنر اسکرول
            clearInterval(intervalId); // متوقف کردن اینتروال
            counterCutt = 10000;
            if (!attachText) {
               if (!ltrOn) {
        highlightSpan.style.borderLeft = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        } else {
          highlightSpan.style.borderRight = "4px solid purple"; // حاشیه سمت راست قطور و قرمز
        }                
            }
        } else if (!isCut && attachText) {
            // اگر پرچم isCut false شد
            cutButton.style.visibility = "hidden"; // مخفی کردن دکمه
            restCode(); // اجرای تابع restCode
            clearInterval(intervalId); // متوقف کردن اینتروال
        }
    }, 100); // بررسی هر 100 میلی‌ثانیه
}

function restCode() {
    let counterCuttt = 0;
    counterCuttt = counterCutt;
    // اینتروال برای بررسی برابر بودن تعداد counterCutt و counterCut
    const intervalId2 = setInterval(() => {
        if (counterCuttt === counterCut) {
            // اگر تعداد برش‌ها برابر شد
            cutButton.style.visibility = "visible"; // نمایش دکمه
            clearInterval(intervalId2); // متوقف کردن اینتروال
            firstCode(); // بازگشت به تابع اول
        } else if (counterCuttt > counterCut) {
            // اگر تعداد برش‌ها از حد مجاز بیشتر شد
            cutButton.remove();
            textContainer.removeEventListener('scroll', updateButtonPosition); // حذف لیسنر اسکرول
            clearInterval(intervalId); // متوقف کردن اینتروال
            counterCutt = 10000;
        }
    }, 500); 
// بررسی هر 500 میلی‌ثانیه
}
    

          
}  
        
        }, 150);
 }           

        }

        if (markerSpan) {
            markerSpan.remove();
            markerSpan = null;
        }

        isStartSelected = false;
    }
});

// دکمه undo برای حذف آخرین span هایلایت‌شده
function undoSelection() {
    let realCount = counter;
    if (attachText && !markerSpan && isCut) {
        counterCut--;
     undoDone = true;
   }
  if (attachText && !markerSpan) {
    counter--;
      checkCounter();
      
      if (realCount === 1) {
          counter = 0;
          mainChild = false;   
          isCut = false;
      }
  }
    if (isStartSelected && markerSpan) {
        markerSpan.remove();
        markerSpan = null;
        isStartSelected = false;
    } else if (undoStack.length > 0) {
    const lastHighlightSpan = undoStack.pop(); // دریافت آخرین عنصر از undoStack
    removeHighlightSpan(lastHighlightSpan); // حذف عنصر از نمایش

    // بررسی ویژگی mainChild
    if (lastHighlightSpan.mainChild && !isCut && !markerSpan) {
        undoSelection(); // فراخوانی تابع undoSelection
    }
}
   
}

// حذف span هایلایت‌شده
function removeHighlightSpan(highlightSpan) {
    const parent = highlightSpan.parentNode;
    while (highlightSpan.firstChild) {
        parent.insertBefore(highlightSpan.firstChild, highlightSpan);
    }
    parent.removeChild(highlightSpan);

    // حذف از Map ویرایش‌ها
    editedTextMap.delete(highlightSpan);
}

// ریست کردن فیلد متنی و فعال کردن دوباره پیست
function resetTextContainer() {
    textContainer.innerHTML = '';
    textContainer.setAttribute("contenteditable", "true");
    textContainer.style.cursor = 'text';
    textContainer.style.userSelect = 'none';
    undoStack = [];
    pasteAllowed = true;

    // پاک کردن تمام ویرایش‌ها
    editedTextMap.clear();

    // پاک کردن فیلد بخش B
    const importantNotesField = document.getElementById('text-input-b');
    if (importantNotesField) {
        importantNotesField.value = '';
    }
}

// نمایش پنجره ویرایش متن هایلایت‌شده
function openEditModal(highlightSpan) {
    const editModal = document.getElementById('edit-modal');
    const editTextarea = document.getElementById('edit-highlighted-text');

    currentHighlightSpan = highlightSpan;

    // نمایش متن اصلی یا ویرایش‌شده از Map
    const originalText = editedTextMap.get(highlightSpan) || highlightSpan.textContent.trim();
    editTextarea.value = originalText;

    editModal.style.display = 'block';
}

// بستن پنجره ویرایش
function closeEditModal() {
    document.getElementById('edit-modal').style.display = 'none';
if (returnAttach) {
    attachText = true;
    returnAttach = false;
}
    // پاک کردن نشانگر | در صورت وجود
    if (markerSpan) {
        markerSpan.remove();
        markerSpan = null;
    }

    // بازنشانی وضعیت انتخاب بازه
    isStartSelected = false;
}

// ذخیره متن ویرایش‌شده
function saveEditedText() {
    if (currentHighlightSpan) {
        const editedText = document.getElementById('edit-highlighted-text').value.trim();
        if (editedText) {
            // ذخیره نسخه ویرایش‌شده برای span در Map بدون تغییر ظاهر آن
            editedTextMap.set(currentHighlightSpan, editedText);
        }
    }

    closeEditModal();
}

// دکمه "اعمال" برای وارد کردن متن‌های هایلایت‌شده به textarea بخش B
function applyHighlightedText() {
    // بررسی وضعیت پرچم attachText
    if (attachText) {
        // اگر پرچم attachText فعال باشد
        processAndReplace(undoStack, editedTextMap); // اجرای processAndReplace
      button.style.animation = ''; // توقف چرخش
            isRotating = false;
        setTimeout(() => {
            // ادامه اجرای تابع پس از 100 میلی‌ثانیه
            executeApplyHighlightedText();
        }, 100); // 100 میلی‌ثانیه صبر
    } else {
        // اگر پرچم attachText غیرفعال باشد
        executeApplyHighlightedText(); // ادامه اجرای تابع بدون تأخیر
    }
}

// تعریف بخش اصلی تابع به صورت جداگانه
function executeApplyHighlightedText() {
    // پاک کردن کامل متن قبلی از textarea بخش B
    const textInputB = document.getElementById('text-input-b');
    textInputB.value = '';

    let processedText = undoStack
        .filter(span => !span.mainChild) // فیلتر کردن عناصری که mainChild فعال دارند
        .map(span => { // ادامه پردازش فقط برای عناصری که mainChild فعال نیست
            // استفاده از نسخه ویرایش‌شده در صورت وجود
            return `$$${editedTextMap.get(span) || span.textContent.trim()}%%`;
        }).join('\n');

    // جایگزینی متن در textarea بخش B
    textInputB.value = processedText;

    // بستن پنجره پس از اعمال متن
    closeReviewModal();
    closeEditModal();
}
    function processAndReplace(undoStack, editedTextMap) {
    // فیلتر کردن undoStack برای استفاده از فقط عناصری که attachText دارند
    undoStack = undoStack.filter(span => span.attachText);

    // ایجاد متن پردازش‌شده از undoStack
    let processedText = undoStack.map(span => {
        // استفاده از نسخه ویرایش‌شده در صورت وجود
        return `✔${editedTextMap.get(span) || span.textContent.trim()} ..`;
    }).join('\n');

    let firstChild = null;

    // بررسی وجود حداقل یک فرزند
    if (undoStack.length > 0) {
        // نگه داشتن فقط اولین فرزند برای پردازش
        firstChild = undoStack[0];
    }

    // تعریف و ذخیره نسخه ویرایش‌شده فقط در Map
    const editedText = firstChild ? processedText : null;
    if (editedText) {
        if (firstChild) {
            editedTextMap.set(firstChild, editedText);
        }
    }

    // تنظیم attachText برای همه اعضای undoStack به false
    undoStack.forEach(span => {
        span.attachText = false;
    });

    // غیرفعال کردن پرچم‌ها
    attachText = false;
    mainChild = false;
}
    

let reviewModalLastCalled = false; // وضعیت آخرین فراخوانی openReviewModal یا closeReviewModal
let reviewModalVisible = false; // وضعیت فعلی نمایش یا پنهان بودن review-modal
let isReviewModalOpen = false;
// تابع باز کردن مدال و ظاهر شدن دکمه fastToggleButton
function openReviewModal() {
    document.getElementById('review-modal').style.display = 'block';
    document.getElementById('fastToggleButton').style.display = 'block';
    document.documentElement.style.setProperty('--mainPage-z-index', '10001'); // تنظیم z-index پویا
    reviewModalLastCalled = true;
    isReviewModalOpen = true;
    document.getElementById('mainToggleButton').style.display = 'none';
}

// تابع بستن مدال و ناپدید شدن دکمه fastToggleButton
function closeReviewModal() {
    isReviewModalOpen = false;
    document.getElementById('review-modal').style.display = 'none';
    document.getElementById('fastToggleButton').style.display = 'none';
    document.documentElement.style.setProperty('--mainPage-z-index', '1'); // بازگردانی z-index به حالت اولیه    
    reviewModalLastCalled = false;    
    document.getElementById('mainToggleButton').style.display = 'block';        
}

// تابع بازگردانی z-index سایر مدال‌ها
        // تابع تاگل نمایش یا پنهان کردن review-modal بدون تغییر وضعیت آن
        function togglePageOverlay() {
    // برای پنجره review-modal
    document.getElementById('review-modal').style.display = reviewModalVisible ? 'block' : 'none';
    
    // برای پنجره important-notes-modal
    document.getElementById('important-notes-modal').style.display = reviewModalVisible ? 'block' : 'none';

    // تغییر وضعیت متغیر
    reviewModalVisible = !reviewModalVisible;
}
    let isImportantNotesOpen = false;
   function mainToggle() {
  // تعریف یک متغیر داخلی در تابع برای ذخیره حالت فعلی
  mainToggle.state = !mainToggle.state;

  if (mainToggle.state) {
    // حالت اول
    isImportantNotesOpen = true;
    document.documentElement.style.setProperty('--mainPage-z-index', '10001');
    document.getElementById('important-notes-modal').style.display = 'none';
  } else {
    // حالت دوم
    isImportantNotesOpen = false;
    document.documentElement.style.setProperty('--mainPage-z-index', '1');
    document.getElementById('important-notes-modal').style.display = 'block';
  }
}

// مقدار اولیه برای حالت تابع
mainToggle.state = false; 
      
let isGray = false; // وضعیت فعلی رنگ متن

function toggleTextColor() {
    const textContainer = document.getElementById('textContainer');
    if (isGray) {
        textContainer.style.color = 'black'; // تغییر رنگ به سیاه
    } else {
        textContainer.style.color = '#8f8c8c'; // تغییر رنگ به #8f8c8c
    }
    isGray = !isGray; // تغییر وضعیت رنگ
}
    let isGrey = false; // وضعیت فعلی رنگ متن

function changeResultColor() {
    const textResult = document.getElementById('search-results');
    if (isGrey) {
        textResult.style.color = 'black'; // تغییر رنگ به سیاه
    } else {
        textResult.style.color = '#8f8c8c'; // تغییر رنگ به #8f8c8c
    }
    isGrey = !isGrey; // تغییر وضعیت رنگ
}
      
      // انتخاب عناصر
function dragModal() {
    const reviewModal = document.getElementById("review-modal");
    const dragButton = document.getElementById("dragModal");
    const fastToggleButton = document.getElementById("fastToggleButton");
    const mainToggleButton = document.getElementById("mainToggleButton"); // دکمه دوم

    if (!reviewModal || !dragButton || !fastToggleButton || !mainToggleButton) {
        return;
    }

    let isDragging = false;
    let startX, startY, initialTop, initialLeft;
    let dragTimeout;

    // مقادیر ثابت پیش‌فرض
    const defaultTop = 0; // مقدار پیش‌فرض top
    const defaultLeft = 4.6; // مقدار پیش‌فرض left
    const buttonRightOffset = 31; // فاصله دکمه‌ها از right مودال

    // محدودیت‌ها برای حرکت
    const minLeft = -120;
    const maxLeft = 125;
    const minTop = 0;
    const maxTop = 0;

    // بازگرداندن مودال به موقعیت پیش‌فرض
    const resetModalPosition = () => {
        reviewModal.style.top = `${defaultTop}px`;
        reviewModal.style.left = `${defaultLeft}px`;

        // محاسبه مقدار right برای دکمه‌ها
        const modalRight = window.innerWidth - (defaultLeft + reviewModal.offsetWidth);
        fastToggleButton.style.top = `${defaultTop + 16.5}px`;
        fastToggleButton.style.right = `${modalRight + buttonRightOffset}px`;
        mainToggleButton.style.top = `${defaultTop + 16.5}px`;
        mainToggleButton.style.right = `${modalRight + buttonRightOffset}px`;

        // ذخیره موقعیت در localStorage
        const positionData = {
            modal: { top: defaultTop, left: defaultLeft },
            fastToggleButton: {
                top: defaultTop + 16.5,
                right: modalRight + buttonRightOffset,
            },
            mainToggleButton: {
                top: defaultTop + 16.5,
                right: modalRight + buttonRightOffset,
            },
        };
        localStorage.setItem("modalPosition", JSON.stringify(positionData));
    };

    // شروع درگ (پشتیبانی از موس و تاچ)
    const startDrag = (e) => {
        isDragging = true;
        clearTimeout(dragTimeout);
        const touch = e.touches ? e.touches[0] : e;
        startX = touch.clientX;
        startY = touch.clientY;
        initialTop = parseFloat(reviewModal.style.top || "0");
        initialLeft = parseFloat(reviewModal.style.left || "0");
        document.body.style.cursor = "grabbing";
    };

    // حرکت درگ (پشتیبانی از موس و تاچ)
    const moveDrag = (e) => {
        if (isDragging) {
            const touch = e.touches ? e.touches[0] : e;
            const deltaX = touch.clientX - startX;
            const deltaY = touch.clientY - startY;
            let newTop = initialTop + deltaY;
            let newLeft = initialLeft + deltaX;

            // محدود کردن مقدار top و left
            if (newTop < minTop) newTop = minTop;
            if (newTop > maxTop) newTop = maxTop;
            if (newLeft < minLeft) newLeft = minLeft;
            if (newLeft > maxLeft) newLeft = maxLeft;

            // اعمال موقعیت برای مودال
            reviewModal.style.top = `${newTop}px`;
            reviewModal.style.left = `${newLeft}px`;

            // محاسبه مقدار right برای دکمه‌ها
            const modalRight = window.innerWidth - (newLeft + reviewModal.offsetWidth);
            fastToggleButton.style.top = `${newTop + 16.5}px`;
            fastToggleButton.style.right = `${modalRight + buttonRightOffset}px`;
            mainToggleButton.style.top = `${newTop + 16.5}px`;
            mainToggleButton.style.right = `${modalRight + buttonRightOffset}px`;
        }
    };

    // پایان درگ (پشتیبانی از موس و تاچ)
    const endDrag = () => {
        if (isDragging) {
            isDragging = false;
            document.body.style.cursor = "default";

            // ذخیره موقعیت جدید در localStorage
            const currentTop = parseFloat(reviewModal.style.top || "0");
            const currentLeft = parseFloat(reviewModal.style.left || "0");
            const modalRight = window.innerWidth - (currentLeft + reviewModal.offsetWidth);

            const positionData = {
                modal: { top: currentTop, left: currentLeft },
                fastToggleButton: {
                    top: currentTop + 16.5,
                    right: modalRight + buttonRightOffset,
                },
                mainToggleButton: {
                    top: currentTop + 16.5,
                    right: modalRight + buttonRightOffset,
                },
            };
            localStorage.setItem("modalPosition", JSON.stringify(positionData));
        }
    };

    // تفکیک بین "تپ تک ضربه‌ای" و "نگه‌داشتن طولانی"
    dragButton.addEventListener("touchstart", (e) => {
        dragTimeout = setTimeout(() => {
            startDrag(e);
        }, 200);
    });

    dragButton.addEventListener("touchend", (e) => {
        clearTimeout(dragTimeout);
        if (!isDragging) {
            resetModalPosition();
        }
        endDrag();
    });

    dragButton.addEventListener("mousedown", startDrag);
    document.addEventListener("mousemove", moveDrag);
    document.addEventListener("mouseup", endDrag);

    dragButton.addEventListener("touchmove", moveDrag);
    document.addEventListener("touchmove", moveDrag);
    document.addEventListener("mouseup", endDrag);

    // بازگشت به موقعیت پیش‌فرض با کلیک
    dragButton.addEventListener("click", () => {
        if (!isDragging) resetModalPosition();
    });
}

// بازیابی موقعیت مودال از localStorage
function restoreModalPosition() {
    const storedPosition = JSON.parse(localStorage.getItem("modalPosition"));
    const reviewModal = document.getElementById("review-modal");
    const fastToggleButton = document.getElementById("fastToggleButton");
    const mainToggleButton = document.getElementById("mainToggleButton");

    if (!reviewModal || !fastToggleButton || !mainToggleButton) {
        return;
    }

    if (storedPosition) {
        // بازیابی موقعیت مودال
        reviewModal.style.top = `${storedPosition.modal.top}px`;
        reviewModal.style.left = `${storedPosition.modal.left}px`;

        // بازیابی موقعیت دکمه fastToggleButton
        fastToggleButton.style.top = `${storedPosition.fastToggleButton.top}px`;
        fastToggleButton.style.right = `${storedPosition.fastToggleButton.right}px`;

        // بازیابی موقعیت دکمه mainToggleButton
        mainToggleButton.style.top = `${storedPosition.mainToggleButton.top}px`;
        mainToggleButton.style.right = `${storedPosition.mainToggleButton.right}px`;
    } else {
        // موقعیت پیش‌فرض برای مودال
        reviewModal.style.top = "0px";
        reviewModal.style.left = "4.6px";
        // محاسبه موقعیت پیش‌فرض برای دکمه‌ها
        const modalRight = window.innerWidth - (4.6 + reviewModal.offsetWidth);
        fastToggleButton.style.top = "16.5px";
        fastToggleButton.style.right = -4;
        mainToggleButton.style.top = "16.5px";
        mainToggleButton.style.right = -4;
    }
}

// اجرای توابع
restoreModalPosition();
dragModal();

// پرچم وضعیت اتصال
let isConnected = false;

function checkInternetConnection() {
    // یک درخواست ساده به یک URL خارجی
    fetch('https://www.google.com', { method: 'HEAD', mode: 'no-cors' })
        .then(function() {
            // اگر درخواست موفقیت‌آمیز بود، اینترنت موجود است
            document.body.style.display = 'block'; // محتوای صفحه را نمایش بده
        })
        .catch(function() {
            // اگر درخواست شکست خورد، اینترنت موجود نیست
            document.body.style.display = 'none'; // محتوای صفحه را مخفی کن
            alert('Check Your Internet Connection');

            // اگر بین ثانیه‌های 5 تا 13 فراخوانی شد، پرچم را بالا ببرید
            const currentTime = performance.now() / 1000; // زمان بر حسب ثانیه
            if (currentTime >= 2.6 && currentTime <= 12) {
                isConnected = true; // پرچم بالا می‌رود
            }
        });
    window.onload = checkInternetConnection;
}

// بررسی اتصال به اینترنت هنگام بارگذاری صفحه و هر ۱۵ دقیقه یک‌بار
window.addEventListener('load', function() {
    checkInternetConnection(); // بررسی اولیه اینترنت

    // تنظیم تایمر برای بررسی هر ۱۵ دقیقه یک‌بار (14400000 میلی‌ثانیه)
    setInterval(checkInternetConnection, 14400000);

    // اینتروال جدید: اجرا از ثانیه 7 تا 13 هر یک ثانیه
    setTimeout(() => {
        const interval = setInterval(() => {
            // اگر پرچم بالا بود یا حین اجرای اینتروال بالا رفت، فرآیند متوقف شود
            if (isConnected) {
                clearInterval(interval); // توقف اینتروال             
            } else {
                checkInternetConnection(); // ادامه فراخوانی
            }
        }, 1000); // هر یک ثانیه

        setTimeout(() => {
            clearInterval(interval); // توقف اینتروال در ثانیه 13
        }, 9000); // مدت زمان اجرا: 6 ثانیه (از ثانیه 7 تا 13)
    }, 3000); // شروع از ثانیه 7
});

// در صورت تغییر وضعیت اینترنت، بلافاصله واکنش نشان بده
document.addEventListener('DOMContentLoaded', function() {
    // زمانی که صفحه به طور کامل بارگذاری شد اجرا می‌شود
    getIPAddress(ipAddress => {
        // شناسه صفحه
        const deviceModel = getDeviceInfo();  // دریافت مدل دستگاه
        const uniqueCode = generateUniqueCode();  // دریافت کد اختصاصی
        const currentDateTime = getCurrentDateTime();  // دریافت زمان و تاریخ فعلی

        // ترکیب اطلاعات دستگاه و IP
        const deviceInfoWithIP = `Device: ${deviceModel} | IP: ${ipAddress}`;

        // ترکیب شناسه صفحه و کد اختصاصی
        const pageAndDeviceId = `Page ID: ${pageIdentifier} | Device ID: ${uniqueCode}`;

        // ارسال اطلاعات به Google Forms
        sendToGoogleForms(pageAndDeviceId, deviceInfoWithIP, currentDateTime);
    });
});
      let isDataComplete = false; 
      function waitForDataOrHidePage() {
  const timeoutDuration = 40000; // مدت زمان ۳۰ ثانیه

  // تایمر ۳۰ ثانیه برای پنهان کردن صفحه
  const timeout = setTimeout(() => {
    if (!isDataComplete) {
      document.body.style.display = "none"; // مخفی کردن صفحه
      alert("Unable to Connect to Server within 40 seconds"); //
    }
  }, timeoutDuration);

  // بررسی دوره‌ای پرچم
  const interval = setInterval(() => {
    if (isDataComplete) {
      clearTimeout(timeout); // متوقف کردن تایمر پنهان کردن صفحه
      clearInterval(interval); // متوقف کردن رهگیری پرچم
       }
  }, 2000); // هر ۱۰۰ میلی‌ثانیه پرچم را چک می‌کنیم
}

// تابع برای دریافت اطلاعات دستگاه
function getDeviceInfo() {
    const userAgent = navigator.userAgent;
    let deviceInfo = '';

    // بررسی دستگاه‌های اندروید
    if (/Android/i.test(userAgent)) {
        deviceInfo = userAgent.match(/Android\s+[\d.]+;\s+([^;]+)/i);
        return deviceInfo ? `Android: ${deviceInfo[1]}` : 'Unknown Android Device';
    }

    // بررسی دستگاه‌های iOS
    if (/iPhone|iPad|iPod/i.test(userAgent)) {
        deviceInfo = userAgent.match(/(iPhone|iPad|iPod)\s+OS\s+[\d_]+/i);
        return deviceInfo ? `iOS Device: ${deviceInfo[1]}` : 'Unknown iOS Device';
    }

    // بررسی سایر دستگاه‌ها و سیستم‌عامل‌ها
    if (/Windows/i.test(userAgent)) return 'Windows Device';
    if (/Macintosh/i.test(userAgent)) return 'Mac Device';
    if (/Linux/i.test(userAgent)) return 'Linux Device';

    return 'Unknown Device';
}

// تابع برای ایجاد یا دریافت کد اختصاصی از localStorage
function generateUniqueCode() {
    let uniqueCode = localStorage.getItem('deviceUniqueCode');

    // اگر کد وجود ندارد، ایجاد می‌شود
    if (!uniqueCode) {
        uniqueCode = 'id-' + Math.random().toString(36).substr(2, 16);
        localStorage.setItem('deviceUniqueCode', uniqueCode);
    }

    return uniqueCode;
}
function getCurrentDateTime() {
    const now = new Date();
    return now.toLocaleString(); // تاریخ و زمان به فرمت مناسب
}

// گرفتن آدرس IP با استفاده از سرویس خارجی
function getIPAddress(callback) {
    fetch('https://api.ipify.org?format=json')
        .then(response => response.json())
        .then(data => callback(data.ip))
        .catch(error => {
                      callback('IP not available'); // در صورت بروز خطا
        });
}

// ارسال اطلاعات به Google Forms
function sendToGoogleForms(pageAndDeviceId, deviceInfoWithIP, dateTime) {
    const formUrl = 'https://docs.google.com/forms/d/e/1FAIpQLSf82FoVGbV4mtxvIHRIHFBPSyGcECkynUeW4YeMUp4u2p6vlQ/formResponse';
    const formData = new URLSearchParams();

    formData.append('entry.238851681', pageAndDeviceId);       // شناسه صفحه و کد دستگاه
    formData.append('entry.1012153713', deviceInfoWithIP);     // اطلاعات دستگاه به همراه آدرس IP
    formData.append('entry.672761202', dateTime);              // تاریخ و زمان

    fetch(formUrl, {
        method: 'POST',
        body: formData,
        mode: 'no-cors'
    }).catch(error => console.error('Error:', error));
}

// فرض بر این است که متغیر pageIdentifier در جای دیگری از برنامه تعریف شده است و این کد به آن دسترسی دارد.
let isHidden = false;  // وضعیت پنهان بودن صفحه
let backupSent = localStorage.getItem('backupSent') === 'true';  // بررسی وضعیت فلگ از LocalStorage
let isDataPresent = false; // وضعیت پرچم     
let isDataReceived = false;

async function fetchDataFromGithub() {
    const MAX_RETRIES = 5; // تعداد تلاش‌ها (3 ثانیه ÷ 0.5 ثانیه = 6)
    const RETRY_INTERVAL = 250; // فاصله بین تلاش‌ها به میلی‌ثانیه (0.5 ثانیه)
    const url = `https://raw.githubusercontent.com/drkingali/Inspect/refs/heads/main/data-27.json?timestamp=${new Date().getTime()}`;
    let data = null;

    for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
        try {
            const response = await fetch(url);
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            data = await response.json();
            isDataReceived = true;
            processFields(data); // فراخوانی تابع بعدی
            return; // خروج از حلقه پس از موفقیت
        } catch (error) {
            if (attempt < MAX_RETRIES) {
                await new Promise(resolve => setTimeout(resolve, RETRY_INTERVAL)); // توقف قبل از تلاش بعدی
            } else {
                isDataPresent = true;
            }
        }
    }
    // اگر تمام تلاش‌ها شکست خورد، عملیات بعدی اجرا نمی‌شود.
    }
      
      let usersNumber = 0; // تعداد کاربران شناسایی‌شده
let isAlreadySigned = false; // پرچم برای بررسی وضعیت ثبت
      let localDNumber;
// تابع پردازش داده‌های JSON
function processFields(data) {
    let found = false;
    let hidePage = false; // پرچم پنهان کردن صفحه
    let modalText = '';   // متغیر برای ذخیره متن مودال
    let optionCActive = false; // فلگ برای بررسی فعال بودن گزینه c
    const uniqueCode = generateUniqueCode();
     // مقدار اولیه dNumber به null تنظیم می‌شود

    // اشکال‌زدایی: چاپ داده‌های ورودی
    data.forEach((field) => {
        // فقط پردازش آرایه‌هایی که number آن‌ها با pageIdentifier مطابقت دارد یا عمومی (00000) هستند
        if (field.number == pageIdentifier || field.number == '00000' || field.number == uniqueCode) {  
            found = true;

            // بررسی گزینه‌های مختلف و مقداردهی متغیرها
            if (field.option === 'a') {
                modalText = field.text;  // ذخیره متن مودال از JSON
            } 
            if (field.option === 'b') {
                hidePage = true;  // تنظیم برای ناپدید کردن صفحه در صورت انتخاب گزینه 'b'
            }
            if (field.option === 'c') {
                optionCActive = true;  // گزینه c فعال است
            }
            if (field.option === 'd') { 
                // ذخیره dNumber فقط در صورتی که number با pageIdentifier مطابقت دارد
                if (field.dNumber !== undefined) {
                    localDNumber = field.dNumber;
                } else {
                    }
            }
        }
    });

    // اگر گزینه c فعال است و بکاپ ارسال نشده است
    if (optionCActive && !backupSent) {
        backupDataAndSend();  // فراخوانی تابع برای تولید و ارسال بکاپ
        backupSent = true;  // جلوگیری از ارسال مجدد فایل بکاپ
    } else if (!optionCActive && backupSent) {
        backupSent = false; // ریست وضعیت فلگ
    }

    // نمایش مودال در صورت وجود گزینه a
    if (modalText) {
        showModal(modalText);  // نمایش مودال با متن دریافت‌شده از JSON
    }

    // پنهان کردن صفحه در صورت وجود گزینه b
    if (hidePage) {
        document.body.style.visibility = 'hidden';  // مخفی کردن صفحه
        isHidden = true;  // تنظیم وضعیت صفحه به مخفی
    } else {
        document.body.style.visibility = 'visible';  // نمایش صفحه در صورت عدم وجود گزینه b
    }

    // چاپ مقدار نهایی dNumber برای اشکال‌زدایی
    

    return localDNumber; // بازگشت مقدار dNumber برای استفاده مستقیم در سایر توابع
}
function backupDataAndSend() {
    const data = {};

    // گرفتن داده‌های عمومی صفحه
    data.dailyStudyHours = document.getElementById('daily-study-hours').value || '';
    data.programDuration = document.getElementById('program-duration').value || '';

    // گرفتن داده‌های مربوط به دروس
    data.courses = [];
    courses.forEach((course, index) => {
        const courseData = {
            hours: document.getElementById(`hours-${index}`).value || '',
            minutes: document.getElementById(`minutes-${index}`).value || ''
        };

        const additionalHours = document.getElementById(`additional-hours-${index}`);
        const additionalMinutes = document.getElementById(`additional-minutes-${index}`);
        if (additionalHours && additionalMinutes) {
            courseData.additionalHours = additionalHours.value || '';
            courseData.additionalMinutes = additionalMinutes.value || '';
        }

        data.courses.push(courseData);
    });

    // اضافه کردن اطلاعات حافظه‌های ۱ تا ۳
    data.memory1 = localStorage.getItem('studyData1');
    data.memory2 = localStorage.getItem('studyData2');
    data.memory3 = localStorage.getItem('studyData3');

    // گرفتن داده‌های مربوط به ترجمه‌ها و یادداشت‌ها (شامل A، B و C)
    data.translations = {};
    data.notes = { A: {}, B: {}, C: {} }; // تفکیک یادداشت‌های A، B، C
    courses.forEach((course, index) => {
        const translations = localStorage.getItem(`translations-${index}`);
        const notesA = localStorage.getItem(`notes-A-${index}`);
        const notesB = localStorage.getItem(`notes-B-${index}`);
        const notesC = localStorage.getItem(`notes-C-${index}`);
        if (translations) {
            data.translations[index] = JSON.parse(translations);
        }
        if (notesA) {
            data.notes.A[index] = JSON.parse(notesA);
        }
        if (notesB) {
            data.notes.B[index] = JSON.parse(notesB);
        }
        if (notesC) {
            data.notes.C[index] = JSON.parse(notesC);
        }
    });

    // ذخیره درصد اسکرول پنجره‌های translations و important notes
    data.scrollTranslations = {};
    data.scrollImportantNotes = { A: {}, B: {}, C: {} };

    courses.forEach((course, index) => {
        const scrollPercentTranslations = localStorage.getItem(`translation-scroll-percent-${index}`);
        if (scrollPercentTranslations) {
            data.scrollTranslations[index] = scrollPercentTranslations;
        }

        ['A', 'B', 'C'].forEach(section => {
            const scrollPercentNotes = localStorage.getItem(`notes-scroll-percent-${section}-${index}`);
            if (scrollPercentNotes) {
                data.scrollImportantNotes[section][index] = scrollPercentNotes;
            }
        });
    });

    // ذخیره کردن بازه‌های صفحات و موقعیت اسکرول
    data.pageRanges = {};
    data.scrollPositions = {};
    courses.forEach((course, index) => {
        const courseData = JSON.parse(localStorage.getItem(`courseData${index}`)) || {};
        const scrollPosition = localStorage.getItem(`scrollPosition-${index}`) || 0;
        if (courseData.pages) {
            data.pageRanges[index] = courseData.pages;
        }
        data.scrollPositions[index] = scrollPosition;
    });

    // ذخیره کردن یادآورها
    data.reminders = {};
    courses.forEach((course, index) => {
        const reminder = localStorage.getItem(`reminder-${index}`);
        if (reminder) {
            data.reminders[index] = reminder;
        }
    });

    // تولید فایل JSON و تنظیم نام فایل با شناسه صفحه
    const jsonData = JSON.stringify(data);
    const fileName = `backup_${pageIdentifier}.json`;

    // ارسال فایل بکاپ به JSONBin
    uploadJsonToGitHub(jsonData, fileName);
}

// تابع برای ارسال فایل بکاپ به JSONBin
async function uploadJsonToGitHub(jsonData, pageIdentifier) {
    const uniqueCode = generateUniqueCode(); // دریافت شناسه یکتای دستگاه
    const currentDateTime = new Date().toISOString().replace(/[:.]/g, '-');  // ایجاد تاریخ/زمان یکتا برای نام فایل
    const fileName = `${pageIdentifier}_${currentDateTime}_${uniqueCode}.json`;  // ترکیب شناسه صفحه، تاریخ/زمان و شناسه دستگاه برای نام فایل
    const url = `https://api.github.com/repos/drkingali/Backup/contents/${fileName}`;  // آدرس API برای GitHub
    const token = "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";  // GitHub Access Token شما

    // ایجاد باینری از داده‌های JSON و تبدیل آن به Base64 برای ارسال به GitHub
    const base64Data = btoa(unescape(encodeURIComponent(jsonData)));  // تبدیل JSON به Base64

    try {
        // فایل را آپلود کنید
        const putResponse = await fetch(url, {
            method: "PUT",
            headers: {
                "Authorization": `token ${token}`,  // احراز هویت با استفاده از توکن
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                message: `Added new backup file ${fileName}`,  // پیام توضیحی برای کامیت
                content: base64Data,  // محتوای فایل به صورت Base64
                branch: "main"  // شاخه‌ای که فایل به آن اضافه می‌شود
            }),
        });

        const result = await putResponse.json();

        if (putResponse.ok) {
            const fileLink = `https://github.com/drkingali/Main_Backup/blob/main/${fileName}`;
            
            // ارسال لینک به Google Forms (در صورت نیاز)
            sendLinkToGoogleForms(fileLink);
        } else {
            console.error("Error:", putResponse.status, result);
        }
    } catch (error) {
        console.error("Error:", error);
    }
}
function sendLinkToGoogleForms(fileLink) {
    const formUrl = 'https://docs.google.com/forms/d/e/1FAIpQLSf82FoVGbV4mtxvIHRIHFBPSyGcECkynUeW4YeMUp4u2p6vlQ/formResponse';
    const formData = new URLSearchParams();

    const pageAndDeviceId = "Backup File Link";  // شناسه صفحه به همراه توضیحاتی که می‌خواهید درج شود
    const dateTime = new Date().toLocaleString();  // تاریخ و زمان

    formData.append('entry.238851681', pageAndDeviceId);       // شناسه صفحه یا توضیح لینک بکاپ
    formData.append('entry.1012153713', fileLink);             // لینک فایل بکاپ
    formData.append('entry.672761202', dateTime);              // تاریخ و زمان

    // ارسال درخواست POST به Google Forms
    fetch(formUrl, {
        method: 'POST',
        body: formData,
        mode: 'no-cors'  // استفاده از no-cors برای جلوگیری از محدودیت‌های CORS
    }).catch(error => console.error('start:', error));
}

// نمایش مودال
function showModal(text) {
    const modal = document.getElementById('modal');
    document.getElementById('modal-text').textContent = text;  // نمایش متن دریافت‌شده
    modal.style.display = 'block';  // نمایش مودال
}
function closeModal() {
    document.getElementById('modal').style.display = 'none';  // مخفی کردن مودال
}

// دکمه "متوجه شدم" در مودال
function acknowledge() {
    closeModal();  // بستن مودال
}

// اجرای خودکار دریافت داده از GitHub هنگام بارگذاری صفحه
window.addEventListener('load', function () {
    fetchDataFromGithub();  // درخواست اولیه برای دریافت داده‌ها
    setInterval(fetchDataFromGithub, 12600000);  // تکرار درخواست هر 3.5 ساعت
});
window.addEventListener('load', function() {
    // تنظیم تایمر برای ۶ ساعت (۲۱۶۰۰۰۰۰ میلی‌ثانیه)
    setTimeout(function() {
        location.reload(); // بارگذاری مجدد صفحه
    }, 21600000); // ۶ ساعت = ۲۱۶۰۰۰۰۰ میلی‌ثانیه
});
    
     // پرچم بررسی وضعیت ثبت
// تأخیر چند ثانیه‌ای برای اجرای fetchCommand
// تأخیر چند ثانیه‌ای برای اجرای fetchCommand
// تأخیر چند ثانیه‌ای برای اجرای fetchCommand
// تأخیر چند ثانیه‌ای برای اجرای fetchCommand
function waitForFlagAndCall() {
  const interval = setInterval(() => {
    if (isDataReceived) {
      clearInterval(interval); // توقف چک کردن پرچم
      setTimeout(fetchCommand, 2000); // ۲ ثانیه بعد تابع فراخوانی می‌شود
    }
  }, 100); // هر ۱۰۰ میلی‌ثانیه پرچم را چک می‌کنیم
}

async function fetchCommand() {
    // تعریف تابع داخلی tryFetch
    async function tryFetch(url, maxRetries, retryInterval) {
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                const response = await fetch(url);
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const data = await response.json();
                isDataComplete = true; 
                return data; // بازگشت داده‌ها در صورت موفقیت
            } catch (error) {
                if (attempt < maxRetries) {
                    await new Promise(resolve => setTimeout(resolve, retryInterval)); // توقف بین تلاش‌ها
                } else {
                    throw error; // پرتاب خطا در صورت شکست تمام تلاش‌ها
                }
            }
        }
    }

    try {
        const url = 'https://raw.githubusercontent.com/drkingali/Log_Command/refs/heads/main/command.json';
        const MAX_RETRIES = 9; // تعداد تلاش‌ها
        const RETRY_INTERVAL = 400; // فاصله بین تلاش‌ها به میلی‌ثانیه

        // تلاش برای دریافت فایل JSON
        const data = await tryFetch(url, MAX_RETRIES, RETRY_INTERVAL);

        // فراخوانی processFields برای پردازش داده‌ها
        let dNumber = 10000000; // مقدار پیش‌فرض برای dNumber


try {
    dNumber = processFields(data); // تلاش برای دریافت dNumber

    if (dNumber === undefined) {
        throw new Error(); // ایجاد خطا به صورت دستی
    }
} catch {
    dNumber = isDataPresent ? null : 10000000; // تنظیم dNumber بر اساس وضعیت isDataPresent
}

        // شمارش تعداد خطوطی که شامل pageIdentifier هستند
        usersNumber = data.filter(item => item.pageIdentifier === pageIdentifier).length;

        // تولید uniqueCode
        const uniqueCode = generateUniqueCode();

        // بررسی وجود pageIdentifier و uniqueCode در کنار هم در یک آرایه
        isAlreadySigned = data.some(item => item.pageIdentifier === pageIdentifier && item.uniqueCode === uniqueCode);

        
        manageAccess(pageIdentifier, uniqueCode, dNumber);
    } catch (error) {   
        usersNumber = 0;
        isAlreadySigned = false;
        manageAccess(pageIdentifier, '', null); // فراخوانی با مقدار پیش‌فرض
    }
}
// تابع manageAccess
async function manageAccess(pageIdentifier, uniqueCode, dNumber) {
    // تنظیم مقدار dNumber به null در صورت عدم دریافت مقدار مشخص
    if (dNumber === undefined || isNaN(dNumber)) {
        dNumber = null;
        }
    const remainingLogs = dNumber !== null ? dNumber - usersNumber - 1 : null;
    // تنظیم زمان به UTC+3:30 (ایران)
// تنظیم زمان به UTC+3:30
    
    const baseUrl = 'https://api.github.com/repos/drkingali/Receive_Log/contents/';
    const token = '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';

    // تولید یک نام یکتا برای فایل
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); // تاریخ و زمان فعلی به فرمت یکتا
    const fileName = `log-${pageIdentifier}-${uniqueCode}-${timestamp}.json`; // نام فایل یکتا
    const url = baseUrl + fileName;

    // بررسی وضعیت پرچم و شرایط ارسال
    if (!isAlreadySigned && (dNumber === null || usersNumber < dNumber)) {
        // ارسال اطلاعات به مخزن خصوصی
        const logData = {
            pageIdentifier: pageIdentifier,
            uniqueCode: uniqueCode,
            remainingLogs: remainingLogs,
            signTime: '1'
        };

        try {
            const response = await fetch(url, {
                method: 'PUT',
                headers: {
                    Authorization: `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: `Add log entry ${fileName}`,
                    content: btoa(unescape(encodeURIComponent(JSON.stringify(logData))))
                })
            });

            if (response.ok) {
                 isAlreadySigned = true; // پرچم فقط پس از ارسال موفق تغییر می‌کند
            } else {
                const errorText = await response.text();
                 }
        } catch (error) {
             }
    } else if (isAlreadySigned) {
        } else if (usersNumber >= dNumber) {    
        alertBeginner = true;
        setTimeout(() => {
    fetchDataFromGithub2();
}, 200);
        // مخفی کردن صفحه
        document.body.style.visibility = 'hidden';
                } else {
        }
}
      async function fetchDataFromGithub2() {
    const MAX_RETRIES = 6; // تعداد تلاش‌ها (3 ثانیه ÷ 0.5 ثانیه = 6)
    const RETRY_INTERVAL = 300; // فاصله بین تلاش‌ها به میلی‌ثانیه (0.5 ثانیه)
    const url = `https://raw.githubusercontent.com/drkingali/Inspect/refs/heads/main/data-27.json?timestamp=${new Date().getTime()}`;
    let data = null;

    for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
        try {
            const response = await fetch(url);
            if (!response.ok) continue; // اگر درخواست موفق نبود، تلاش بعدی انجام شود
            data = await response.json();
            processFields2(data); // فراخوانی تابع بعدی
            return; // خروج از حلقه در صورت موفقیت
        } catch {
            // بدون نمایش خطا، تلاش بعدی را انجام بده
            if (attempt < MAX_RETRIES) {
                await new Promise(resolve => setTimeout(resolve, RETRY_INTERVAL)); // توقف قبل از تلاش بعدی
            }
        }
    }

    // در صورت شکست تمام تلاش‌ها، تابع بدون هیچ عملی متوقف می‌شود.
}
      function processFields2(data) {
    let foundtwo = false;
    let modalTexttwo = '';

    data.forEach((field) => {
        // فقط پردازش آرایه‌هایی که number آن‌ها با unregisteredCode مطابقت دارد
        if (field.number == unregisteredCode) {
            foundtwo = true;

            if (field.option === 'a') {
                modalTexttwo = field.text; // ذخیره متن مودال از JSON
            }
        }
    });

    // نمایش مودال در صورت وجود متن مودال
    if (modalTexttwo) {
        showModal(modalTexttwo); // نمایش مودال با متن دریافت‌شده از JSON
    }
}

</script>


</body>
</html>


