<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Function to display the typing text section (copied from aysa-setup-wizard.php)
if (!function_exists('aysa_display_typing_text_section')) {
    function aysa_display_typing_text_section($text_to_type, $element_id_suffix) {
        ob_start();
        ?>
        <div class="aysa-chat-container aysa-wizard-intro-text">
            <div class="aysa-chat-message aysa-ai-message">
                <p id="aysa-dynamic-text-<?php echo esc_attr($element_id_suffix); ?>"></p>
            </div>
        </div>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                const uniqueSuffix = '<?php echo esc_js($element_id_suffix); ?>';
                const targetElementId = 'aysa-dynamic-text-' + uniqueSuffix;
                console.log('[Aysa Typing Effect DEBUG] Trying to initialize for suffix: ' + uniqueSuffix + ', Target ID: ' + targetElementId);

                const textElement = document.getElementById(targetElementId);
                const textToType = <?php echo json_encode($text_to_type); ?>;
                let currentIndex = 0;
                const typingSpeed = 30; // Milliseconds per character

                console.log('[Aysa Typing Effect DEBUG ' + uniqueSuffix + '] Target Element:', textElement);
                console.log('[Aysa Typing Effect DEBUG ' + uniqueSuffix + '] Text to type:', textToType);

                function typeWriter() {
                    if (textElement && currentIndex < textToType.length) {
                        textElement.innerHTML += textToType.charAt(currentIndex);
                        currentIndex++;
                        setTimeout(typeWriter, typingSpeed);
                    } else if (textElement) {
                        textElement.classList.add('typing-done');
                        console.log('[Aysa Typing Effect DEBUG ' + uniqueSuffix + '] Typing complete.');
                    } else {
                        console.error('[Aysa Typing Effect DEBUG ' + uniqueSuffix + '] Target element became null during typing.');
                    }
                }

                if (textElement) {
                    textElement.innerHTML = ''; // Clear initial content
                    console.log('[Aysa Typing Effect DEBUG ' + uniqueSuffix + '] Starting typewriter.');
                    typeWriter();
                } else {
                    console.error('[Aysa Typing Effect DEBUG ' + uniqueSuffix + '] Target element NOT FOUND at initialization for ID: ' + targetElementId);
                }
            });
        </script>
        <?php
        return ob_get_clean();
    }
}
?>

<div class="aysa-admin">
    <!-- Page Title -->
    <div class="aysa-page-title">
        <h1>Aysa.ai - SEO Domain Authority Table</h1>
        <div class="aysa-title-right">
            <?php 
            // Use the static display method with fallback
            if (class_exists('Aysa_Credits_Component')) {
                Aysa_Credits_Component::display();
            } else {
                // Fallback if the component doesn't exist
                echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
            }
            ?>
        </div>
    </div>

    <!-- Top Tabs -->
    <div class="aysa-top-tabs">
        <div class="aysa-tab active">Domain Authority</div>
        <a href="admin.php?page=aysa-research&tab=keyword-discovery" class="aysa-tab">Keyword Discovery</a>
        <a href="admin.php?page=aysa-research&tab=competitor-gap" class="aysa-tab">Competitor Keyword Gap</a>
        <a href="admin.php?page=aysa-research&tab=competitor-identification" class="aysa-tab">Competitor Identification</a>
        <a href="admin.php?page=aysa-research&tab=competitor-backlinks" class="aysa-tab">Competitor Backlink Analysis</a>
        <a href="admin.php?page=aysa-research&tab=missing-pages" class="aysa-tab">Missing Pages</a>
        <a href="admin.php?page=aysa-research&tab=content-strategy" class="aysa-tab">Content Strategy</a>
        <a href="admin.php?page=aysa-research&tab=sitemap-competition" class="aysa-tab">Sitemap Competition</a>
        
    </div>

    <!-- Main Content -->
    <div class="aysa-content">
        <div class="aysa-grid-span-full">
            <!-- AI Message commented out -->
            <!--
            <div class="aysa-global-intro-text" style="background-color:#e6f7ea;display:flex;align-items:center;gap:20px;padding:15px 20px;border-radius:8px;border:1px solid #d1dde5;margin-bottom:20px;max-width:90%;margin-left:auto;margin-right:auto;">
                <img src="<?php echo plugin_dir_url(dirname(__FILE__, 2)); ?>assets/images/aysa-eyes.png" alt="Aysa Eyes" class="aysa-eyes-img" style="width:67px;height:auto;display:block;margin:0;background:#e6f7ea;" />
                <div class="aysa-chat-message aysa-ai-message" style="background-color:#e1f0ff;color:#333;border-bottom-left-radius:0;text-align:center;display:inline-block;width:100%;">
                    <p id="aysa-dynamic-text-domain-authority-intro" style="margin:0;font-size:1.2rem;font-weight:600;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;"></p>
                </div>
            </div>
            -->
            <script type="text/javascript">
                document.addEventListener('DOMContentLoaded', function() {
                    const textElement = document.getElementById('aysa-dynamic-text-domain-authority-intro');
                    const textToType = "How likely is your site to rank? Domain Authority (DA) by Moz predicts just that. A higher score means a better chance of ranking on search results. Ready to see where you stand? Let's check your score and dive into the factors that can boost it.";
                    let currentIndex = 0;
                    const typingSpeed = 30;
                    function typeWriter() {
                        if (textElement && currentIndex < textToType.length) {
                            textElement.innerHTML += textToType.charAt(currentIndex);
                            currentIndex++;
                            setTimeout(typeWriter, typingSpeed);
                        } else if (textElement) {
                            textElement.classList.add('typing-done');
                        }
                    }
                    if (textElement) {
                        textElement.innerHTML = '';
                        typeWriter();
                    }
                });
            </script>
        </div>

        <!-- Left Column -->
        <div class="aysa-left-column">
            <!-- Domain Authority Analysis Header -->
            <div class="aysa-section-header">
                <div class="aysa-header-icon">★</div>
                <h2>Domain Authority Analysis (SEMrush)</h2>
            </div>
            
            <!-- Domain Description -->
            <div class="aysa-domain-description">
                <p>Domain Authority is a metric that predicts how well your website will rank in search engines. It's calculated based on various factors including the quality and quantity of links pointing to your site, making it a crucial indicator for SEO success.</p>
            </div>
            
            <!-- Domain Score -->
            <div class="aysa-domain-score">
                <h3>Your Domain Authority Score</h3>
                <div class="aysa-progress-container">
                    <div class="aysa-progress-bar">
                        <div class="aysa-progress" style="width: 0%;">
                            <span class="aysa-score-value"><span class="aysa-loading-spinner">...</span></span>
                        </div>
                    </div>
                    <div class="aysa-progress-scale">
                        <span>0</span>
                        <span>50</span>
                        <span>100</span>
                    </div>
                </div>
            </div>
            
            <!-- Authority Levels -->
            <div class="aysa-authority-levels">
                <div class="aysa-authority-level low">
                    <h4>Score 0-30: Low Authority</h4>
                    <p>Your site is new or has low visibility. You need to build more quality backlinks and valuable content.</p>
                </div>
                
                <div class="aysa-authority-level medium">
                    <h4>Score 31-60: Medium Authority</h4>
                    <p>Your site has good potential. Continue creating quality content and obtaining relevant links.</p>
                </div>
                
                <div class="aysa-authority-level high">
                    <h4>Score 61-100: High Authority</h4>
                    <p>Your site is strong and well-positioned. Maintain content quality and keep monitoring this score.</p>
                </div>
            </div>
        </div>
        
        <!-- Right Column -->
        <div class="aysa-right-column">
            <!-- Authority Score Trend -->
            <div class="aysa-trend-section">
                <div class="aysa-trend-header">
                    <h3>Authority Score Trend</h3>
                    <div class="aysa-info-icon">i</div>
                </div>
                <div class="aysa-trend-period">Last 12 months</div>
                <div class="aysa-trend-chart">
                    <canvas id="authorityTrendGraph"></canvas>
                </div>
            </div>
            
            <!-- Your Action Plan section removed - functionality moved to Adjustment page -->
        </div>
    </div>

</div>

<style>
/* Base Styles */
.aysa-admin {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    color: #333;
    max-width: 100%;
    margin: 0 auto;
    background-color: white;
    display: flex;
    flex-direction: column;
    height: 100%;
}

/* Page Title */
.aysa-page-title {
    padding: 15px 20px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aysa-page-title h1 {
    font-size: 20px;
    font-weight: 500;
    margin: 0;
    color: #333;
}

.aysa-title-right {
    display: flex;
    align-items: center;
    gap: 15px;
}

/* Top Tabs */
.aysa-top-tabs {
    display: flex;
    flex-wrap: wrap;
    border-bottom: 1px solid #e0e0e0;
    background-color: #f8f9fa;
    padding: 0;
}

.aysa-tab {
    padding: 10px 15px;
    font-size: 13px;
    color: #666;
    cursor: pointer;
    border-bottom: 3px solid transparent;
    white-space: nowrap;
    text-decoration: none;
}

.aysa-tab.active {
    color: #1a73e8;
    font-weight: 500;
    border-bottom: 3px solid #1a73e8;
}

.aysa-tab.disabled {
    color: #bbb;
    cursor: not-allowed;
}

.aysa-tab:hover:not(.disabled):not(.active) {
    color: #1a73e8;
    border-bottom: 3px solid #e8f0fe;
}

/* Main Content */
.aysa-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
    padding: 20px;
    flex-grow: 1;
    max-width: 100%;
    overflow-x: auto;
}

/* Section Header */
.aysa-section-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.aysa-header-icon {
    color: #1a73e8;
    margin-right: 10px;
    font-size: 20px;
}

.aysa-section-header h2 {
    font-size: 18px;
    font-weight: 500;
    margin: 0;
}

/* Domain Description */
.aysa-domain-description {
    color: #666;
    line-height: 1.5;
    font-size: 14px;
    margin-bottom: 25px;
}

/* Domain Score */
.aysa-domain-score {
    margin-bottom: 25px;
    max-width: 100%;
}

.aysa-domain-score h3 {
    font-size: 16px;
    font-weight: 500;
    margin-top: 0;
    margin-bottom: 15px;
}

.aysa-progress-container {
    margin-bottom: 25px;
    width: 100%;
}

.aysa-progress-bar {
    height: 24px;
    background-color: #f2f2f2;
    border-radius: 12px;
    overflow: hidden;
    position: relative;
}

.aysa-progress {
    height: 100%;
    background-color: #1a73e8;
    position: relative;
    border-radius: 12px;
}

.aysa-score-value {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: white;
    font-weight: bold;
}

.aysa-progress-scale {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
    font-size: 13px;
    color: #666;
}

/* Authority Levels */
.aysa-authority-levels {
    margin-bottom: 25px;
}

.aysa-authority-level {
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 10px;
}

.aysa-authority-level.low {
    background: #fff2f0;
    border-left: 4px solid #ff4d4f;
}

.aysa-authority-level.medium {
    background: #fffbe6;
    border-left: 4px solid #faad14;
}

.aysa-authority-level.high {
    background: #f6ffed;
    border-left: 4px solid #52c41a;
}

.aysa-authority-level h4 {
    margin: 0 0 5px 0;
    font-size: 15px;
    font-weight: 500;
}

