/**
 * Generated Blog History - JavaScript functionality
 */

document.addEventListener('DOMContentLoaded', function() {
    // Expose nonces for AJAX calls
    window.blog82ai_ajax_nonce = blogHistoryData.ajaxNonce;
    window.blog82ai_regenerate_nonce = blogHistoryData.regenerateNonce;
    
    // Filter functionality
    const categoryFilter = document.getElementById('filter-category');
    const statusFilter = document.getElementById('filter-status');
    const dateFilter = document.getElementById('filter-date');
    const searchInput = document.getElementById('search-blogs');

    function applyFilters() {
        const params = new URLSearchParams();
        // Use the main plugin page and tab/subtab parameters so WordPress recognizes the route
        params.set('page', 'blogibot');
        params.set('tab', 'ai_blog');
        params.set('subtab', 'generated_blogs_history');

        if (categoryFilter.value) params.set('filter_category', categoryFilter.value);
        if (statusFilter.value) params.set('filter_status', statusFilter.value);
        if (dateFilter.value) params.set('filter_date', dateFilter.value);
        if (searchInput.value) params.set('search_blogs', searchInput.value);

        window.location.href = '?' + params.toString();
    }

    categoryFilter.addEventListener('change', applyFilters);
    statusFilter.addEventListener('change', applyFilters);
    dateFilter.addEventListener('change', applyFilters);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            applyFilters();
        }
    });

    // Select all functionality
    const selectAllCheckbox = document.getElementById('select-all-blogs');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.blog-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }

    // Make applyFilters globally available
    window.applyFilters = applyFilters;
});

function applyFilters() {
    // This function is now defined above and made global
    if (window.applyFilters) {
        window.applyFilters();
    }
}

function sortTable(column) {
    // Implementation for table sorting would be added here
}

