<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Template for the blog content metabox
 * 
 * @var array $keyword_data Keyword data for the post
 */

// Default values
$keyword_data = isset($keyword_data) ? $keyword_data : array();
$post_id = isset($post->ID) ? $post->ID : 0;

// Define plugin text domain
$text_domain = 'aysa';
?>

<!-- Custom styles for blog content metabox -->
<style>
    .aysa-blog-content-container {
        border: 1px solid #ccd0d4;
        border-radius: 4px;
        background-color: #fff;
        padding: 15px;
        margin-top: 10px;
        box-shadow: 0 1px 1px rgba(0,0,0,0.04);
    }
    
    /* Credits styling for blog metabox */
    .aysa-metabox-credits {
        background: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        padding: 4px 8px;
    }
    
    .aysa-metabox-credits .aysa-credits-component {
        font-size: 12px;
        color: #666;
        margin: 0;
    }
    
    .aysa-metabox-credits .aysa-credits-value {
        font-weight: 500;
    }
    
    .aysa-metabox-credits .aysa-credits-amount {
        color: #008392;
        font-weight: 600;
    }
    
    .aysa-metabox-credits .aysa-loading-spinner {
        display: inline-block;
        width: 12px;
        height: 12px;
        border: 2px solid #f3f3f3;
        border-top: 2px solid #008392;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    .aysa-metabox-credits .aysa-credits-fallback {
        font-size: 12px;
        color: #666;
        font-weight: 500;
        margin: 0;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .aysa-blog-section {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #e1e1e1;
        border-radius: 4px;
        background: #f9f9f9;
    }
    
    .aysa-blog-section h4 {
        margin: 0 0 10px 0;
        font-size: 14px;
        font-weight: 600;
        color: #333;
    }
    
    .aysa-input-group {
        margin-bottom: 15px;
    }
    
    .aysa-input-group label {
        display: block;
        margin-bottom: 5px;
        font-weight: 500;
        color: #333;
    }
    
    .aysa-input-group input,
    .aysa-input-group textarea {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 13px;
    }
    
    .aysa-input-group textarea {
        min-height: 100px;
        resize: vertical;
    }
    
    .aysa-generate-btn {
        background-color: #2ea043 !important;
        color: white !important;
        border: 1px solid #2ea043 !important;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 13px;
        font-weight: 500;
        transition: all 0.2s ease;
        margin-right: 10px;
        margin-bottom: 10px;
    }
    
    .aysa-generate-btn:hover {
        background-color: #238636 !important;
        border-color: #238636 !important;
        transform: translateY(-1px);
    }
    
    .aysa-generate-btn:disabled {
        background-color: #ccc !important;
        border-color: #ccc !important;
        cursor: not-allowed;
        transform: none;
    }
    
    .aysa-content-preview {
        background: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 15px;
        margin-top: 10px;
        max-height: 300px;
        overflow-y: auto;
        font-size: 13px;
        line-height: 1.5;
    }
    
    .aysa-loading {
        display: none;
        text-align: center;
        padding: 20px;
        color: #666;
    }
    
    .aysa-loading.active {
        display: block;
    }
    
    .aysa-spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #2ea043;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-right: 10px;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .aysa-progress-bar {
        width: 100%;
        height: 8px;
        background: #f0f0f0;
        border-radius: 4px;
        margin: 15px 0;
        overflow: hidden;
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    
    .aysa-progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #2ea043, #28a745);
        width: 0%;
        transition: width 0.3s ease;
        border-radius: 4px;
    }
    
    .aysa-step-indicator {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 20px;
        font-size: 12px;
        justify-content: center;
    }
    
    .aysa-step {
        padding: 6px 12px;
        border-radius: 15px;
        background: #f0f0f0;
        color: #666;
        flex: 0 0 auto;
        min-width: 60px;
        text-align: center;
        white-space: nowrap;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    
    .aysa-step.active {
        background: #2ea043;
        color: white;
    }
    
    .aysa-step.completed {
        background: #28a745;
        color: white;
        box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
    }
    
    .aysa-step:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }
    
    .aysa-step.active:hover {
        box-shadow: 0 2px 8px rgba(46, 160, 67, 0.4);
    }
    
    /* Button group styling */
    .aysa-button-group {
        display: flex;
        gap: 10px;
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .aysa-button-group .aysa-generate-btn {
        flex: 1;
        min-width: 200px;
        max-width: 300px;
    }
    
    /* Character count styling */
    .character-count {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
        text-align: right;
    }
    
    .character-count.optimal {
        color: #28a745;
        font-weight: 500;
    }
    
    .character-count.warning {
        color: #ffc107;
        font-weight: 500;
    }
    
    .character-count.error {
        color: #dc3545;
        font-weight: 500;
    }
    
    /* Responsive design for smaller screens */
    @media (max-width: 768px) {
        .aysa-step-indicator {
            justify-content: flex-start;
        }
        
        .aysa-step {
            min-width: 50px;
            padding: 4px 8px;
            font-size: 11px;
        }
        
        .aysa-blog-content-container {
            padding: 10px;
        }
        
        .aysa-button-group {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .aysa-generate-btn {
            width: 100% !important;
            margin-bottom: 0 !important;
            margin-right: 0 !important;
        }
    }
    
    /* Extra small screens */
    @media (max-width: 480px) {
        .aysa-step {
            min-width: 45px;
            padding: 3px 6px;
            font-size: 10px;
        }
        
        .aysa-step-indicator {
            gap: 4px;
        }
    }
</style>

<div class="aysa-blog-content-container aysa-metabox-unified">
    <div class="aysa-metabox-header">
        <div class="aysa-metabox-brand">
            <h2>AYSA Blog Content Generator</h2>
            <span class="aysa-metabox-badge">AI SEO Co-Pilot</span>
        </div>
        <p class="aysa-metabox-subtitle">Generate complete blog content with AI assistance</p>
        <div class="aysa-metabox-credits">
            <?php 
            // Display credits in metabox with fallback
            try {
                if (class_exists('Aysa_Credits_Component')) {
                    echo Aysa_Credits_Component::display();
                } else {
                    echo '<span class="aysa-credits-fallback">Credits: Loading...</span>';
                }
            } catch (Exception $e) {
                echo '<span class="aysa-credits-fallback">Credits: Loading...</span>';
            }
            ?>
        </div>
    </div>
    
    <!-- Credits will be loaded by the main credits component script -->
    
    <!-- Progress indicator -->
    <div class="aysa-step-indicator">
        <div class="aysa-step" data-step="outline">Outline</div>
        <div class="aysa-step" data-step="intro">Intro</div>
        <div class="aysa-step" data-step="content">Content</div>
        <div class="aysa-step" data-step="faq">FAQ</div>
        <div class="aysa-step" data-step="conclusion">Conclusion</div>
        <div class="aysa-step" data-step="meta">Meta</div>
    </div>
    
    <div class="aysa-progress-bar">
        <div class="aysa-progress-fill" id="aysa-progress-fill"></div>
    </div>
    
    <!-- Input Section -->
    <div class="aysa-blog-section">
        <h4>Article Setup</h4>
        
        <div class="aysa-input-group">
            <label for="aysa-article-topic">Article Topic *</label>
            <input type="text" id="aysa-article-topic" placeholder="Enter the main topic for your article" 
                   value="<?php echo isset($keyword_data['article_topic']) ? esc_attr($keyword_data['article_topic']) : ''; ?>">
        </div>
        
        <div class="aysa-input-group">
            <label for="aysa-primary-keyword">Primary Keyword *</label>
            <input type="text" id="aysa-primary-keyword" placeholder="Main keyword for SEO optimization" 
                   value="<?php echo isset($keyword_data['keyword']) ? esc_attr($keyword_data['keyword']) : ''; ?>">
        </div>
        
        <div class="aysa-input-group">
            <label for="aysa-entity-second-keyword">Secondary Keywords</label>
            
            <!-- Hidden input field for JavaScript compatibility -->
            <input type="hidden" id="aysa-entity-second-keyword" name="aysa_secondary_keywords" 
                   value="<?php 
                   // Check multiple sources for secondary keywords data
                   $secondary_keywords = '';
                   if (isset($keyword_data['second_keyword'])) {
                       $secondary_keywords = $keyword_data['second_keyword'];
                   } elseif (isset($keyword_data['aysa_secondary_keywords'])) {
                       $secondary_keywords = $keyword_data['aysa_secondary_keywords'];
                   } elseif (isset($post->ID)) {
                       $secondary_keywords = get_post_meta($post->ID, 'aysa_secondary_keywords', true);
                       if (empty($secondary_keywords)) {
                           $secondary_keywords = get_post_meta($post->ID, 'aysa_second_keyword', true);
                       }
                   }
                   echo esc_attr($secondary_keywords);
                   ?>">
            
            <!-- Container for secondary keyword tags (will be populated by JavaScript) -->
            <div id="secondary-keywords-container" style="margin-top: 10px;"></div>
        </div>
        
        <div class="aysa-input-group">
            <label for="aysa-local-specifics">Local Specifics</label>
            <input type="text" id="aysa-local-specifics" placeholder="Local context (e.g., Bucharest, Romania)" 
                   value="<?php echo isset($keyword_data['local_specifics']) ? esc_attr($keyword_data['local_specifics']) : ''; ?>">
        </div>
        
        <!-- Force Regenerate Secondary Keywords Option -->
        <div style="margin-bottom: 15px; margin-top: 15px; padding: 10px; background: #f9f9f9; border-radius: 5px; border: 1px solid #ddd;">
            <label style="display: flex; align-items: center; font-size: 13px; color: #666; cursor: pointer;">
                <input type="checkbox" id="aysa-force-regenerate-secondary" style="margin-right: 8px; margin-top: 0;">
                <span style="user-select: none;">Force regenerate secondary keywords (even if they exist)</span>
            </label>
            <div style="font-size: 11px; color: #999; margin-top: 3px; margin-left: 21px;">
                Check this to generate new secondary keywords even if you already have some
            </div>
        </div>
        
        <div style="text-align: center; margin-top: 20px;" class="aysa-button-group">
            <button type="button" class="aysa-generate-btn" id="aysa-generate-all-content">
                <span class="aysa-spinner" style="display: none;"></span>
                Generate Complete Article
                <span class="aysa-credit-badge cost-very-high">75 cr</span>
            </button>
            <button type="button" class="aysa-generate-btn" id="aysa-generate-step-by-step" style="background-color: #0073aa !important; border-color: #0073aa !important;">
                Generate Step by Step
                <span class="aysa-credit-badge cost-very-high">75 cr</span>
            </button>
        </div>
        
        <div class="aysa-loading" id="aysa-loading">
            <div class="aysa-spinner"></div>
            <span id="aysa-loading-text">Generating content...</span>
        </div>
    </div>
    
    <!-- Meta SEO Fields Section -->
    <div class="aysa-blog-section">
        <h4>SEO Meta Fields</h4>
        <p style="font-size: 12px; color: #666; margin-bottom: 15px;">These fields will be populated automatically when generating content, but you can also edit them manually.</p>
        
        <div class="aysa-input-group">
            <label for="aysa-meta-title">Meta Title</label>
            <div class="character-count meta-subtitle" id="aysa-blog-meta-title-char-count">
                <span class="char-count">0</span>/60 characters
                <span class="char-status">Outside recommended range (50-60)</span>
            </div>
            <input type="text" id="aysa-meta-title" name="aysa_meta_title" placeholder="Meta title for SEO" 
                   value="<?php 
                   // Check multiple sources for meta title data
                   $meta_title = '';
                   if (isset($keyword_data['meta_title'])) {
                       $meta_title = $keyword_data['meta_title'];
                   } elseif (isset($post->ID)) {
                       $meta_title = get_post_meta($post->ID, 'aysa_meta_title', true);
                   }
                   echo esc_attr($meta_title);
                   ?>">
        </div>
        
        <div class="aysa-input-group">
            <label for="aysa-meta-description">Meta Description</label>
            <div class="character-count meta-subtitle" id="aysa-blog-meta-description-char-count">
                <span class="char-count">0</span>/160 characters
                <span class="char-status">Outside recommended range (150-160)</span>
            </div>
            <textarea id="aysa-meta-description" name="aysa_meta_description" rows="3" placeholder="Meta description for SEO"><?php 
            // Check multiple sources for meta description data
            $meta_description = '';
            if (isset($keyword_data['meta_description'])) {
                $meta_description = $keyword_data['meta_description'];
            } elseif (isset($post->ID)) {
                $meta_description = get_post_meta($post->ID, 'aysa_meta_description', true);
            }
            echo esc_textarea($meta_description);
            ?></textarea>
        </div>
        
        <div class="aysa-input-group">
            <label for="aysa-url-recomandat">Recommended URL</label>
            <input type="text" id="aysa-url-recomandat" name="aysa_url_recomandat" placeholder="Recommended URL slug" 
                   value="<?php 
                   // Check multiple sources for URL recomandat data
                   $url_recomandat = '';
                   if (isset($keyword_data['url_recomandat'])) {
                       $url_recomandat = $keyword_data['url_recomandat'];
                   } elseif (isset($post->ID)) {
                       $url_recomandat = get_post_meta($post->ID, 'aysa_url_recomandat', true);
                   }
                   echo esc_attr($url_recomandat);
                   ?>">
            <div style="font-size: 12px; color: #666; margin-top: 3px;">
                Example: domain.com/<strong>recommended-url-slug</strong>
            </div>
        </div>
    </div>

    <!-- Success Message -->
    <div id="aysa-generated-content" style="display: none;">
        <div class="aysa-success-message" style="background: #d1edff; border-left: 4px solid #0073aa; padding: 12px 16px; margin: 15px 0; border-radius: 4px;">
            <p style="margin: 0; color: #0073aa; font-weight: 500;">
                ✅ Content generated and inserted into editor! 
                <button type="button" class="aysa-generate-btn" id="aysa-copy-content" style="background: #0073aa; border: 1px solid #0073aa; color: white; padding: 4px 12px; margin-left: 10px; font-size: 12px; border-radius: 3px;">
                    Copy to Clipboard
                </button>
                <button type="button" class="aysa-generate-btn" id="aysa-regenerate-content" style="background: none; border: 1px solid #0073aa; color: #0073aa; padding: 4px 12px; margin-left: 5px; font-size: 12px; border-radius: 3px;">
                    Generate Again
                </button>
            </p>
        </div>
        
        <!-- Hidden textarea with generated content for copying -->
        <textarea id="aysa-generated-full-content" style="display: none;"></textarea>
    </div>
</div>

<!-- Add nonce field for security -->
<input type="hidden" id="aysa-blog-content-nonce" value="<?php echo wp_create_nonce('aysa_metabox_nonce'); ?>">
<input type="hidden" id="aysa-post-id" value="<?php echo $post_id; ?>">

<script>
jQuery(document).ready(function($) {
    if (typeof AysaBlogContent !== 'undefined') {
        AysaBlogContent.init();
    }
    
    // Initialize character count functionality
    initCharacterCount();
    
    // Make character count functions globally available
    window.updateMetaTitleCount = null;
    window.updateMetaDescCount = null;
    
    function initCharacterCount() {
        // Meta Title Character Count (50-60 optimal)
        const metaTitleInput = document.getElementById('aysa-meta-title');
        const metaTitleCount = document.getElementById('aysa-blog-meta-title-char-count');
        
        if (metaTitleInput && metaTitleCount) {
            window.updateMetaTitleCount = function() {
                const length = metaTitleInput.value.length;
                const charSpan = metaTitleCount.querySelector('.char-count');
                const statusSpan = metaTitleCount.querySelector('.char-status');
                if (charSpan) charSpan.textContent = length;
                
                // Color coding for meta title (50-60 optimal)
                metaTitleCount.classList.remove('is-optimal', 'is-warning', 'is-error');
                if (length >= 50 && length <= 60) {
                    metaTitleCount.classList.add('is-optimal');
                    if (statusSpan) statusSpan.textContent = 'In recommended range (50-60)';
                } else if ((length >= 40 && length < 50) || (length > 60 && length <= 70)) {
                    metaTitleCount.classList.add('is-warning');
                    if (statusSpan) statusSpan.textContent = 'Close to recommended range (50-60)';
                } else if (length < 40 || length > 70) {
                    metaTitleCount.classList.add('is-error');
                    if (statusSpan) statusSpan.textContent = 'Outside recommended range (50-60)';
                }
            };
            
            metaTitleInput.addEventListener('input', window.updateMetaTitleCount);
            metaTitleInput.addEventListener('keyup', window.updateMetaTitleCount);
            metaTitleInput.addEventListener('paste', () => setTimeout(window.updateMetaTitleCount, 10));
            window.updateMetaTitleCount(); // Initial count
        }
        
        // Meta Description Character Count (150-160 optimal)
        const metaDescInput = document.getElementById('aysa-meta-description');
        const metaDescCount = document.getElementById('aysa-blog-meta-description-char-count');
        
        if (metaDescInput && metaDescCount) {
            window.updateMetaDescCount = function() {
                const length = metaDescInput.value.length;
                const charSpan = metaDescCount.querySelector('.char-count');
                const statusSpan = metaDescCount.querySelector('.char-status');
                if (charSpan) charSpan.textContent = length;
                
                // Color coding for meta description (150-160 optimal)
                metaDescCount.classList.remove('is-optimal', 'is-warning', 'is-error');
                if (length >= 150 && length <= 160) {
                    metaDescCount.classList.add('is-optimal');
                    if (statusSpan) statusSpan.textContent = 'In recommended range (150-160)';
                } else if ((length >= 140 && length < 150) || (length > 160 && length <= 170)) {
                    metaDescCount.classList.add('is-warning');
                    if (statusSpan) statusSpan.textContent = 'Close to recommended range (150-160)';
                } else if (length < 140 || length > 170) {
                    metaDescCount.classList.add('is-error');
                    if (statusSpan) statusSpan.textContent = 'Outside recommended range (150-160)';
                }
            };
            
            metaDescInput.addEventListener('input', window.updateMetaDescCount);
            metaDescInput.addEventListener('keyup', window.updateMetaDescCount);
            metaDescInput.addEventListener('paste', () => setTimeout(window.updateMetaDescCount, 10));
            window.updateMetaDescCount(); // Initial count
        }
        
        console.log('✅ Character count functionality initialized for blog metabox');
    }
    
    // ✅ Auto-trigger content generation if coming from Content Strategy
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('aysa_auto_generate') === '1') {
        console.log('🚀 [AYSA] Auto-trigger detected - URL parameter found!');
        console.log('🚀 [AYSA] Current URL:', window.location.href);
        
        // Function to try clicking the button
        function tryClickGenerateButton(attempts = 0) {
            const maxAttempts = 10; // Try for up to 10 seconds
            
            console.log(`🔄 [AYSA] Attempt ${attempts + 1}/${maxAttempts} to find generate button...`);
            
            const generateButton = document.getElementById('aysa-generate-all-content');
            
            if (generateButton) {
                console.log('✅ [AYSA] Button found! Checking if enabled...');
                console.log('✅ [AYSA] Button disabled?', generateButton.disabled);
                
                if (!generateButton.disabled) {
                    console.log('✅ [AYSA] Clicking "Generate Complete Article" button NOW!');
                    generateButton.click();
                    
                    // Remove the parameter from URL to prevent re-triggering on refresh
                    const cleanUrl = new URL(window.location);
                    cleanUrl.searchParams.delete('aysa_auto_generate');
                    window.history.replaceState({}, document.title, cleanUrl);
                    console.log('✅ [AYSA] Auto-trigger complete! URL cleaned.');
                } else {
                    console.warn('⚠️ [AYSA] Button found but disabled, retrying...');
                    if (attempts < maxAttempts) {
                        setTimeout(() => tryClickGenerateButton(attempts + 1), 1000);
                    }
                }
            } else {
                console.warn(`⚠️ [AYSA] Generate button not found yet (attempt ${attempts + 1}/${maxAttempts})`);
                if (attempts < maxAttempts) {
                    setTimeout(() => tryClickGenerateButton(attempts + 1), 1000);
                } else {
                    console.error('❌ [AYSA] Failed to find generate button after 10 attempts');
                }
            }
        }
        
        // Start trying after initial page load
        setTimeout(() => tryClickGenerateButton(), 1000);
    }
});
</script>