.aysa-authority-level p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

/* Trend Section */
.aysa-trend-section {
    margin-bottom: 30px;
}

.aysa-trend-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5px;
}

.aysa-trend-header h3 {
    font-size: 16px;
    font-weight: 500;
    margin: 0;
}

.aysa-info-icon {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #e0e0e0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #666;
    cursor: help;
}

.aysa-trend-period {
    text-align: right;
    color: #666;
    font-size: 13px;
    margin-bottom: 10px;
}

/* Trend Chart */
.aysa-trend-chart {
    height: 240px;
}

/* Loading Spinner */
.aysa-loading-spinner {
    display: inline-block;
    font-size: 14px;
    font-weight: normal;
    color: rgba(255, 255, 255, 0.8);
    animation: pulse 1.2s infinite;
}

@keyframes pulse {
    0% { opacity: 0.5; }
    50% { opacity: 1; }
    100% { opacity: 0.5; }
}

/* New Modern Tasks Section Styles */
.aysa-modern-tasks-section {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    margin-top: 20px; /* Ensure some space from elements above */
}

.aysa-tasks-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9edf0;
}

.aysa-tasks-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #334155; /* Darker blue-gray */
    margin: 0;
}

.aysa-add-task-btn {
    background-color: #3b82f6; /* Tailwind Blue 500 */
    color: white;
    border: none;
    border-radius: 6px;
    padding: 8px 15px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.aysa-add-task-btn:hover {
    background-color: #2563eb; /* Tailwind Blue 600 */
}

/* Tasks Pagination Styles */
.aysa-tasks-pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    font-size: 14px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #e9edf0;
}

.aysa-pagination-btn {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    color: #475569;
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-pagination-btn:hover:not(:disabled) {
    background: #3b82f6;
    color: white;
    border-color: #3b82f6;
}

.aysa-pagination-btn:disabled {
    background: #f1f5f9;
    color: #94a3b8;
    border-color: #e2e8f0;
    cursor: not-allowed;
}

.aysa-tasks-showing {
    color: #64748b;
    font-weight: 500;
}

.aysa-task-count {
    background: #e2e8f0;
    color: #64748b;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    margin-left: 8px;
}

.aysa-todo-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.aysa-todo-list li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 5px;
    border-bottom: 1px solid #f1f5f9; /* Lighter border */
    transition: background-color 0.15s ease;
}

.aysa-todo-list li:last-child {
    border-bottom: none;
}

.aysa-todo-list li:hover {
    background-color: #f8fafc; /* Slight hover effect */
}

.aysa-todo-checkbox-label {
    display: flex;
    align-items: center;
    cursor: pointer;
    flex-grow: 1;
}

.aysa-todo-checkbox {
    opacity: 0; /* Hide actual checkbox */
    width: 0;
    height: 0;
    position: absolute;
}

.aysa-custom-checkbox {
    width: 20px;
    height: 20px;
    background-color: #ffffff;
    border: 2px solid #cbd5e1; /* Tailwind Slate 300 */
    border-radius: 5px;
    margin-right: 12px;
    display: inline-block;
    transition: all 0.2s ease;
    flex-shrink: 0;
    position: relative;
}

.aysa-custom-checkbox::after {
    content: '\2713'; /* Checkmark character */
    font-size: 14px;
    color: white;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    transition: transform 0.2s ease;
}

.aysa-todo-checkbox:checked + .aysa-custom-checkbox {
    background-color: #22c55e; /* Tailwind Green 500 */
    border-color: #22c55e;
}

.aysa-todo-checkbox:checked + .aysa-custom-checkbox::after {
    transform: translate(-50%, -50%) scale(1);
}

.aysa-todo-text {
    font-size: 15px;
    color: #475569; /* Tailwind Slate 600 */
    transition: color 0.2s ease, text-decoration 0.2s ease;
}

.aysa-todo-list li[data-status="completed"] .aysa-todo-text {
    text-decoration: line-through;
    color: #94a3b8; /* Tailwind Slate 400 */
}

.aysa-delete-task {
    color: #94a3b8; /* Tailwind Slate 400 */
    font-size: 20px;
    font-weight: bold;
    cursor: pointer;
    padding: 0 5px;
    border-radius: 4px;
    transition: color 0.2s ease, background-color 0.2s ease;
    margin-left: 10px;
}

.aysa-delete-task:hover {
    color: #ef4444; /* Tailwind Red 500 */
    background-color: #fee2e2; /* Tailwind Red 100 for hover background */
}

.aysa-todo-done {
  text-decoration: line-through;
  color: #888;
}
.aysa-todo-deleted-text {
  text-decoration: line-through;
  color: #888 !important;
}
.aysa-todo-deleted + .aysa-custom-checkbox {
  border-color: #e53935 !important;
  background: #fff !important;
}
.aysa-todo-deleted:checked + .aysa-custom-checkbox {
  background: #e53935 !important;
  border-color: #e53935 !important;
}
.aysa-task-flag-icon {
  font-size: 1.1em;
  vertical-align: middle;
  opacity: 0.85;
  margin-right: 4px;
}

#aysa-add-task-modal.aysa-modal {
  display: none;
  position: fixed;
  z-index: 9999;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(30, 41, 59, 0.45);
  align-items: center;
  justify-content: center;
  animation: fadeIn .2s;
}
#aysa-add-task-modal.aysa-modal[style*="display: block"] {
  display: flex !important;
}
#aysa-add-task-modal .aysa-modal-content {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(30,41,59,0.18);
  max-width: 420px;
  width: 100%;
  margin: auto;
  padding: 0;
  animation: popIn .2s;
}
#aysa-add-task-modal .aysa-modal-header {
  padding: 20px 28px 10px 28px;
  border-radius: 16px 16px 0 0;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
#aysa-add-task-modal .aysa-modal-header h3 {
  margin: 0;
  font-size: 1.18rem;
  font-weight: 600;
  color: #1a202c;
}
#aysa-add-task-modal .aysa-modal-close {
  background: none;
  border: none;
  font-size: 1.6rem;
  color: #64748b;
  cursor: pointer;
  margin-left: 10px;
  transition: color 0.2s;
}
#aysa-add-task-modal .aysa-modal-close:hover {
  color: #1a73e8;
}
#aysa-add-task-modal .aysa-modal-body {
  padding: 18px 28px 0 28px;
}
#aysa-add-task-modal .aysa-form-group label {
  font-size: 0.98rem;
  font-weight: 500;
  color: #1a202c;
  margin-bottom: 4px;
  display: block;
}
#aysa-add-task-modal .aysa-input {
  width: 100%;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 1rem;
  margin-bottom: 12px;
  background: #f8fafc;
  color: #1a202c;
  transition: border 0.2s;
}
#aysa-add-task-modal .aysa-input:focus {
  border: 1.5px solid #1a73e8;
  outline: none;
}
#aysa-add-task-modal .aysa-modal-footer {
  padding: 18px 28px 22px 28px;
  border-radius: 0 0 16px 16px;
  background: #fff;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #f0f0f0;
}
#aysa-add-task-save {
  background: #1a73e8;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}
#aysa-add-task-save:hover {
  background: #1558b0;
}
#aysa-add-task-cancel {
  background: #f1f5f9;
  color: #64748b;
  border: none;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}
#aysa-add-task-cancel:hover {
  background: #e2e8f0;
}
@keyframes fadeIn {
  from { opacity: 0; } to { opacity: 1; }
}
@keyframes popIn {
  from { transform: scale(0.95); opacity: 0.7; } to { transform: scale(1); opacity: 1; }
}

/* New Modern Tasks Section Styles */
.aysa-modern-tasks-section {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    margin-top: 20px; /* Ensure some space from elements above */
}

.aysa-tasks-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9edf0;
}

.aysa-tasks-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #334155; /* Darker blue-gray */
    margin: 0;
}

.aysa-add-task-btn {
    background-color: #3b82f6; /* Tailwind Blue 500 */
    color: white;
    border: none;
    border-radius: 6px;
    padding: 8px 15px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.aysa-add-task-btn:hover {
    background-color: #2563eb; /* Tailwind Blue 600 */
}

/* Task Groups */
.aysa-task-group {
    margin-bottom: 25px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    overflow: hidden;
}

.aysa-task-group-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 1px solid #e2e8f0;
}

.aysa-task-group-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #334155;
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-task-group-icon {
    font-size: 18px;
}

.aysa-task-group-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.aysa-badge-auto {
    background-color: #e0f2fe;
    color: #0369a1;
    border: 1px solid #bae6fd;
}

.aysa-badge-manual {
    background-color: #fef3c7;
    color: #d97706;
    border: 1px solid #fed7aa;
}

.aysa-task-list {
    list-style: none;
    padding: 0;
    margin: 0;
    background: #ffffff;
}

.aysa-task-item {
    border-bottom: 1px solid #f1f5f9;
    transition: all 0.2s ease;
}

.aysa-task-item:last-child {
    border-bottom: none;
}

.aysa-task-item:hover {
    background-color: #f8fafc;
}

/* Task Action Buttons Styling */
.aysa-task-actions {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-left: auto;
}

.aysa-task-action-btn {
    background: #e2e8f0;
    color: #64748b;
    border: none;
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    flex-shrink: 0;
}

.aysa-goto-btn {
    background: #3b82f6;
    color: white;
}

.aysa-goto-btn:hover {
    background: #2563eb;
}

.aysa-complete-btn {
    background: #22c55e;
    color: white;
}

.aysa-complete-btn:hover {
    background: #16a34a;
}

.aysa-task-action-btn:hover {
    background: #cbd5e1;
}

/* Remove old call-to-action styling */
.aysa-task-item {
    cursor: pointer;
}

.aysa-task-item:hover {
    background-color: #f8fafc;
}

.aysa-task-content {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    gap: 12px;
}

.aysa-task-checkbox {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    cursor: pointer;
    flex-shrink: 0;
}

.aysa-task-label {
    flex-grow: 1;
    font-size: 14px;
    color: #475569;
    cursor: pointer;
    line-height: 1.4;
    margin-right: 12px;
    font-weight: 500;
}

.aysa-task-label.completed {
    text-decoration: line-through;
    color: #94a3b8;
}

.aysa-task-progress-inline {
    width: 120px;
    height: 8px;
    background: #f1f5f9;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 8px;
    flex-shrink: 0;
}

.aysa-inline-progress-bar {
    height: 100%;
    transition: width 0.3s ease;
    border-radius: 4px;
}

.aysa-progress-text {
    font-size: 12px;
    color: #64748b;
    white-space: nowrap;
    min-width: 90px;
    text-align: right;
    margin-right: 8px;
    flex-shrink: 0;
}

.aysa-task-detail-btn {
    background: #e2e8f0;
    color: #64748b;
    border: none;
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;
    cursor: pointer;
    transition: background-color 0.2s ease;
    margin-right: 4px;
    flex-shrink: 0;
}

.aysa-task-detail-btn:hover {
    background: #cbd5e1;
}

.aysa-delete-btn {
    background: none;
    border: none;
    color: #94a3b8;
    font-size: 16px;
    cursor: pointer;
    padding: 4px 6px;
    border-radius: 4px;
    transition: all 0.2s ease;
    flex-shrink: 0;
}