function regenerateTitle(id) {
    // Use modal, call server to get generated titles, and let user pick one to save
    const nonce = blogHistoryData.ajaxNonce;
    const editNonce = blogHistoryData.regenerateNonce;

    try {
        const checkbox = document.querySelector('input.blog-checkbox[value="' + id + '"]');
        const row = checkbox ? checkbox.closest('tr') : null;
        const titleAnchor = row ? row.querySelector('td strong a') : null;
        const currentTitle = titleAnchor ? titleAnchor.textContent.trim() : '';

        Blog82AI_Modal.showLoading('Generating title suggestions...');

        const form = new FormData();
        form.append('action', 'blog82ai_fetch_regenerated_titles');
        form.append('security', nonce);
        form.append('blog_id', id);
        form.append('title', currentTitle);

        fetch(ajaxurl, {
            method: 'POST',
            body: form
        }).then(res => res.json())
        .then(data => {
            Blog82AI_Modal.closeLoading();
            if (!data.success) {
                Blog82AI_Modal.showError('Failed', data.data || 'Could not get title suggestions');
                return;
            }

            const suggestions = data.data.generated_titles || [];
            if (!Array.isArray(suggestions) || suggestions.length === 0) {
                Blog82AI_Modal.showError('No Suggestions', 'The API did not return any title suggestions.');
                return;
            }

            // Clean up titles - remove markdown list markers (* or -) and trim whitespace
            const cleanedSuggestions = suggestions.map(t => {
                if (typeof t === 'string') {
                    return t.replace(/^\s*[\*\-]\s*/, '').trim();
                }
                return t;
            });

            // Build selection modal
            const modalId = 'blog82ai-title-suggestions-modal';
            let existing = document.getElementById(modalId);
            if (existing) existing.remove();

            const optionsHtml = cleanedSuggestions.map((t, idx) => `<div class="blog82ai-title-option" data-idx="${idx}" style="padding:10px;border-radius:6px;border:1px solid #eee;margin-bottom:8px;cursor:pointer;">${t}</div>`).join('');

            const modalHtml = `
                <div id="${modalId}" style="position: fixed; top:0; left:0; right:0; bottom:0; background: rgba(0,0,0,0.5); z-index:100100; display:flex; align-items:center; justify-content:center;">
                    <div style="background:#fff;padding:20px;border-radius:8px;max-width:700px;width:100%;">
                        <h3 style="margin-top:0;">Choose a new title</h3>
                        <p style="color:#666;margin-top:0;margin-bottom:12px;">Select one of the suggested titles below to apply to the post.</p>
                        <div style="max-height:320px;overflow:auto;margin-bottom:12px;">${optionsHtml}</div>
                        <div style="text-align:right;">
                            <button id="blog82ai-title-suggestions-cancel" class="button">Cancel</button>
                            <button id="blog82ai-title-suggestions-apply" class="button button-primary" disabled style="margin-left:8px;">Apply</button>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);

            // Selection handling: allow browsing without immediate confirm
            let selectedIndex = -1;
            const modalEl = document.getElementById(modalId);
            const optionEls = modalEl.querySelectorAll('.blog82ai-title-option');
            const applyBtn = document.getElementById('blog82ai-title-suggestions-apply');
            const cancelBtn = document.getElementById('blog82ai-title-suggestions-cancel');

            const clearSelection = () => {
                optionEls.forEach(o => {
                    o.style.background = '';
                    o.style.borderColor = '#eee';
                });
                selectedIndex = -1;
                if (applyBtn) applyBtn.disabled = true;
            };

            optionEls.forEach(function(el, idx) {
                el.addEventListener('click', function() {
                    // Mark visual selection
                    optionEls.forEach(o => { o.style.background = ''; o.style.borderColor = '#eee'; });
                    this.style.background = '#f5f8fb';
                    this.style.borderColor = '#cbd5e0';
                    selectedIndex = idx;
                    if (applyBtn) applyBtn.disabled = false;
                });

                // Allow keyboard navigation/focus
                el.setAttribute('tabindex', '0');
                el.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        this.click();
                    }
                });
            });

            cancelBtn.onclick = function() {
                const m = document.getElementById(modalId);
                if (m) m.remove();
            };

            applyBtn.onclick = function() {
                if (selectedIndex === -1) return;
                const chosen = cleanedSuggestions[selectedIndex];

                // Hide the selection modal so the confirmation modal appears on top
                const selectionModal = document.getElementById(modalId);
                if (selectionModal) selectionModal.style.display = 'none';

                // Confirm and save. If user cancels, re-show the selection modal
                Blog82AI_Modal.showConfirm('Apply Title', 'Apply the selected title to this blog post?', function() {
                    const saveForm = new FormData();
                    saveForm.append('action', 'regenerate_blog_title');
                    saveForm.append('_wpnonce', editNonce);
                    saveForm.append('blog_id', id);
                    saveForm.append('new_title', chosen);

                    Blog82AI_Modal.showLoading('Saving new title...');
                    fetch(ajaxurl, { method: 'POST', body: saveForm })
                    .then(r => r.json())
                    .then(res => {
                        Blog82AI_Modal.closeLoading();
                        if (!res.success) {
                            Blog82AI_Modal.showError('Failed', res.data || 'Could not save new title');
                            // If save failed, show the selection modal again so user can retry
                            if (selectionModal) selectionModal.style.display = 'flex';
                            return;
                        }
                        // Update UI title in the table row
                        if (titleAnchor) titleAnchor.textContent = chosen;
                        // Remove modal
                        const m = document.getElementById(modalId);
                        if (m) m.remove();
                        Blog82AI_Modal.showSuccess('Saved', 'Title updated successfully', true);
                    })
                    .catch(err => {
                        Blog82AI_Modal.closeLoading();
                        Blog82AI_Modal.showError('Error', 'Network error while saving title');
                        console.error(err);
                        if (selectionModal) selectionModal.style.display = 'flex';
                    });
                }, function() {
                    // onCancel: re-show the selection modal so the user can pick another suggestion
                    const m = document.getElementById(modalId);
                    if (m) m.style.display = 'flex';
                });
            };
        }).catch(err => {
            Blog82AI_Modal.closeLoading();
            Blog82AI_Modal.showError('Error', 'Network error while generating titles');
            console.error(err);
        });
    } catch (e) {
        console.error(e);
        Blog82AI_Modal.closeLoading();
        Blog82AI_Modal.showError('Error', 'An unexpected error occurred');
    }
}

function regenerateImage(id) {
    // Fetch regenerated image from server, show preview modal, and apply on confirmation
    const nonce = blogHistoryData.ajaxNonce;

    try {
        const checkbox = document.querySelector('input.blog-checkbox[value="' + id + '"]');
        const row = checkbox ? checkbox.closest('tr') : null;
        const titleAnchor = row ? row.querySelector('td strong a') : null;
        const currentTitle = titleAnchor ? titleAnchor.textContent.trim() : '';

        Blog82AI_Modal.showLoading('Generating image preview...');

        const form = new FormData();
        form.append('action', 'blog82ai_fetch_regenerated_image');
        form.append('security', nonce);
        form.append('blog_id', id);
        form.append('title', currentTitle);

        fetch(ajaxurl, { method: 'POST', body: form })
        .then(r => r.json())
        .then(function(resp) {
            Blog82AI_Modal.closeLoading();
            
            if (!resp || !resp.success) {
                Blog82AI_Modal.showError('Failed', resp && resp.data ? resp.data : 'Could not get regenerated image');
                return;
            }

            const imageUrl = resp.data.image_url || '';
            const imageDescription = resp.data.image_description || '';
            const mimeType = resp.data.mime_type || 'image/png';
            const filename = resp.data.filename || '';
            const isTemporary = resp.data.is_temporary !== false;
            const expiresAt = resp.data.expires_at || '';

            if (!imageUrl) {
                Blog82AI_Modal.showError('Failed', 'No image URL returned from API');
                return;
            }

            // Build image preview modal
            const modalId = 'blog82ai-image-preview-modal';
            let existing = document.getElementById(modalId);
            if (existing) existing.remove();

            const modalHtml = `
                <div id="${modalId}" style="position: fixed; top:0; left:0; right:0; bottom:0; background: rgba(0,0,0,0.55); z-index:100100; display:flex; align-items:center; justify-content:center;padding:20px;">
                    <div style="background:#fff;padding:24px;border-radius:8px;max-width:900px;width:100%;max-height:85vh;overflow:hidden;box-shadow:0 10px 30px rgba(0,0,0,0.25);display:flex;flex-direction:column;">
                        <h3 style="margin:0 0 16px 0;font-size:20px;">Regenerated Image Preview</h3>
                        <div style="flex:1;overflow:auto;border:1px solid #e5e7eb;padding:20px;border-radius:6px;background:#fafafa;text-align:center;">
                            <img src="${imageUrl}" alt="${imageDescription}" style="max-width:100%;height:auto;border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.1);" />
                        </div>
                        <div style="margin-top:16px;padding-top:16px;border-top:1px solid #eee;">
                            <div style="font-size:13px;color:#666;margin-bottom:8px;"><strong>Description:</strong> ${imageDescription || '—'}</div>
                            <div style="font-size:13px;color:#666;margin-bottom:8px;"><strong>Filename:</strong> ${filename || '—'}</div>
                            <div style="font-size:13px;color:#666;margin-bottom:8px;"><strong>Type:</strong> ${mimeType}</div>
                            ${isTemporary ? `<div style="font-size:12px;color:#d97706;margin-top:8px;">⚠️ This is a temporary image. Click Apply to save it permanently to your media library.</div>` : ''}
                        </div>
                        <div style="text-align:right;margin-top:16px;">
                            <button id="blog82ai-image-preview-cancel" class="button">Cancel</button>
                            <button id="blog82ai-image-preview-apply" class="button button-primary" style="margin-left:8px;">Apply & Save to Media</button>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);

            const cancelBtn = document.getElementById('blog82ai-image-preview-cancel');
            const applyBtn = document.getElementById('blog82ai-image-preview-apply');
            const selectionModal = document.getElementById(modalId);

            cancelBtn.onclick = function() {
                const m = document.getElementById(modalId);
                if (m) m.remove();
            };

            applyBtn.onclick = function() {
                // Hide preview modal, show confirm modal on top
                if (selectionModal) selectionModal.style.display = 'none';

                Blog82AI_Modal.showConfirm('Apply Regenerated Image', 'This will set the generated image as the featured image for this post. Continue?', function() {
                    const saveForm = new FormData();
                    saveForm.append('action', 'blog82ai_save_regenerated_image');
                    saveForm.append('security', nonce);
                    saveForm.append('blog_id', id);
                    saveForm.append('image_url', imageUrl);
                    saveForm.append('filename', filename);
                    saveForm.append('mime_type', mimeType);
                    saveForm.append('description', imageDescription);
                    
                    // Pass base64_image if available (for base64-encoded API responses)
                    if (resp.data.base64_image) {
                        saveForm.append('base64_image', resp.data.base64_image);
                    }

                    Blog82AI_Modal.showLoading('Saving image to media library...');
                    fetch(ajaxurl, { method: 'POST', body: saveForm })
                    .then(r => r.json())
                    .then(function(sr) {
                        Blog82AI_Modal.closeLoading();
                        if (!sr || !sr.success) {
                            Blog82AI_Modal.showError('Failed to save', sr && sr.data ? sr.data : 'Could not save image');
                            if (selectionModal) selectionModal.style.display = 'flex';
                            return;
                        }
                        Blog82AI_Modal.showSuccess('Image saved!', 'Featured image updated successfully.');
                        if (selectionModal) selectionModal.remove();
                        // Optionally reload to show new thumbnail
                        setTimeout(() => location.reload(), 1500);
                    })
                    .catch(function(err) {
                        Blog82AI_Modal.closeLoading();
                        Blog82AI_Modal.showError('Error', 'Network error: ' + err.message);
                        if (selectionModal) selectionModal.style.display = 'flex';
                    });
                }, function() {
                    // User canceled confirm, restore preview modal
                    if (selectionModal) selectionModal.style.display = 'flex';
                });
            };
        })
        .catch(function(err) {
            Blog82AI_Modal.closeLoading();
            Blog82AI_Modal.showError('Error', 'Network error: ' + err.message);
        });
    } catch (err) {
        Blog82AI_Modal.closeLoading();
        Blog82AI_Modal.showError('Error', err.message);
    }
}