.aysa-delete-btn:hover {
    background: #fee2e2;
    color: #ef4444;
}

.aysa-todo-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.aysa-todo-list li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 5px;
    border-bottom: 1px solid #f1f5f9; /* Lighter border */
    transition: background-color 0.15s ease;
}

.aysa-todo-list li:last-child {
    border-bottom: none;
}

.aysa-todo-list li:hover {
    background-color: #f8fafc; /* Slight hover effect */
}

.aysa-todo-checkbox-label {
    display: flex;
    align-items: center;
    cursor: pointer;
    flex-grow: 1;
}

.aysa-todo-checkbox {
    opacity: 0; /* Hide actual checkbox */
    width: 0;
    height: 0;
    position: absolute;
}

.aysa-custom-checkbox {
    width: 20px;
    height: 20px;
    background-color: #ffffff;
    border: 2px solid #cbd5e1; /* Tailwind Slate 300 */
    border-radius: 5px;
    margin-right: 12px;
    display: inline-block;
    transition: all 0.2s ease;
    flex-shrink: 0;
    position: relative;
}

.aysa-custom-checkbox::after {
    content: '\2713'; /* Checkmark character */
    font-size: 14px;
    color: white;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    transition: transform 0.2s ease;
}

.aysa-todo-checkbox:checked + .aysa-custom-checkbox {
    background-color: #22c55e; /* Tailwind Green 500 */
    border-color: #22c55e;
}

.aysa-todo-checkbox:checked + .aysa-custom-checkbox::after {
    transform: translate(-50%, -50%) scale(1);
}

.aysa-todo-text {
    font-size: 15px;
    color: #475569; /* Tailwind Slate 600 */
    transition: color 0.2s ease, text-decoration 0.2s ease;
}

.aysa-todo-list li[data-status="completed"] .aysa-todo-text {
    text-decoration: line-through;
    color: #94a3b8; /* Tailwind Slate 400 */
}

.aysa-delete-task {
    color: #94a3b8; /* Tailwind Slate 400 */
    font-size: 20px;
    font-weight: bold;
    cursor: pointer;
    padding: 0 5px;
    border-radius: 4px;
    transition: color 0.2s ease, background-color 0.2s ease;
    margin-left: 10px;
}

.aysa-delete-task:hover {
    color: #ef4444; /* Tailwind Red 500 */
    background-color: #fee2e2; /* Tailwind Red 100 for hover background */
}

/* Responsive adjustments */
@media screen and (max-width: 1200px) {
    .aysa-content {
        grid-template-columns: 1fr;
        gap: 20px;
    }
    
    .aysa-trend-chart {
        width: 100%;
        overflow-x: auto;
    }
}

/* Styles for the dynamic text */
.aysa-wizard-intro-text {
    background-color: #f0f4f8;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    max-width: 100%;
    border: 1px solid #d1dde5;
}

.aysa-wizard-intro-text .aysa-chat-message {
    padding: 10px 15px;
    border-radius: 15px;
    line-height: 1.6;
    text-align: left;
    max-width: 100%;
}

.aysa-wizard-intro-text .aysa-ai-message {
    background-color: #e1f0ff;
    color: #333;
    display: inline-block;
    width: auto;
    border-bottom-left-radius: 0;
}

.aysa-wizard-intro-text .aysa-ai-message p {
    margin: 0;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-size: 15px;
}

.aysa-wizard-intro-text .aysa-ai-message p::after {
    content: '|';
    display: inline-block;
    animation: blink-animation 1s infinite;
    font-weight: bold;
}

.aysa-wizard-intro-text .aysa-ai-message p.typing-done::after {
    animation: none;
    content: '';
}

@keyframes blink-animation {
    to {
        visibility: hidden;
    }
}
</style>