function regenerateContent(id) {
    // Fetch regenerated content from server, show preview modal, and apply on confirmation
    const nonce = blogHistoryData.ajaxNonce;
    const editNonce = blogHistoryData.contentRegenerateNonce;

    try {
        const checkbox = document.querySelector('input.blog-checkbox[value="' + id + '"]');
        const row = checkbox ? checkbox.closest('tr') : null;
        const titleAnchor = row ? row.querySelector('td strong a') : null;
        const currentTitle = titleAnchor ? titleAnchor.textContent.trim() : '';

        Blog82AI_Modal.showLoading('Generating content preview...');

        const form = new FormData();
        form.append('action', 'blog82ai_fetch_regenerated_content');
        form.append('security', nonce);
        form.append('blog_id', id);
        form.append('title', currentTitle);

        fetch(ajaxurl, { method: 'POST', body: form })
        .then(r => r.json())
        .then(function(resp) {
            Blog82AI_Modal.closeLoading();
            
            if (!resp || !resp.success) {
                Blog82AI_Modal.showError('Failed', resp && resp.data ? resp.data : 'Could not get regenerated content');
                return;
            }

            const contentHtml = resp.data.blog_content || '';
            const metaTitle = resp.data.meta_title || '';
            const metaDescription = resp.data.meta_description || '';
            const focusKeywords = resp.data.focus_keywords || '';
            const tags = resp.data.tags || '';

            // Build simple content preview modal
            const modalId = 'blog82ai-content-preview-modal';
            let existing = document.getElementById(modalId);
            if (existing) existing.remove();

            const modalHtml = `
                <div id="${modalId}" style="position: fixed; top:0; left:0; right:0; bottom:0; background: rgba(0,0,0,0.55); z-index:100100; display:flex; align-items:center; justify-content:center;padding:20px;">
                    <div style="background:#fff;padding:24px;border-radius:8px;max-width:900px;width:100%;max-height:85vh;overflow:hidden;box-shadow:0 10px 30px rgba(0,0,0,0.25);display:flex;flex-direction:column;">
                        <h3 style="margin:0 0 16px 0;font-size:20px;">Regenerated Content Preview</h3>
                        <div style="flex:1;overflow:auto;border:1px solid #e5e7eb;padding:20px;border-radius:6px;background:#fafafa;">
                            <div id="blog82ai-content-display" style="background:#fff;padding:16px;border-radius:4px;line-height:1.6;color:#222;font-size:15px;">${contentHtml}</div>
                        </div>
                        <div style="margin-top:16px;padding-top:16px;border-top:1px solid #eee;">
                            <div style="font-size:13px;color:#666;margin-bottom:12px;"><strong>Meta title:</strong> ${metaTitle || '—'}</div>
                            <div style="font-size:13px;color:#666;margin-bottom:12px;"><strong>Meta description:</strong> ${metaDescription || '—'}</div>
                            <div style="font-size:13px;color:#666;margin-bottom:12px;"><strong>Focus keywords:</strong> ${focusKeywords || '—'} &nbsp; <strong>Tags:</strong> ${tags || '—'}</div>
                        </div>
                        <div style="text-align:right;margin-top:16px;">
                            <button id="blog82ai-content-preview-cancel" class="button">Cancel</button>
                            <button id="blog82ai-content-preview-apply" class="button button-primary" style="margin-left:8px;">Apply</button>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);

            const cancelBtn = document.getElementById('blog82ai-content-preview-cancel');
            const applyBtn = document.getElementById('blog82ai-content-preview-apply');
            const selectionModal = document.getElementById(modalId);

            cancelBtn.onclick = function() {
                const m = document.getElementById(modalId);
                if (m) m.remove();
            };

            applyBtn.onclick = function() {
                // Hide preview modal, show confirm modal on top
                if (selectionModal) selectionModal.style.display = 'none';

                Blog82AI_Modal.showConfirm('Apply Regenerated Content', 'This will overwrite the existing post content. Continue?', function() {
                    const saveForm = new FormData();
                    saveForm.append('action', 'regenerate_blog_content');
                    saveForm.append('_wpnonce', editNonce);
                    saveForm.append('blog_id', id);
                    saveForm.append('new_content', contentHtml);
                    saveForm.append('meta_title', metaTitle);
                    saveForm.append('meta_description', metaDescription);
                    saveForm.append('focus_keywords', focusKeywords);
                    saveForm.append('tags', tags);

                    Blog82AI_Modal.showLoading('Saving content...');
                    fetch(ajaxurl, { method: 'POST', body: saveForm })
                    .then(r => r.json())
                    .then(function(sr) {
                        Blog82AI_Modal.closeLoading();
                        if (!sr || !sr.success) {
                            Blog82AI_Modal.showError('Failed to save', sr && sr.data ? sr.data : 'Could not save content');
                            if (selectionModal) selectionModal.style.display = 'flex';
                            return;
                        }

                        // Remove modal and show success
                        const m = document.getElementById(modalId);
                        if (m) m.remove();
                        Blog82AI_Modal.showSuccess('Saved', 'Content updated successfully', true);
                    })
                    .catch(function(err) {
                        Blog82AI_Modal.closeLoading();
                        Blog82AI_Modal.showError('Network Error', 'Could not reach server to save content');
                        console.error(err);
                        if (selectionModal) selectionModal.style.display = 'flex';
                    });
                }, function() {
                    // onCancel: re-show the preview modal
                    if (selectionModal) selectionModal.style.display = 'flex';
                });
            };
        })
        .catch(function(err) {
            Blog82AI_Modal.closeLoading();
            Blog82AI_Modal.showError('Error', 'Network error while generating content');
            console.error(err);
        });
    } catch (e) {
        console.error(e);
        Blog82AI_Modal.closeLoading();
        Blog82AI_Modal.showError('Error', 'An unexpected error occurred');
    }
}

function exportHistory() {
    alert('Export functionality would be implemented here');
}

function applyBulkAction() {
    const action = document.getElementById('bulk-action-bottom').value;
    const selectedCheckboxes = document.querySelectorAll('.blog-checkbox:checked');
    
    if (!action || selectedCheckboxes.length === 0) {
        Blog82AI_Modal.showError('No Selection', 'Please select an action and at least one blog post.');
        return;
    }
    
    const selectedIds = Array.from(selectedCheckboxes).map(cb => cb.value);
    
    // Use the shared modal for confirmation and call server to persist changes
    Blog82AI_Modal.showConfirm(
        'Confirm Bulk Action',
        `Apply "${action}" to ${selectedIds.length} blog post(s)?`,
        function onOk() {
            // Show loading UI
            Blog82AI_Modal.showLoading('Applying bulk action...');

            const form = new FormData();
            form.append('action', 'blog82ai_generated_bulk_action');
            form.append('security', window.blog82ai_ajax_nonce || '');
            form.append('bulk_action', action);
            form.append('post_ids', JSON.stringify(selectedIds));

            fetch(ajaxurl, { method: 'POST', body: form })
            .then(r => r.json())
            .then(function(resp) {
                Blog82AI_Modal.closeLoading();
                if (!resp || !resp.success) {
                    const msg = resp && resp.data && resp.data.message ? resp.data.message : (resp && resp.data ? JSON.stringify(resp.data) : 'Failed to apply bulk action');
                    Blog82AI_Modal.showError('Bulk Action Failed', msg);
                    return;
                }

                // Update UI based on action
                if (action === 'trash') {
                    selectedCheckboxes.forEach(cb => {
                        const row = cb.closest('tr');
                        if (row) row.remove();
                    });
                } else {
                    selectedCheckboxes.forEach(cb => {
                        const row = cb.closest('tr');
                        if (!row) return;
                        const statusBadge = row.querySelector('.status-badge');
                        if (statusBadge) statusBadge.textContent = action.toUpperCase();
                    });
                }

                // Reset UI selections
                const bulkSelect = document.getElementById('bulk-action-bottom');
                if (bulkSelect) bulkSelect.value = '';
                const selectAll = document.getElementById('select-all-blogs');
                if (selectAll) selectAll.checked = false;

                const processed = resp.data && resp.data.processed ? resp.data.processed : selectedIds.length;
                Blog82AI_Modal.showSuccess('Bulk Action Applied', `Bulk action "${action}" applied to ${processed} blog post(s).`, true);
            })
            .catch(function(err) {
                Blog82AI_Modal.closeLoading();
                console.error('Bulk action error', err);
                Blog82AI_Modal.showError('Network Error', 'Could not reach the server to apply bulk action');
            });
        },
        function onCancel() {
            // No-op: keep selections intact
        }
    );
}