<!-- Include Chart.js -->
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript ?>
<script src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/js/vendor/chartjs-stub.js'); ?>"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('authorityTrendGraph').getContext('2d');
    let chart;
    
    // Function to fetch domain authority history
    function fetchDomainAuthorityHistory() {
        console.log('[Domain Authority Research] Starting to fetch domain authority history');
        const secretKey = getSecretKey();
        if (!secretKey) {
            console.error('[Domain Authority Research] Secret key not found, trying to save data first');
            // Instead of just fallback, try to save data first to create history
            saveAndCreateDomainAuthorityHistory();
            return;
        }
        
        console.log('[Domain Authority Research] Using secret key to fetch history');
        // Get domain authority history using the ProjectDomainAuthority/BySecret endpoint
        AysaAPI.getDataByEndpoint('project_domain_authority_by_secret', {secret: secretKey})
            .then(function(response) {
                console.log('[Domain Authority Research] API response:', response);
                // Parse the response if needed
                const authorityData = typeof response === 'string' ? JSON.parse(response) : response;
                
                if (authorityData && authorityData.length > 0) {
                    // Extract dates and scores
                    const labels = authorityData.map(item => formatDate(item.creationDate));
                    const scores = authorityData.map(item => item.daValue);
                    
                    // Update current score display
                    const latestScore = scores[0]; // Most recent score
                    console.log('[Domain Authority Research] Successfully retrieved score:', latestScore);
                    updateScoreDisplay(latestScore);
                    
                    // Update chart
                    updateChart(labels.reverse(), scores.reverse());
                    
                    // Check if we need to update the data today
                    const hasDataFromToday = authorityData.some(item => isToday(item.creationDate));
                    
                    if (!hasDataFromToday) {
                        // If no data from today, trigger a refresh (but only once)
                        saveDomainAuthorityOnce(secretKey);
                    }
                } else {
                    console.log('[Domain Authority Research] No authority data in response, triggering save');
                    // If no data, trigger a save to get initial data (but only once)
                    saveDomainAuthorityOnce(secretKey);
                }
            })
            .catch(function(error) {
                console.error('[Domain Authority Research] Error fetching domain authority history:', error);
                // Instead of just fallback, try to save data first to create history
                saveAndCreateDomainAuthorityHistory();
            });
    }
    
    // Function to save domain authority data and create history when secret key is missing
    let aysaSecretKeyCache = null;

    function saveAndCreateDomainAuthorityHistory() {
        console.log('[Domain Authority Research] Attempting to save and create domain authority history');
        
        // First try to get secret key from server
        tryGetSecretKeyFromServer()
            .then(function(secretKey) {
                if (secretKey) {
                    console.log('[Domain Authority Research] Secret key obtained from server, retrying main flow');
                    aysaSecretKeyCache = secretKey;
                    // Retry the main fetch function now that we have the key
                    fetchDomainAuthorityHistory();
                    return;
                }
                
                // If still no secret key, continue with fallback method
                console.log('[Domain Authority Research] No secret key available, using fallback method');
                executeSecretKeyFallback();
            })
            .catch(function(error) {
                console.error('[Domain Authority Research] Error getting secret key from server:', error);
                executeSecretKeyFallback();
            });
    }
    
    // Function to try getting secret key from server
    function tryGetSecretKeyFromServer() {
        return new Promise(function(resolve, reject) {
            console.log('[Domain Authority Research] Attempting to get secret key from server');
            
            // Try to get secret key via WordPress AJAX
            if (typeof ajaxurl !== 'undefined') {
                const formData = new FormData();
                formData.append('action', 'aysa_get_secret_key');
                if (typeof aysaParams !== 'undefined' && aysaParams.nonce) {
                    formData.append('nonce', aysaParams.nonce);
                }
                
                fetch(ajaxurl, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(function(data) {
                    if (data.success && data.data && data.data.secret_key) {
                        console.log('[Domain Authority Research] Secret key retrieved from server');
                        aysaSecretKeyCache = data.data.secret_key;
                        resolve(data.data.secret_key);
                    } else {
                        console.log('[Domain Authority Research] No secret key found on server');
                        resolve(null);
                    }
                })
                .catch(function(error) {
                    console.error('[Domain Authority Research] AJAX error getting secret key:', error);
                    resolve(null);
                });
            } else {
                console.log('[Domain Authority Research] No ajaxurl available');
                resolve(null);
            }
        });
    }
    
    // Function to execute fallback when no secret key is available
    function executeSecretKeyFallback() {
        const currentDomain = window.location.hostname;
        
        // First, get the current domain authority score using the fallback endpoint
        const fallbackBaseUrl = (window.AYSA_API_BASE || 'https://api.aysa.ai') + '/';
        const fullUrl = `${fallbackBaseUrl}api/AysaPluginUser/domain-authority?target=${currentDomain}`;
        
        console.log('[Domain Authority Research] Getting current score from:', fullUrl);
        
        fetch(fullUrl)
            .then(response => response.json())
            .then(function(authorityData) {
                console.log('[Domain Authority Research] Current score API response:', authorityData);
                
                if (authorityData && authorityData.data && authorityData.data.length > 0) {
                    const authorityScore = authorityData.data[0].authority_score;
                    if (authorityScore !== undefined && authorityScore !== null) {
                        console.log('[Domain Authority Research] Current score retrieved:', authorityScore);
                        
                        // Update display with current score
                        updateScoreDisplay(authorityScore);
                        
                        // Show a simple chart with current data only (no history)
                        const currentDate = new Date().toLocaleDateString();
                        updateChart([currentDate], [authorityScore]);
                        
                        // Show info message that history is not available
                        showHistoryNotAvailableMessage();
                        
                        return;
                    }
                }
                
                console.error('[Domain Authority Research] Failed to get current domain authority score');
                showDomainAuthorityError();
            })
            .catch(function(error) {
                console.error('[Domain Authority Research] Error getting current score:', error);
                showDomainAuthorityError();
            });
    }
    
    // Show message that history is not available
    function showHistoryNotAvailableMessage() {
        const chartContainer = document.querySelector('.aysa-chart-container');
        if (chartContainer) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'aysa-info-message';
            messageDiv.style.cssText = 'background: #e3f2fd; border: 1px solid #2196f3; padding: 10px; margin-top: 10px; border-radius: 4px; font-size: 12px; color: #1976d2;';
            messageDiv.innerHTML = '📊 Historical data will be available after authentication. Current score shown only.';
            chartContainer.appendChild(messageDiv);
        }
    }
    

    // Enhanced domain authority loading function for research page
    function loadDomainAuthorityFallback() {
        console.log('[Domain Authority Research] Attempting fallback method...');
        const currentDomain = window.location.hostname;
        
        // Ensure API configuration is loaded before making the call
        if (typeof AysaAPI !== 'undefined' && AysaAPI.init) {
            AysaAPI.init();
        }
        
        // Get the API configuration to ensure we have the correct base URL
        let apiConfig = null;
        if (typeof AysaAPI !== 'undefined' && AysaAPI.getConfig) {
            apiConfig = AysaAPI.getConfig();
        }
        
        // Fallback base URL if configuration is not loaded
        const fallbackBaseUrl = (window.AYSA_API_BASE || 'https://api.aysa.ai') + '/';
        
        // Method 1: Try the main domain authority endpoint
        console.log('[Domain Authority Research] API Config:', apiConfig);
        AysaAPI.getDataByEndpoint('domain_authority', {}, {target: currentDomain})
            .then(function(authorityData) {
                console.log('[Domain Authority Research] Fallback API response:', authorityData);
                
                if (authorityData && authorityData.data && authorityData.data.length > 0) {
                    const authorityScore = authorityData.data[0].authority_score;
                    if (authorityScore !== undefined && authorityScore !== null) {
                        console.log('[Domain Authority Research] Fallback successful, score:', authorityScore);
                        updateScoreDisplay(authorityScore);
                        
                        // Create a simple chart with just the current score
                        const currentDate = new Date().toLocaleDateString();
                        updateChart([currentDate], [authorityScore]);
                        return;
                    }
                }
                
                // If fallback also fails, show error state
                showDomainAuthorityError();
            })
            .catch(function(error) {
                console.error('[Domain Authority Research] Fallback API error:', error);
                console.log('[Domain Authority Research] Trying with full URL as fallback...');
                
                // Try with full URL as last resort
                const fullUrl = `${fallbackBaseUrl}api/AysaPluginUser/domain-authority?target=${currentDomain}`;
                console.log('[Domain Authority Research] Trying full URL:', fullUrl);
                
                fetch(fullUrl)
                    .then(response => response.json())
                    .then(function(authorityData) {
                        console.log('[Domain Authority Research] Full URL API response:', authorityData);
                        
                        if (authorityData && authorityData.data && authorityData.data.length > 0) {
                            const authorityScore = authorityData.data[0].authority_score;
                            if (authorityScore !== undefined && authorityScore !== null) {
                                console.log('[Domain Authority Research] Full URL successful, score:', authorityScore);
                                updateScoreDisplay(authorityScore);
                                
                                // Create a simple chart with just the current score
                                const currentDate = new Date().toLocaleDateString();
                                updateChart([currentDate], [authorityScore]);
                                return;
                            }
                        }
                        
                        showDomainAuthorityError();
                    })
                    .catch(function(fullUrlError) {
                        console.error('[Domain Authority Research] Full URL API error:', fullUrlError);
                        showDomainAuthorityError();
                    });
            });
    }
    
    // Show error state for domain authority in research page
    function showDomainAuthorityError() {
        console.log('[Domain Authority Research] Showing error state');
        const progressBar = document.querySelector('.aysa-progress');
        const scoreValue = document.querySelector('.aysa-score-value');
        
        if (progressBar && scoreValue) {
            progressBar.style.width = '0%';
            scoreValue.innerHTML = '<span style="color: #dc3545;">--</span>';
            
            // Add retry functionality
            const retryHtml = '<button onclick="retryDomainAuthorityResearch()" style="background: none; border: none; color: #007cba; text-decoration: underline; cursor: pointer; font-size: 11px; margin-left: 5px;">Retry</button>';
            scoreValue.innerHTML += retryHtml;
        }
    }
    
    // Get secret key helper function for research page
    function getSecretKey() {
        if (aysaSecretKeyCache) {
            return aysaSecretKeyCache;
        }

        // Read only from localized runtime objects (no browser persistence)
        if (typeof aysa_ajax !== 'undefined' && aysa_ajax.secret_key) {
            aysaSecretKeyCache = aysa_ajax.secret_key;
            return aysa_ajax.secret_key;
        }
        if (typeof aysaParams !== 'undefined' && aysaParams.secret_key) {
            aysaSecretKeyCache = aysaParams.secret_key;
            return aysaParams.secret_key;
        }

        console.log('[Secret Key] Not available in runtime objects, will try server');
        return null;
    }
    
    // Global retry function for research page
    window.retryDomainAuthorityResearch = function() {
        const progressBar = document.querySelector('.aysa-progress');
        const scoreValue = document.querySelector('.aysa-score-value');
        
        if (progressBar && scoreValue) {
            progressBar.style.width = '0%';
            scoreValue.innerHTML = '<span class="aysa-loading-spinner">...</span>';
        }
        
        fetchDomainAuthorityHistory();
    };
    
    // Global flag to prevent infinite loops
    let isSavingDomainAuthority = false;
    let hasAttemptedSave = false;
    
    // Function to save domain authority (with loop prevention)
    function saveDomainAuthorityOnce(secretKey) {
        if (isSavingDomainAuthority || hasAttemptedSave) {
            console.log('[Domain Authority Research] Save already in progress or attempted, skipping to prevent infinite loop');
            return;
        }
        isSavingDomainAuthority = true;
        hasAttemptedSave = true;
        saveDomainAuthority(secretKey);
    }
    
    // Function to fetch domain authority history (with loop prevention)
    function fetchDomainAuthorityHistoryOnce() {
        if (isSavingDomainAuthority) {
            console.log('[Domain Authority Research] Fetch already in progress, skipping to prevent infinite loop');
            return;
        }
        fetchDomainAuthorityHistory();
    }
    
    // Function to save domain authority
    function saveDomainAuthority(secretKey) {
        if (!secretKey) {
            console.error('[Domain Authority Research] Secret key not found for save operation, trying alternative method');
            // If no secret key, try to save using domain-based approach
            saveAndCreateDomainAuthorityHistory();
            return;
        }
        
        console.log('[Domain Authority Research] Saving domain authority data with secret key');
        // Use the ProjectDomainAuthority POST endpoint to save domain authority
        AysaAPI.postDataByEndpoint('project_domain_authority', {
            secretKey: secretKey
        })
        .then(function(response) {
            console.log('[Domain Authority Research] Domain authority saved successfully');
            isSavingDomainAuthority = false;
            // Refresh data after saving, but only once to prevent infinite loops
            setTimeout(function() {
                fetchDomainAuthorityHistoryOnce();
            }, 1000);
        })
        .catch(function(error) {
            console.error('[Domain Authority Research] Error saving domain authority:', error);
            isSavingDomainAuthority = false;
            // Don't trigger another save attempt to prevent infinite loops
            showDomainAuthorityError();
        });
    }
    
    // Show error state for domain authority
    function showDomainAuthorityError() {
        console.log('[Domain Authority Research] Showing error state');
        const progressBar = document.querySelector('.aysa-progress');
        const scoreValue = document.querySelector('.aysa-score-value');
        
        if (progressBar && scoreValue) {
            progressBar.style.width = '0%';
            scoreValue.textContent = '--';
        }
        
        // Show error message in console for debugging
        console.error('[Domain Authority Research] Unable to load domain authority data. Please check your API configuration.');
    }
    
    // Update the score display
    function updateScoreDisplay(score) {
        // Update the progress bar width and text
        const progressBar = document.querySelector('.aysa-progress');
        const scoreValue = document.querySelector('.aysa-score-value');
        
        if (progressBar && scoreValue) {
            progressBar.style.width = `${score}%`;
            scoreValue.textContent = score;
        }
    }
    
    // Update the chart with new data
    function updateChart(labels, scores) {
        const data = {
            labels: labels,
            datasets: [{
                label: 'Authority Score',
                data: scores,
                borderColor: '#1a73e8',
                backgroundColor: 'rgba(26, 115, 232, 0.1)',
                fill: true,
                tension: 0.4,
                pointRadius: 3,
                pointBackgroundColor: '#1a73e8'
            }]
        };
        
        // If chart already exists, update it
        if (chart) {
            chart.data = data;
            chart.update();
        } else {
            // Otherwise create new chart
            chart = new Chart(ctx, {
                type: 'line',
                data: data,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            titleFont: {
                                size: 12
                            },
                            bodyFont: {
                                size: 12
                            },
                            padding: 10,
                            displayColors: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                stepSize: 25,
                                font: {
                                    size: 11
                                }
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            ticks: {
                                font: {
                                    size: 11
                                },
                                maxRotation: 45,
                                minRotation: 45
                            },
                            grid: {
                                display: false
                            }
                        }
                    }
                }
            });
        }
    }
    
    // Function to format dates consistently
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
    }
    
    // Function to check if a date is today
    function isToday(dateString) {
        const today = new Date();
        const date = new Date(dateString);
        
        return today.getDate() === date.getDate() && 
               today.getMonth() === date.getMonth() && 
               today.getFullYear() === date.getFullYear();
    }
    
    // Add click event listeners to tabs
    const tabs = document.querySelectorAll('.aysa-tab:not(.disabled)');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const currentActive = document.querySelector('.aysa-tab.active');
            if (currentActive) {
                currentActive.classList.remove('active');
            }
            this.classList.add('active');
        });
    });
    
    // Initialize - fetch domain authority history  
    fetchDomainAuthorityHistory();

    // Modern Task List Functionality with backend integration
    const automatedTasksList = document.querySelector('.aysa-automated-tasks');
    const manualTasksList = document.querySelector('.aysa-manual-tasks');
    const addTaskBtn = document.querySelector('.aysa-add-task-btn');
    const apiBase = `${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks`;
    
    console.log('[AYSA TASKS] DOM elements found:', {
        automatedTasksList: !!automatedTasksList,
        manualTasksList: !!manualTasksList,
        addTaskBtn: !!addTaskBtn
    });

    // Pagination variables - separate for each type
    let automatedCurrentPage = 1;
    let manualCurrentPage = 1;
    const tasksPerPage = 5; // Reduced to 5 per page for each group
    let allAutomatedTasks = [];
    let allManualTasks = [];

    // Helper to get projectId
    function getProjectId() {
        console.log('[AYSA DOMAIN AUTHORITY] Getting project ID for domain: ' + window.location.hostname);
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId && parseInt(projectId, 10) > 0) {
            console.log('[AYSA DOMAIN AUTHORITY] Project ID found in localStorage: ' + projectId);
            return parseInt(projectId, 10);
        }
        // Fallback: async fetch by domain (never block main thread)
        if (!window.__aysaProjectIdFetchInFlight) {
            window.__aysaProjectIdFetchInFlight = true;
            const domain = window.location.hostname;
            fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/Project/getbydomain/` + domain)
                .then(res => res.ok ? res.json() : null)
                .then(resp => {
                    if (resp && resp.projectId) {
                        localStorage.setItem('aysa_project_id', String(resp.projectId));
                        console.log('[AYSA DOMAIN AUTHORITY] Project ID retrieved from API: ' + resp.projectId);
                        if (typeof fetchTasks === 'function') {
                            fetchTasks();
                        }
                    }
                })
                .catch(error => {
                    console.error('[AYSA DOMAIN AUTHORITY] Failed async project ID fetch:', error);
                })
                .finally(() => {
                    window.__aysaProjectIdFetchInFlight = false;
                });
        }
        return 0;
    }
    // Task type to page mapping function
    function getTaskRedirectUrl(taskTitle) {
        const title = taskTitle.toLowerCase();
        
        // Association tasks redirect to Keyword Discovery
        if (title.includes('associate') && title.includes('keywords')) {
            return 'admin.php?page=aysa-research&tab=keyword-discovery';
        }
        
        // Complete association tasks redirect to Keyword Discovery
        if (title.includes('complete') && title.includes('association')) {
            return 'admin.php?page=aysa-research&tab=keyword-discovery';
        }
        
        // Backlink tasks redirect to Adjustment & Improvement Domain Authority tab
        if (title.includes('links') && title.includes('authority')) {
            return 'admin.php?page=aysa-adjustment-improvement&tab=domain-authority';
        }
        
        // Competitor analysis tasks
        if (title.includes('competitor')) {
            if (title.includes('gap') || title.includes('keyword')) {
                return 'admin.php?page=aysa-research&tab=competitor-gap';
            }
            if (title.includes('backlink')) {
                return 'admin.php?page=aysa-research&tab=competitor-backlinks';
            }
            if (title.includes('identification') || title.includes('identify')) {
                return 'admin.php?page=aysa-research&tab=competitor-identification';
            }
        }
        
        // Keyword discovery tasks
        if (title.includes('keyword') && (title.includes('research') || title.includes('discovery'))) {
            return 'admin.php?page=aysa-research&tab=keyword-discovery';
        }
        
        // Domain authority tasks redirect to Adjustment & Improvement Domain Authority tab
        if (title.includes('domain') && title.includes('authority')) {
            return 'admin.php?page=aysa-adjustment-improvement&tab=domain-authority';
        }
        
        // Default fallback to research page
        return 'admin.php?page=aysa-research';
    }

    // Then modify the createTaskItem function to use this calculation:
    function escapeHtml(value) {
        return String(value ?? '').replace(/[&<>"']/g, function(char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;'
            }[char];
        });
    }

    function escapeAttr(value) {
        return escapeHtml(value).replace(/`/g, '&#96;');
    }

    function createTaskItem(task) {
        const li = document.createElement('li');
        li.className = 'aysa-task-item';
        li.dataset.status = (task.status === 'done') ? 'completed' : (task.status === 'deleted' ? 'deleted' : 'in-progress');
        li.dataset.taskId = task.id;
        li.dataset.taskTitle = task.title;
        li.dataset.taskDescription = task.description || '';
        li.dataset.taskFlag = task.flag;
        li.dataset.taskCreatedDate = task.createdDate;
        li.dataset.taskUpdatedDate = task.updatedDate || '';
        
        const isCompleted = task.status === 'done';
        const isDeleted = task.status === 'deleted';
        
        // Calculate progress based on task type
        let progress = 0;
        if (isCompleted) {
            progress = 100;
        } else if (isDeleted) {
            progress = 0;
        } else {
                         // Use the percent from API for all tasks (including link purchase tasks)
             progress = task.percent || 0;
        }
        
        const progressColor = isCompleted ? '#34a853' : (progress > 50 ? '#3b82f6' : '#f59e0b');
        const progressWidth = Math.min(progress, 100);
        
        const safeTaskId = parseInt(task.id, 10) || 0;
        const safeTitle = escapeHtml(task.title || 'Untitled task');

        // Get redirect URL for this task
        const redirectUrl = getTaskRedirectUrl(task.title);
        const safeRedirectUrl = escapeAttr(redirectUrl);
        
        li.innerHTML = `
            <div class="aysa-task-content" data-redirect-url="${safeRedirectUrl}">
                <input type="checkbox" id="task-${safeTaskId}" class="aysa-task-checkbox" ${isCompleted ? 'checked' : ''}>
                <label for="task-${safeTaskId}" class="aysa-task-label ${isCompleted ? 'completed' : ''}">${safeTitle}</label>
                <div class="aysa-task-progress-inline">
                    <div class="aysa-inline-progress-bar" style="width: ${progressWidth}%; background-color: ${progressColor};"></div>
                </div>
                <span class="aysa-progress-text">${progress}% Complete</span>
                <div class="aysa-task-actions">
                    <button class="aysa-task-action-btn aysa-goto-btn" onclick="goToTask('${safeTaskId}'); event.stopPropagation();" data-redirect-url="${safeRedirectUrl}">Go To</button>
                    <button class="aysa-task-action-btn aysa-complete-btn" onclick="completeTask('${safeTaskId}'); event.stopPropagation();" data-redirect-url="${safeRedirectUrl}">Complete</button>
                    <button class="aysa-task-detail-btn" onclick="openTaskDetail('${safeTaskId}'); event.stopPropagation();">Details</button>
                    <button class="aysa-delete-btn" onclick="deleteTask(this); event.stopPropagation();">×</button>
                </div>
            </div>
        `;
        
        // Add click handler to open task details (no redirect)
        li.addEventListener('click', function(e) {
            // Don't open details if clicking on buttons (but allow checkbox clicks to open details)
            if (e.target.matches('button, .aysa-task-action-btn, .aysa-goto-btn, .aysa-complete-btn, .aysa-task-detail-btn, .aysa-delete-btn')) {
                return;
            }
            
            // Open task details instead of redirecting - now works for checkbox clicks too
            openTaskDetail(task.id);
        });
        
        // Prevent checkbox from being checked/unchecked and open details instead
        const checkbox = li.querySelector('.aysa-task-checkbox');
        if (checkbox) {
            checkbox.addEventListener('click', function(e) {
                e.preventDefault(); // Prevent checkbox state change
                openTaskDetail(task.id);
            });
        }
        
        return li;
    }

    // Render tasks from backend
    function renderTasks(tasks) {
        if (!automatedTasksList || !manualTasksList) {
            console.warn('[AYSA TASKS] Task containers are not present on this view; skipping task rendering.');
            return;
        }
        
        // Clear both lists
        automatedTasksList.innerHTML = '';
        manualTasksList.innerHTML = '';
        
        // Filter and sort tasks (excluding deleted tasks and domain authority tasks)
        const activeTasks = tasks.filter(task => 
            task.status !== 'deleted' && 
            !(task.title && task.title.toLowerCase().includes('links') && task.title.toLowerCase().includes('authority'))
        );
        
        let automatedCount = 0;
        let manualCount = 0;
        
        activeTasks.forEach(function(task, index) {
            try {
                const taskElement = createTaskItem(task);
                
                if (!taskElement) {
                    console.error('[AYSA TASKS] createTaskItem returned null for task:', task.title);
                    return;
                }
                
                // Add to appropriate list based on flag
                // Note: treating null flag as manual task to ensure all tasks are displayed
                if (task.flag === 'isAi') {
                    automatedTasksList.appendChild(taskElement);
                    automatedCount++;
                } else {
                    // All non-isAi tasks (including null flag) go to manual tasks
                    manualTasksList.appendChild(taskElement);
                    manualCount++;
                }
            } catch (error) {
                console.error('[AYSA TASKS] Error creating task element for:', task.title, error);
            }
        });
        
        // Tasks successfully distributed
    }

    // Render automated tasks with pagination
    function renderAutomatedTasksWithPagination() {
        if (!automatedTasksList) {
            console.warn('[AYSA TASKS] Automated task container missing on current view.');
            return;
        }
        
        // Calculate pagination for automated tasks
        const totalTasks = allAutomatedTasks.length;
        const totalPages = Math.ceil(totalTasks / tasksPerPage);
        const startIndex = (automatedCurrentPage - 1) * tasksPerPage;
        const endIndex = startIndex + tasksPerPage;
        const currentTasks = allAutomatedTasks.slice(startIndex, endIndex);
        
        // Clear automated list
        automatedTasksList.innerHTML = '';
        
        // Render current page tasks
        currentTasks.forEach(function(task) {
            try {
                const taskElement = createTaskItem(task);
                if (taskElement) {
                    automatedTasksList.appendChild(taskElement);
                }
            } catch (error) {
                console.error('[AYSA TASKS] Error creating automated task element:', error);
            }
        });
        
        // Update automated count and show/hide group
        const automatedCountEl = document.getElementById('automated-count');
        const automatedGroup = document.getElementById('automated-tasks-group');
        if (automatedCountEl) automatedCountEl.textContent = currentTasks.length;
        if (automatedGroup) automatedGroup.style.display = totalTasks > 0 ? 'block' : 'none';
        
        // Update pagination info for automated tasks
        updatePaginationInfo(
            totalTasks, 
            startIndex + 1, 
            Math.min(endIndex, totalTasks), 
            automatedCurrentPage, 
            totalPages,
            'automated'
        );
    }

    // Render manual tasks with pagination  
    function renderManualTasksWithPagination() {
        if (!manualTasksList) {
            console.warn('[AYSA TASKS] Manual task container missing on current view.');
            return;
        }
        
        // Calculate pagination for manual tasks
        const totalTasks = allManualTasks.length;
        const totalPages = Math.ceil(totalTasks / tasksPerPage);
        const startIndex = (manualCurrentPage - 1) * tasksPerPage;
        const endIndex = startIndex + tasksPerPage;
        const currentTasks = allManualTasks.slice(startIndex, endIndex);
        
        // Clear manual list
        manualTasksList.innerHTML = '';
        
        // Render current page tasks
        currentTasks.forEach(function(task) {
            try {
                const taskElement = createTaskItem(task);
                if (taskElement) {
                    manualTasksList.appendChild(taskElement);
                }
            } catch (error) {
                console.error('[AYSA TASKS] Error creating manual task element:', error);
            }
        });
        
        // Update manual count and show/hide group
        const manualCountEl = document.getElementById('manual-count');
        const manualGroup = document.getElementById('manual-tasks-group');
        if (manualCountEl) manualCountEl.textContent = currentTasks.length;
        if (manualGroup) manualGroup.style.display = totalTasks > 0 ? 'block' : 'none';
        
        // Update pagination info for manual tasks
        updatePaginationInfo(
            totalTasks, 
            startIndex + 1, 
            Math.min(endIndex, totalTasks), 
            manualCurrentPage, 
            totalPages,
            'manual'
        );
    }

    // Update pagination information and controls for specific task type
    function updatePaginationInfo(total, from, to, page, totalPages, type) {
        const showingEl = document.getElementById(`${type}-showing`);
        const prevBtn = document.getElementById(`prev-${type}-btn`);
        const nextBtn = document.getElementById(`next-${type}-btn`);
        
        if (showingEl) {
            if (total === 0) {
                showingEl.textContent = 'No tasks found';
            } else {
                showingEl.textContent = `Showing ${from}-${to} of ${total} tasks`;
            }
        }
        
        if (prevBtn) {
            prevBtn.disabled = page <= 1;
        }
        
        if (nextBtn) {
            nextBtn.disabled = page >= totalPages;
        }
    }

    // Fetch and render tasks on page load
    function fetchTasks() {
        const projectId = getProjectId();
        if (!projectId) return;
        
        fetch(`${apiBase}/ByProject/${projectId}`)
            .then(res => res.json())
            .then(tasks => {
                // Filter out deleted tasks AND domain authority tasks (moved to Off-Page Optimization)
                const activeTasks = tasks.filter(task => 
                    task.status !== 'deleted' && 
                    !(task.title && task.title.toLowerCase().includes('links') && task.title.toLowerCase().includes('authority'))
                );
                
                // Separate tasks by type
                allAutomatedTasks = activeTasks.filter(task => task.flag === 'isAi');
                allManualTasks = activeTasks.filter(task => task.flag !== 'isAi');
                
                // Reset to first page for both
                automatedCurrentPage = 1;
                manualCurrentPage = 1;
                
                // Render both task types
                renderAutomatedTasksWithPagination();
                renderManualTasksWithPagination();
            })
            .catch(error => {
                console.warn('[AYSA TASKS] Unable to fetch tasks on this view:', error);
            });
    }
    fetchTasks();

    // Automated tasks pagination event listeners
    document.getElementById('prev-automated-btn')?.addEventListener('click', function() {
        if (automatedCurrentPage > 1) {
            automatedCurrentPage--;
            renderAutomatedTasksWithPagination();
        }
    });

    document.getElementById('next-automated-btn')?.addEventListener('click', function() {
        const totalPages = Math.ceil(allAutomatedTasks.length / tasksPerPage);
        if (automatedCurrentPage < totalPages) {
            automatedCurrentPage++;
            renderAutomatedTasksWithPagination();
        }
    });

    // Manual tasks pagination event listeners
    document.getElementById('prev-manual-btn')?.addEventListener('click', function() {
        if (manualCurrentPage > 1) {
            manualCurrentPage--;
            renderManualTasksWithPagination();
        }
    });

    document.getElementById('next-manual-btn')?.addEventListener('click', function() {
        const totalPages = Math.ceil(allManualTasks.length / tasksPerPage);
        if (manualCurrentPage < totalPages) {
            manualCurrentPage++;
            renderManualTasksWithPagination();
        }
    });

    // Global function for "Go To" button
    window.goToTask = function(taskId) {
        const taskElement = document.querySelector(`[data-task-id="${taskId}"]`);
        if (!taskElement) return;
        
        const redirectUrl = taskElement.querySelector('.aysa-goto-btn').dataset.redirectUrl;
        if (redirectUrl) {
            console.log('[AYSA TASK GO TO] Redirecting to:', redirectUrl);
            window.location.href = redirectUrl;
        }
    };

    // Global function for "Complete" button
    window.completeTask = function(taskId) {
        const taskElement = document.querySelector(`[data-task-id="${taskId}"]`);
        if (!taskElement) return;
        
        const taskLabel = taskElement.querySelector('.aysa-task-label').textContent;
        const taskFlag = taskElement.dataset.taskFlag; // Get the original flag
        
        // Mark task as completed
        fetch(`${apiBase}/${taskId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                status: 'done',
                title: taskLabel,
                description: '',
                flag: taskFlag  // ✅ FIXED: Preserve original flag (isAi/isHuman)
            })
        }).then(() => {
            // Only refresh tasks - no redirect
            fetchTasks();
            console.log('[AYSA TASK COMPLETE] Task marked as completed without redirect');
        });
    };

    // Global function for delete task
    window.deleteTask = function(button) {
        const listItem = button.closest('.aysa-task-item');
        const taskId = listItem ? listItem.dataset.taskId : null;
        if (!taskId) return;
        
        const taskLabel = listItem.querySelector('.aysa-task-label').textContent;
        const taskFlag = listItem.dataset.taskFlag; // Get the original flag
        
        fetch(`${apiBase}/${taskId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                status: 'deleted',
                title: taskLabel,
                description: '',
                flag: taskFlag  // ✅ FIXED: Preserve original flag (isAi/isHuman)
            })
        }).then(() => fetchTasks());
    };

    // Global function for task details
    window.openTaskDetail = function(taskId) {
        console.log('[AYSA TASK DETAIL] Opening task detail for ID:', taskId);
        
        // Ensure modal exists first - wait for jQuery section to complete
        setTimeout(() => {
            const taskElement = document.querySelector(`[data-task-id="${taskId}"]`);
            if (!taskElement) {
                console.error('[AYSA TASK DETAIL] Task element not found for ID:', taskId);
                return;
            }
            
            const title = taskElement.dataset.taskTitle;
            const description = taskElement.dataset.taskDescription;
            const flag = taskElement.dataset.taskFlag;
            const status = taskElement.dataset.status;
            const createdDate = taskElement.dataset.taskCreatedDate;
            const updatedDate = taskElement.dataset.taskUpdatedDate;
            
            console.log('[AYSA TASK DETAIL] Task data:', { title, description, flag, status });
            
            // Format dates
            const formatDate = (dateString) => {
                if (!dateString) return 'N/A';
                const date = new Date(dateString);
                return date.toLocaleDateString('en-US', { 
                    year: 'numeric', 
                    month: 'short', 
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            };
            
            // Check if modal exists - try both with jQuery and vanilla JS
            let modal = document.getElementById('aysa-task-detail-modal');
            if (!modal && typeof $ !== 'undefined') {
                modal = $('#aysa-task-detail-modal')[0];
            }
            
            if (!modal) {
                console.error('[AYSA TASK DETAIL] Modal element not found');
                return;
            }
            
            console.log('[AYSA TASK DETAIL] Modal found:', modal);
            
            // Set modal content
            const titleEl = document.getElementById('task-detail-title');
            const descEl = document.getElementById('task-detail-description');
            const typeEl = document.getElementById('task-detail-type');
            const statusEl = document.getElementById('task-detail-status');
            const createdEl = document.getElementById('task-detail-created');
            const updatedEl = document.getElementById('task-detail-updated');
            
            if (titleEl) titleEl.textContent = title;
            if (descEl) descEl.textContent = description || 'No description provided';
            if (typeEl) typeEl.textContent = flag === 'isAi' ? 'Automated Task' : 'Manual Task';
            if (statusEl) statusEl.textContent = status.charAt(0).toUpperCase() + status.slice(1).replace('-', ' ');
            if (createdEl) createdEl.textContent = formatDate(createdDate);
            if (updatedEl) updatedEl.textContent = formatDate(updatedDate);
            
            // Check if this is a domain authority task and show link purchase section
            const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
            const isDomainAuthorityTask = title && title.toLowerCase().includes('links') && 
                                         title.toLowerCase().includes('authority');
            
            console.log('[AYSA TASK DETAIL] Is domain authority task:', isDomainAuthorityTask);
            
            if (isDomainAuthorityTask && linkPurchaseSection) {
                linkPurchaseSection.style.display = 'block';
                // Store task info for later use
                linkPurchaseSection.dataset.taskId = taskId;
                linkPurchaseSection.dataset.taskTitle = title;
                
                // Start auto-polling for progress updates
                setTimeout(() => {
                    if (typeof startProgressPolling === 'function') {
                        startProgressPolling(taskId);
                    }
                }, 100);
            } else if (linkPurchaseSection) {
                linkPurchaseSection.style.display = 'none';
            }
            
            // Show modal using both methods
            console.log('[AYSA TASK DETAIL] Showing modal');
            modal.style.display = 'block';
            
            // Also try jQuery method as backup
            if (typeof $ !== 'undefined') {
                $('#aysa-task-detail-modal').show();
            }
            
        }, 200); // Wait 200ms to ensure modal is created
    };

    // Handle checkbox changes for both task lists
    // COMMENTED OUT: Task checkboxes no longer mark tasks as complete
    // Tasks now only open details when clicked anywhere on the task
    /*
    function handleTaskCheckboxes() {
        document.addEventListener('change', function(e) {
            if (e.target.classList.contains('aysa-task-checkbox')) {
                const listItem = e.target.closest('.aysa-task-item');
                const taskId = listItem ? listItem.dataset.taskId : null;
                if (!taskId) return;
                
                const newStatus = e.target.checked ? 'done' : 'in_progress';
                const taskLabel = listItem.querySelector('.aysa-task-label').textContent;
                
                fetch(`${apiBase}/${taskId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        status: newStatus,
                        title: taskLabel,
                        description: ''
                    })
                }).then(() => fetchTasks());
            }
        });
    }
    
    handleTaskCheckboxes();
    */
});

// --- Domain Authority Action Plan Task Injection ---
document.addEventListener('DOMContentLoaded', function() {
    // Helper to get projectId (from localStorage sau API by domain)
    function getProjectId() {
        console.log('[AYSA DOMAIN AUTHORITY] Getting project ID for domain: ' + window.location.hostname);
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId && parseInt(projectId, 10) > 0) {
            console.log('[AYSA DOMAIN AUTHORITY] Project ID found in localStorage: ' + projectId);
            return parseInt(projectId, 10);
        }
        if (!window.__aysaProjectIdFetchInFlight) {
            window.__aysaProjectIdFetchInFlight = true;
            const domain = window.location.hostname;
            fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/Project/getbydomain/` + domain)
                .then(res => res.ok ? res.json() : null)
                .then(resp => {
                    if (resp && resp.projectId) {
                        localStorage.setItem('aysa_project_id', String(resp.projectId));
                        console.log('[AYSA DOMAIN AUTHORITY] Project ID retrieved from API: ' + resp.projectId);
                    }
                })
                .catch(error => {
                    console.error('[AYSA DOMAIN AUTHORITY] Failed async project ID fetch:', error);
                })
                .finally(() => {
                    window.__aysaProjectIdFetchInFlight = false;
                });
        }
        return 0;
    }

    // Domain Authority tasks have been moved to Off-Page Optimization section
});

// === START PATCH ===
jQuery(function($) {
  console.log('[AYSA PATCH] jQuery patch section started');
  // --- VARIABILE GLOBALE PENTRU TASKURI ---
  const apiBase = `${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks`;
  function getProjectId() {
    let projectId = localStorage.getItem('aysa_project_id');
    if (projectId && parseInt(projectId, 10) > 0) {
      return parseInt(projectId, 10);
    }
    if (!window.__aysaProjectIdFetchInFlight) {
      window.__aysaProjectIdFetchInFlight = true;
      const domain = window.location.hostname;
      fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/Project/getbydomain/` + domain)
        .then(res => res.ok ? res.json() : null)
        .then(resp => {
          if (resp && resp.projectId) {
            localStorage.setItem('aysa_project_id', String(resp.projectId));
            fetchAndInjectAssociationTask();
          }
        })
        .catch(() => {})
        .finally(() => {
          window.__aysaProjectIdFetchInFlight = false;
        });
    }
    return 0;
  }

  // --- Association Task Injection ---
  function injectAssociationTask(toAssociateCount) {
    console.log('[AYSA DOMAIN AUTHORITY] Starting association task injection with count: ' + toAssociateCount);
    
    // Check if automation is enabled
    const automationConfig = window.aysaAutomationConfig || {};
    if (automationConfig.domain_authority_automation) {
      console.log('[AYSA DOMAIN AUTHORITY] Automation enabled, scheduling association task via automation queue');
      if (typeof scheduleAssociationTasks === 'function') {
        scheduleAssociationTasks();
      } else {
        console.error('[AYSA DOMAIN AUTHORITY] scheduleAssociationTasks function not available');
      }
      return;
    }
    
    console.log('[AYSA DOMAIN AUTHORITY] Automation disabled, creating association task via Research Tasks API');
    const automatedTasksList = document.querySelector('.aysa-automated-tasks');
    if (!automatedTasksList) return;
    // Remove any previous association task
    const existing = automatedTasksList.querySelector('li[data-dynamic-task="association-task"]');
    if (existing) existing.remove();
    if (toAssociateCount > 0) {
      const taskTitle = `Associate ${toAssociateCount} keywords with pages/products/categories`;
      const projectId = getProjectId();
      if (projectId) {
        fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks/ByProject/${projectId}`)
          .then(res => res.json())
          .then(tasks => {
            const existingTask = tasks.find(t => t.title === taskTitle && t.status !== 'deleted');
            if (!existingTask) {
              fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  projectId: projectId,
                  title: taskTitle,
                  description: '',
                  status: 'in_progress',
                  flag: 'isAi'
                })
              }).then(() => {
                if (typeof fetchTasks === 'function') fetchTasks();
              });
            } else if (existingTask.status !== 'in_progress') {
              fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks/${existingTask.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  status: 'in_progress',
                  title: taskTitle,
                  description: '',
                  flag: 'isAi'
                })
              }).then(() => {
                if (typeof fetchTasks === 'function') fetchTasks();
              });
            }
          });
      }
    }
  }

  function fetchAndInjectAssociationTask() {
    const projectId = getProjectId();
    if (!projectId) return;
    fetch(`${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/AssociationsTask/ToAssociateCount/${projectId}`)
      .then(res => res.json())
      .then(data => {
        injectAssociationTask(data.toAssociateCount);
      });
  }

  // Rulează la load și la refresh
  fetchAndInjectAssociationTask();
  const refreshBtn = document.querySelector('.aysa-refresh-btn');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', fetchAndInjectAssociationTask);
  }

  // Auto-refresh progress for link purchase tasks
  let progressPollingInterval = null;
  let lastKnownProgress = null;
  
  function startProgressPolling(taskId) {
    // Clear any existing polling
    stopProgressPolling();
    
  console.log('[AYSA PROGRESS] Auto-refresh disabled - manual refresh only');
    
  // No auto-polling - manual refresh only
    
    // Also refresh immediately
    loadLinkPurchaseStatus(taskId, true);
  }
  
  function stopProgressPolling() {
    if (progressPollingInterval) {
      console.log('[AYSA PROGRESS] Stopping auto-refresh');
      clearInterval(progressPollingInterval);
      progressPollingInterval = null;
      lastKnownProgress = null; // Reset progress tracking
    }
  }

  // Link Purchase Functionality
  function loadLinkPurchaseStatus(taskId, silentRefresh = false) {
    const projectId = getProjectId();
    if (!projectId) return;
    
    const statusDiv = document.getElementById('aysa-purchase-status');
    if (statusDiv) {
      statusDiv.innerHTML = '<span style="color:#6b7280;">Loading status...</span>';
    }
    
    // Create FormData for the request
    const formData = new FormData();
    formData.append('action', 'aysa_get_link_purchase_status');
    formData.append('nonce', aysaLinkPurchaseNonce);
    formData.append('task_id', taskId);
    formData.append('project_id', projectId);
    
    fetch(ajaxurl + '?' + new URLSearchParams(formData))
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          const status = data.data;
          document.getElementById('aysa-links-quantity').value = status.links_requested || 1;
          
          // The progress is now updated directly in the ResearchTasks table via backend
          // Refresh task list to get updated progress from API (silent if polling)
          if (typeof fetchTasks === 'function') {
            if (!silentRefresh) {
              console.log('[AYSA PROGRESS] Refreshing task list');
            }
            fetchTasks();
          }
          
          // Check for progress changes and notify user
          const currentProgress = status.links_purchased;
          if (silentRefresh && lastKnownProgress !== null && currentProgress > lastKnownProgress) {
            console.log(`[AYSA PROGRESS] Progress updated: ${lastKnownProgress} → ${currentProgress}`);
            
            // Show a subtle notification
            const progressNotification = document.createElement('div');
            progressNotification.style.cssText = `
              position: fixed;
              top: 20px;
              right: 20px;
              background: #10b981;
              color: white;
              padding: 12px 16px;
              border-radius: 8px;
              box-shadow: 0 4px 12px rgba(0,0,0,0.15);
              z-index: 10000;
              font-size: 14px;
              font-weight: 500;
            `;
            progressNotification.textContent = `🎉 Link purchased! Progress: ${currentProgress}/${status.links_requested}`;
            document.body.appendChild(progressNotification);
            
            // Remove after 3 seconds
            setTimeout(() => {
              if (progressNotification.parentNode) {
                progressNotification.parentNode.removeChild(progressNotification);
              }
            }, 3000);
          }
          lastKnownProgress = currentProgress;
          
          // Check if task should be marked as completed (all links purchased but status not 'done')
          console.log(`[AYSA PROGRESS] Status check: ${status.links_purchased}/${status.links_requested} links, status: '${status.status}'`);
          
          // If link purchase status is 'completed', we need to update ResearchTask status to 'done'
          if (status.status === 'completed') {
            console.log('[AYSA PROGRESS] Link purchase is completed - updating ResearchTask status to done');
            
            // Get task ID from the link purchase section
            const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
            const taskId = linkPurchaseSection ? linkPurchaseSection.dataset.taskId : null;
            
            if (taskId) {
              // Trigger status update to 'done' for ResearchTask
              const statusFormData = new FormData();
              statusFormData.append('action', 'aysa_fix_task_status');
              statusFormData.append('task_id', taskId);
              statusFormData.append('nonce', aysa_ajax.nonce);
              
              // Add task title and description from modal
              const titleEl = document.getElementById('aysa-task-detail-title');
              const descEl = document.getElementById('aysa-task-detail-description');
              
              if (titleEl && titleEl.textContent) {
                statusFormData.append('task_title', titleEl.textContent.trim());
              }
              if (descEl && descEl.textContent) {
                statusFormData.append('task_description', descEl.textContent.trim());
              }
              
              fetch(aysa_ajax.ajax_url, {
                method: 'POST',
                body: statusFormData
              })
              .then(response => response.json())
              .then(statusData => {
                console.log('[AYSA PROGRESS] ResearchTask status update result:', statusData);
                
                if (statusData.success) {
                  console.log('✅ ResearchTask status updated to done');
                  
                  // Show notification
                  const statusNotification = document.createElement('div');
                  statusNotification.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #10b981;
                    color: white;
                    padding: 12px 16px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    z-index: 10000;
                    font-size: 14px;
                    font-weight: 500;
                  `;
                  statusNotification.textContent = '✅ Research task marked as completed!';
                  document.body.appendChild(statusNotification);
                  
                  setTimeout(() => {
                    if (statusNotification.parentNode) {
                      statusNotification.parentNode.removeChild(statusNotification);
                    }
                  }, 3000);
                  
                  // Refresh task list to show updated status
                  if (typeof fetchTasks === 'function') {
                    fetchTasks();
                  }
                } else {
                  console.log('❌ Failed to update ResearchTask status:', statusData.data);
                }
              })
              .catch(error => {
                console.error('[AYSA PROGRESS] Error updating ResearchTask status:', error);
              });
            }
          }
          
          if (status.links_purchased >= status.links_requested && status.status !== 'done' && status.status !== 'completed') {
            console.log('[AYSA PROGRESS] Task at 100% but status not done - triggering status update');
            
            // Get task ID from the link purchase section
            const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
            const taskId = linkPurchaseSection ? linkPurchaseSection.dataset.taskId : null;
            
            if (taskId) {
              // Trigger status update to 'done'
              const statusFormData = new FormData();
              statusFormData.append('action', 'aysa_fix_task_status');
              statusFormData.append('task_id', taskId);
              statusFormData.append('nonce', aysa_ajax.nonce);
              
              fetch(aysa_ajax.ajax_url, {
                method: 'POST',
                body: statusFormData
              })
              .then(response => response.json())
              .then(statusData => {
                console.log('[AYSA PROGRESS] Status update result:', statusData);
                
                if (statusData.success) {
                  console.log('✅ Task status updated to done');
                  
                  // Show notification
                  const statusNotification = document.createElement('div');
                  statusNotification.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #10b981;
                    color: white;
                    padding: 12px 16px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    z-index: 10000;
                    font-size: 14px;
                    font-weight: 500;
                  `;
                  statusNotification.textContent = '✅ Task marked as completed!';
                  document.body.appendChild(statusNotification);
                  
                  setTimeout(() => {
                    if (statusNotification.parentNode) {
                      statusNotification.parentNode.removeChild(statusNotification);
                    }
                  }, 3000);
                  
                  // Refresh task list to show updated status
                  if (typeof fetchTasks === 'function') {
                    fetchTasks();
                  }
                } else {
                  console.log('❌ Failed to update task status:', statusData.data);
                }
              })
              .catch(error => {
                console.error('[AYSA PROGRESS] Error updating task status:', error);
              });
            }
          }
          
          // Check if task is completed and stop polling
          if (status.status === 'done' || status.links_purchased >= status.links_requested) {
            if (!silentRefresh) {
              console.log('[AYSA PROGRESS] Task completed, stopping auto-refresh');
            }
            stopProgressPolling();
            
            // Show completion notification
            if (silentRefresh) {
              const completionNotification = document.createElement('div');
              completionNotification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #059669;
                color: white;
                padding: 12px 16px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 10000;
                font-size: 14px;
                font-weight: 500;
              `;
              completionNotification.textContent = `✅ Task completed! All ${status.links_requested} links purchased.`;
              document.body.appendChild(completionNotification);
              
              setTimeout(() => {
                if (completionNotification.parentNode) {
                  completionNotification.parentNode.removeChild(completionNotification);
                }
              }, 5000);
            }
          }
          
          if (status.status === 'none') {
            statusDiv.innerHTML = '<span style="color:#6b7280;">No purchase request found</span>';
          } else {
            const progress = status.links_purchased + '/' + status.links_requested;
            let statusColor = '#6b7280';
            let statusText = status.status;
            
            if (status.status === 'done') {
              statusColor = '#10b981';
              statusText = 'Completed';
            } else if (status.status === 'completed') {
              statusColor = '#10b981';
              statusText = 'Completed';
            } else if (status.status === 'processing') {
              statusColor = '#f59e0b';
              statusText = 'In Progress';
            } else if (status.status === 'pending') {
              statusColor = '#3b82f6';
              statusText = 'Pending';
            } else if (status.status === 'error') {
              statusColor = '#ef4444';
              statusText = 'Error';
              
              // Check for insufficient credits error details
              if (status.error_details && status.error_details.response) {
                try {
                  const apiResponse = JSON.parse(status.error_details.response);
                  if (apiResponse.message && apiResponse.message.toLowerCase().includes('insufficient credits')) {
                    // Show user-friendly insufficient credits message
                    const requiredCredits = apiResponse.requiredCredits ? (apiResponse.requiredCredits * 100) : 'N/A';
                    const currentCredits = apiResponse.currentCredits ? (apiResponse.currentCredits * 100) : 'N/A';
                    const currentTaskId = taskId; // Make taskId available in template
                    
                    statusDiv.innerHTML = `
                      <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:16px;margin-top:8px;">
                        <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                          <span style="color:#dc2626;font-weight:600;">⚠️ You’ve used all the credits included in your subscription.
To continue, please add more credits or upgrade your plan.</span>
                        </div>
                        <div style="color:#7f1d1d;font-size:14px;margin-bottom:12px;">
                          <strong>Links purchased:</strong> ${status.links_purchased}/${status.links_requested}<br>
                          <strong>Required:</strong> ${requiredCredits} credits<br>
                          <strong>Available:</strong> ${currentCredits} credits
                        </div>
                        <div style="display:flex;gap:8px;flex-wrap:wrap;">
                          <a href="https://demoapp.aysa.ai/credits" target="_blank" style="background:#dc2626;color:white;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;font-weight:500;">Add Credits</a>
                          <a href="https://demoapp.aysa.ai/credits" target="_blank" style="background:#6b7280;color:white;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;font-weight:500;">View Plans</a>
                          <button onclick="resetLinkPurchaseError('${currentTaskId}')" style="background:#059669;color:white;border:none;padding:8px 16px;border-radius:6px;font-size:14px;font-weight:500;cursor:pointer;">Reset Error</button>
                        </div>
                      </div>
                    `;
                    return; // Don't show the default status div
                  }
                } catch (e) {
                  console.log('Could not parse error response:', e);
                }
              }
            }
            
            // Auto-refresh indicator removed (manual refresh only)
              
            statusDiv.innerHTML = `
              <div style="display:flex;align-items:center;gap:8px;">
                <span style="color:${statusColor};font-weight:600;">Status: ${statusText}</span>
                <span style="color:#374151;">Progress: ${progress} links</span>
                ${autoRefreshIndicator}
              </div>
            `;
          }
        } else {
          statusDiv.innerHTML = '<span style="color:#ef4444;">Error loading status</span>';
        }
      })
      .catch(error => {
        console.error('Error loading purchase status:', error);
        if (statusDiv) {
          statusDiv.innerHTML = '<span style="color:#ef4444;">Error loading status</span>';
        }
      });
  }
  
  function saveLinkPurchaseRequest() {
    const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
    if (!linkPurchaseSection) return;
    
    const taskId = linkPurchaseSection.dataset.taskId;
    const taskTitle = linkPurchaseSection.dataset.taskTitle;
    const projectId = getProjectId();
    
    const linksQuantity = parseInt(document.getElementById('aysa-links-quantity').value) || 1;
    
    if (!taskId || !projectId || linksQuantity <= 0) {
      alert('Invalid parameters. Please check your input.');
      return;
    }
    
    const saveBtn = document.getElementById('aysa-save-purchase-request');
    if (saveBtn) {
      saveBtn.disabled = true;
      saveBtn.textContent = 'Saving...';
    }
    
    const formData = new FormData();
    formData.append('action', 'aysa_save_link_purchase_request');
    formData.append('nonce', aysaLinkPurchaseNonce);
    formData.append('task_id', taskId);
    formData.append('project_id', projectId);
    formData.append('task_title', taskTitle);
    formData.append('links_requested', linksQuantity);
    
    fetch(ajaxurl, {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('Link purchase request saved successfully! Links will be purchased automatically over time.');
        loadLinkPurchaseStatus(taskId); // Refresh status
      } else {
        alert('Error saving purchase request: ' + (data.data || 'Unknown error'));
      }
    })
    .catch(error => {
      console.error('Error saving purchase request:', error);
      alert('Error saving purchase request. Please try again.');
    })
    .finally(() => {
      if (saveBtn) {
        saveBtn.disabled = false;
        saveBtn.textContent = 'Save Purchase Request';
      }
    });
  }
  
  // Function to reset link purchase error
  window.resetLinkPurchaseError = function(taskId) {
    if (!confirm('Are you sure you want to reset this error and retry the purchase?')) {
      return;
    }
    
    const formData = new FormData();
    formData.append('action', 'aysa_reset_link_purchase_errors');
    formData.append('nonce', aysaLinkPurchaseNonce);
    
    fetch(ajaxurl, {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('Error has been reset. The purchase will be retried automatically.');
        loadLinkPurchaseStatus(taskId); // Refresh status - this will also update progress
      } else {
        alert('Failed to reset error: ' + (data.data || 'Unknown error'));
      }
    })
    .catch(error => {
      console.error('Reset error failed:', error);
      alert('Failed to reset error. Check console for details.');
    });
  };
  

  // Add event listeners for link purchase functionality
  document.addEventListener('click', function(e) {
    if (e.target && e.target.id === 'aysa-save-purchase-request') {
      saveLinkPurchaseRequest();
    }
    
    if (e.target && e.target.id === 'aysa-refresh-purchase-status') {
      const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
      if (linkPurchaseSection && linkPurchaseSection.dataset.taskId) {
        loadLinkPurchaseStatus(linkPurchaseSection.dataset.taskId);
      }
    }
    
  });

  // Add Task Modal HTML (dacă nu există deja)
  if ($('#aysa-add-task-modal').length === 0) {
    const modalHtml = `
    <div id="aysa-add-task-modal" class="aysa-modal" style="display:none;">
      <div class="aysa-modal-content" style="max-width:400px;">
        <div class="aysa-modal-header" style="background:#1a73e8;color:white;">
          <h3 style="color:white;">Add Task</h3>
          <button class="aysa-modal-close" style="color:white;background:none;border:none;font-size:24px;float:right;">&times;</button>
        </div>
        <div class="aysa-modal-body" style="padding:24px;">
          <div class="aysa-form-group">
            <label for="aysa-task-title">Title <span style="color:#dc3545;">*</span></label>
            <input type="text" id="aysa-task-title" class="aysa-input" placeholder="Task title" required style="width:100%;margin-bottom:12px;">
          </div>
          <div class="aysa-form-group">
            <label for="aysa-task-desc">Description</label>
            <textarea id="aysa-task-desc" class="aysa-input" placeholder="Task description (optional)" style="width:100%;min-height:60px;"></textarea>
          </div>
          <div class="aysa-form-group" style="margin-bottom:12px;">
            <label style="font-weight:500;">Task type:</label><br>
            <label style="margin-right:18px;">
              <input type="radio" name="aysa-task-flag" value="isHuman" checked> Human
            </label>
            <label>
              <input type="radio" name="aysa-task-flag" value="isAi"> AI
            </label>
          </div>
        </div>
        <div class="aysa-modal-footer" style="padding:16px;text-align:right;">
          <button id="aysa-add-task-cancel" class="aysa-button-secondary">Cancel</button>
          <button id="aysa-add-task-save" class="aysa-btn-blue">Add Task</button>
        </div>
      </div>
    </div>`;
    $(document.body).append(modalHtml);
  }

  // Task Detail Modal HTML (dacă nu există deja)
  console.log('[AYSA MODAL] Checking if task detail modal exists');
  if ($('#aysa-task-detail-modal').length === 0) {
    console.log('[AYSA MODAL] Creating task detail modal');
    const detailModalHtml = `
    <div id="aysa-task-detail-modal" class="aysa-modal" style="display:none;">
      <div class="aysa-modal-content" style="max-width:500px;">
        <div class="aysa-modal-header" style="background:#2563eb;color:white;">
          <h3 style="color:white;">Task Details</h3>
          <button class="aysa-modal-close-detail" style="color:white;background:none;border:none;font-size:24px;float:right;">&times;</button>
        </div>
        <div class="aysa-modal-body" style="padding:24px;">
          <div class="aysa-detail-group" style="margin-bottom:16px;">
            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Title:</label>
            <p id="task-detail-title" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;"></p>
          </div>
          <div class="aysa-detail-group" style="margin-bottom:16px;">
            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Description:</label>
            <p id="task-detail-description" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;min-height:60px;"></p>
          </div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;">
            <div class="aysa-detail-group">
              <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Type:</label>
              <p id="task-detail-type" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;"></p>
            </div>
            <div class="aysa-detail-group">
              <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Status:</label>
              <p id="task-detail-status" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;"></p>
            </div>
          </div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
            <div class="aysa-detail-group">
              <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Created:</label>
              <p id="task-detail-created" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid:#e2e8f0;font-size:12px;"></p>
            </div>
            <div class="aysa-detail-group">
              <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Updated:</label>
              <p id="task-detail-updated" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid:#e2e8f0;font-size:12px;"></p>
            </div>
          </div>
          
          <!-- Link Purchase Section (only for domain authority tasks) -->
          <div id="aysa-link-purchase-section" style="display:none;margin-top:20px;padding:16px;background:#f0f9ff;border:1px solid #0ea5e9;border-radius:8px;">
            <h4 style="margin:0 0 12px 0;color:#0369a1;font-size:16px;">🛒 Purchase Links for Domain Authority</h4>
            <div style="margin-bottom:12px;">
              <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Number of links to purchase:</label>
              <input type="number" id="aysa-links-quantity" min="1" max="100" value="1" style="width:100px;padding:6px 8px;border:1px solid #cbd5e1;border-radius:4px;">
              <span style="font-size:12px;color:#64748b;margin-left:8px;">Links will be purchased automatically over time</span>
            </div>
            <div id="aysa-purchase-status" style="margin-bottom:12px;font-size:14px;color:#374151;"></div>
            <div style="display:flex;gap:8px;">
                             <button id="aysa-save-purchase-request" style="background:#10b981;color:white;border:none;border-radius:6px;padding:8px 16px;font-weight:500;cursor:pointer;">Save Purchase Request</button>
               <button id="aysa-refresh-purchase-status" style="background:#6b7280;color:white;border:none;border-radius:6px;padding:8px 16px;font-weight:500;cursor:pointer;">Refresh Status</button>
            </div>
          </div>
        </div>
        <div class="aysa-modal-footer" style="padding:16px;text-align:right;">
          <button id="aysa-task-detail-close" class="aysa-button-secondary">Close</button>
        </div>
      </div>
    </div>    `;
    $(document.body).append(detailModalHtml);
    console.log('[AYSA MODAL] Task detail modal created and appended to body');
  } else {
    console.log('[AYSA MODAL] Task detail modal already exists');
  }
  const $modal = $('#aysa-add-task-modal');
  const $closeBtn = $modal.find('.aysa-modal-close');
  const $cancelBtn = $('#aysa-add-task-cancel');
  const $saveBtn = $('#aysa-add-task-save');

  const $detailModal = $('#aysa-task-detail-modal');
  const $detailCloseBtn = $detailModal.find('.aysa-modal-close-detail');
  const $detailCloseBtnFooter = $('#aysa-task-detail-close');

  // Open add task modal
  $(document).on('click', '.aysa-add-task-btn', function() {
    $modal.show();
    $('#aysa-task-title').val('');
    $('#aysa-task-desc').val('');
  });
  $closeBtn.on('click', function() { $modal.hide(); });
  $cancelBtn.on('click', function(e) { e.preventDefault(); $modal.hide(); });

  // Close detail modal handlers
  $detailCloseBtn.on('click', function() { 
    stopProgressPolling(); 
    $detailModal.hide(); 
  });
  $detailCloseBtnFooter.on('click', function(e) { 
    e.preventDefault(); 
    stopProgressPolling(); 
    $detailModal.hide(); 
  });
  
  // Close modal when clicking outside
  $(document).on('click', '.aysa-modal', function(e) {
    if (e.target === this) {
      stopProgressPolling();
      $(this).hide();
    }
  });
  
  // Stop polling when page unloads
  $(window).on('beforeunload', function() {
    stopProgressPolling();
  });

  // Save task
  $saveBtn.on('click', function(e) {
    e.preventDefault();
    const title = $('#aysa-task-title').val().trim();
    const desc = $('#aysa-task-desc').val().trim();
    const flag = $('input[name="aysa-task-flag"]:checked').val();
    if (!title) {
      $('#aysa-task-title').focus();
      return;
    }
    const projectId = getProjectId();
    fetch(apiBase, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        projectId: projectId,
        title: title,
        description: desc || "",
        status: 'in_progress',
        flag: flag
      })
    })
    .then(res => res.json())
    .then(() => {
      $modal.hide();
      fetchTasks();
    });
  });

  // Task handling is now managed by the main JavaScript functions above
});
// === END PATCH ===
</script>                        
