{% extends "admin/base.html" %}

{% block title %}Import - Focomy{% endblock %}

{% block header_title %}WordPress Import{% endblock %}

{% block content %}
<div class="import-container">
    <!-- Source Selection -->
    <div class="card" id="source-card">
        <div class="card-header">
            <h2 class="card-title">Import Source</h2>
        </div>
        <div class="card-body">
            <div class="source-tabs">
                <button class="source-tab active" data-source="file" onclick="selectSource('file')">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                        <polyline points="14 2 14 8 20 8"/>
                    </svg>
                    WXR File Upload
                </button>
                <button class="source-tab" data-source="url" onclick="selectSource('url')">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="10"/>
                        <line x1="2" y1="12" x2="22" y2="12"/>
                        <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
                    </svg>
                    REST API (URL)
                </button>
            </div>

            <!-- File Upload -->
            <div id="file-source" class="source-content">
                <div class="upload-area" id="upload-area">
                    <input type="file" id="wxr-file" accept=".xml" hidden>
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                        <polyline points="17 8 12 3 7 8"/>
                        <line x1="12" y1="3" x2="12" y2="15"/>
                    </svg>
                    <p>Drop your WordPress export file here</p>
                    <p class="text-muted">or click to browse (.xml)</p>
                    <p id="file-name" class="file-name"></p>
                </div>
                <p class="help-text">
                    Export your WordPress site: WordPress Admin &rarr; Tools &rarr; Export &rarr; All Content
                </p>
            </div>

            <!-- URL Input -->
            <div id="url-source" class="source-content hidden">
                <div class="form-group">
                    <label class="form-label" for="wp-url">WordPress Site URL</label>
                    <input type="url" id="wp-url" class="form-input" placeholder="https://your-wordpress-site.com">
                </div>
                <div class="form-group">
                    <label class="form-label" for="wp-username">Username</label>
                    <input type="text" id="wp-username" class="form-input" placeholder="admin">
                </div>
                <div class="form-group">
                    <label class="form-label" for="wp-password">Application Password</label>
                    <input type="password" id="wp-password" class="form-input" placeholder="xxxx xxxx xxxx xxxx xxxx xxxx">
                    <p class="help-text">
                        Create in WordPress: Users &rarr; Your Profile &rarr; Application Passwords
                    </p>
                </div>
                <button class="btn btn-secondary" onclick="testConnection()">
                    Test Connection
                </button>
                <span id="connection-status"></span>
            </div>
        </div>
    </div>

    <!-- Options -->
    <div class="card" id="options-card">
        <div class="card-header">
            <h2 class="card-title">Import Options</h2>
        </div>
        <div class="card-body">
            <div class="option-group">
                <label class="checkbox-label">
                    <input type="checkbox" id="opt-media" checked>
                    <span>Import media metadata</span>
                </label>
            </div>
            <div class="option-group">
                <label class="checkbox-label">
                    <input type="checkbox" id="opt-download-media">
                    <span>Download media files (slower, requires storage)</span>
                </label>
            </div>
            <div class="option-group media-sub-option hidden" id="webp-options">
                <label class="checkbox-label">
                    <input type="checkbox" id="opt-webp">
                    <span>Convert images to WebP format</span>
                </label>
                <div class="sub-option" id="webp-quality-option" style="margin-left: 28px; margin-top: 8px; display: none;">
                    <label class="form-label" style="font-size: 0.875rem;">WebP Quality: <span id="webp-quality-value">85</span>%</label>
                    <input type="range" id="opt-webp-quality" min="50" max="100" value="85" style="width: 200px;">
                </div>
            </div>
            <div class="option-group">
                <label class="checkbox-label">
                    <input type="checkbox" id="opt-drafts" checked>
                    <span>Include draft posts</span>
                </label>
            </div>
            <div class="option-group">
                <label class="checkbox-label">
                    <input type="checkbox" id="opt-comments" checked>
                    <span>Import comments</span>
                </label>
            </div>
            <div class="option-group">
                <label class="checkbox-label">
                    <input type="checkbox" id="opt-menus" checked>
                    <span>Import navigation menus</span>
                </label>
            </div>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="action-buttons">
        <button class="btn btn-secondary btn-lg" id="analyze-btn" onclick="startAnalysis()">
            Analyze
        </button>
        <button class="btn btn-warning btn-lg" id="dryrun-btn" onclick="runDryRun()" disabled>
            Dry Run
        </button>
        <button class="btn btn-secondary btn-lg" id="preview-btn" onclick="runPreview()" disabled>
            Preview (3 items)
        </button>
        <button class="btn btn-primary btn-lg" id="import-btn" onclick="startImport()" disabled>
            Start Import
        </button>
        <button class="btn btn-secondary btn-lg" id="diff-btn" onclick="detectDiff()" disabled>
            Detect Diff
        </button>
    </div>

    <!-- Analysis Results -->
    <div class="card hidden" id="analysis-card">
        <div class="card-header">
            <h2 class="card-title">Analysis Results</h2>
        </div>
        <div class="card-body" id="analysis-content">
            <!-- Populated by JavaScript -->
        </div>
    </div>

    <!-- Dry-Run Results -->
    <div class="card hidden" id="dryrun-card">
        <div class="card-header">
            <h2 class="card-title">Dry-Run Results</h2>
        </div>
        <div class="card-body" id="dryrun-content">
            <!-- Populated by JavaScript -->
        </div>
    </div>

    <!-- Preview Results -->
    <div class="card hidden" id="preview-card">
        <div class="card-header">
            <h2 class="card-title">Preview Import</h2>
        </div>
        <div class="card-body" id="preview-content">
            <!-- Populated by JavaScript -->
        </div>
        <div class="card-footer" id="preview-actions" style="display: flex; gap: 1rem; justify-content: flex-end; padding: 1rem;">
            <button class="btn btn-danger" onclick="discardPreview()">Discard</button>
            <button class="btn btn-success" onclick="confirmPreview()">Confirm & Continue</button>
        </div>
    </div>

    <!-- Diff Results -->
    <div class="card hidden" id="diff-card">
        <div class="card-header">
            <h2 class="card-title">Diff Detection Results</h2>
        </div>
        <div class="card-body" id="diff-content">
            <!-- Populated by JavaScript -->
        </div>
        <div class="card-footer" id="diff-actions" style="display: flex; gap: 1rem; justify-content: space-between; align-items: center; padding: 1rem; flex-wrap: wrap;">
            <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                <label style="display: flex; align-items: center; gap: 0.5rem;">
                    <input type="checkbox" id="import-new" checked> Import New
                </label>
                <label style="display: flex; align-items: center; gap: 0.5rem;">
                    <input type="checkbox" id="import-updated" checked> Update Changed
                </label>
                <label style="display: flex; align-items: center; gap: 0.5rem;">
                    <input type="checkbox" id="delete-removed"> Delete Removed
                </label>
            </div>
            <button class="btn btn-primary" onclick="importDiff()">Import Changes</button>
        </div>
    </div>

    <!-- Progress -->
    <div class="card hidden" id="progress-card">
        <div class="card-header">
            <h2 class="card-title">Import Progress</h2>
        </div>
        <div class="card-body">
            <div class="progress-bar">
                <div class="progress-fill" id="progress-fill" style="width: 0%"></div>
            </div>
            <div class="progress-info">
                <span id="progress-phase">Initializing...</span>
                <span id="progress-percent">0%</span>
            </div>
            <p id="progress-message" class="progress-message"></p>
        </div>
    </div>

    <!-- Results -->
    <div class="card hidden" id="results-card">
        <div class="card-header">
            <h2 class="card-title">Import Complete</h2>
        </div>
        <div class="card-body" id="results-content">
            <!-- Populated by JavaScript -->
        </div>
        <div class="card-footer" id="results-actions" style="display: none; padding: 1rem; border-top: 1px solid var(--border);">
            <button class="btn btn-danger" id="rollback-btn" onclick="confirmRollback()">
                Rollback Import
            </button>
            <span id="rollback-info" style="margin-left: 1rem; color: var(--muted); font-size: 0.875rem;"></span>
        </div>
    </div>
</div>

<style>
.import-container {
    max-width: 800px;
    margin: 0 auto;
}

.source-tabs {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.source-tab {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    padding: 1.5rem;
    border: 2px solid var(--border);
    border-radius: 8px;
    background: var(--bg);
    cursor: pointer;
    transition: all 0.2s;
}

.source-tab:hover {
    border-color: var(--primary);
}

.source-tab.active {
    border-color: var(--primary);
    background: var(--primary-light);
}

.source-content {
    padding: 1rem 0;
}

.source-content.hidden {
    display: none;
}

.upload-area {
    border: 2px dashed var(--border);
    border-radius: 8px;
    padding: 3rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
}

.upload-area:hover {
    border-color: var(--primary);
    background: var(--primary-light);
}

.upload-area.dragover {
    border-color: var(--primary);
    background: var(--primary-light);
}

.upload-area svg {
    margin-bottom: 1rem;
    color: var(--muted);
}

.file-name {
    margin-top: 1rem;
    font-weight: 600;
    color: var(--primary);
}

.help-text {
    font-size: 0.875rem;
    color: var(--muted);
    margin-top: 0.5rem;
}

.option-group {
    margin-bottom: 1rem;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
    width: 1.25rem;
    height: 1.25rem;
}

.action-buttons {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
    margin: 1.5rem 0;
}

.btn-lg {
    padding: 0.75rem 2rem;
    font-size: 1rem;
}

.progress-bar {
    height: 24px;
    background: var(--border);
    border-radius: 12px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: var(--primary);
    transition: width 0.3s ease;
}

.progress-info {
    display: flex;
    justify-content: space-between;
    margin-top: 0.5rem;
    font-size: 0.875rem;
}

.progress-message {
    margin-top: 1rem;
    color: var(--muted);
}

.analysis-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.analysis-stat {
    text-align: center;
    padding: 1rem;
    background: var(--bg-secondary);
    border-radius: 8px;
}

.analysis-stat .number {
    font-size: 2rem;
    font-weight: 700;
    color: var(--primary);
}

.analysis-stat .label {
    font-size: 0.875rem;
    color: var(--muted);
}

.warning-list {
    background: #fef3c7;
    border: 1px solid #f59e0b;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
}

.warning-list h4 {
    color: #b45309;
    margin-bottom: 0.5rem;
}

.warning-list ul {
    margin: 0;
    padding-left: 1.5rem;
}

.results-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 1rem;
}

.result-stat {
    text-align: center;
    padding: 1rem;
    background: var(--bg-secondary);
    border-radius: 8px;
}

.result-stat .number {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--success);
}

.result-stat .label {
    font-size: 0.75rem;
    color: var(--muted);
}

#connection-status {
    margin-left: 1rem;
}

#connection-status.success {
    color: var(--success);
}

#connection-status.error {
    color: var(--danger);
}

.btn-warning {
    background-color: #f59e0b;
    color: white;
}

.btn-warning:hover {
    background-color: #d97706;
}

.dryrun-summary {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.dryrun-item {
    background: var(--bg-secondary);
    padding: 1rem;
    border-radius: 8px;
    text-align: center;
}

.dryrun-item .count {
    font-size: 1.5rem;
    font-weight: 700;
}

.dryrun-item .count.new { color: var(--success); }
.dryrun-item .count.duplicate { color: var(--warning); }

.dryrun-item .label {
    font-size: 0.875rem;
    color: var(--muted);
}

.duplicate-list {
    background: #fef3c7;
    border: 1px solid #f59e0b;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
    max-height: 200px;
    overflow-y: auto;
}

.duplicate-list h4 {
    color: #b45309;
    margin-bottom: 0.5rem;
}

.duplicate-list table {
    width: 100%;
    font-size: 0.875rem;
}

.duplicate-list th, .duplicate-list td {
    padding: 0.25rem 0.5rem;
    text-align: left;
}

.preview-item {
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1rem;
}

.preview-item h4 {
    margin: 0 0 0.5rem 0;
    font-size: 1rem;
}

.preview-item .meta {
    font-size: 0.875rem;
    color: var(--muted);
    margin-bottom: 0.5rem;
}

.preview-item .content-preview {
    font-size: 0.875rem;
    color: var(--text);
    line-height: 1.5;
    max-height: 100px;
    overflow: hidden;
}

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

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

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

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

.spinner {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid rgba(255,255,255,0.3);
    border-radius: 50%;
    border-top-color: #fff;
    animation: spin 0.8s linear infinite;
    margin-right: 6px;
    vertical-align: middle;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<script>
let currentSource = 'file';
let selectedFile = null;
let currentJobId = null;
let pollInterval = null;
let dryRunCompleted = false;
let previewCompleted = false;
let currentPreviewId = null;

function selectSource(source) {
    currentSource = source;
    document.querySelectorAll('.source-tab').forEach(tab => {
        tab.classList.toggle('active', tab.dataset.source === source);
    });
    document.getElementById('file-source').classList.toggle('hidden', source !== 'file');
    document.getElementById('url-source').classList.toggle('hidden', source !== 'url');
}

// File upload handling
const uploadArea = document.getElementById('upload-area');
const fileInput = document.getElementById('wxr-file');

uploadArea.addEventListener('click', () => fileInput.click());

uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    const file = e.dataTransfer.files[0];
    if (file && file.name.endsWith('.xml')) {
        handleFile(file);
    }
});

fileInput.addEventListener('change', (e) => {
    if (e.target.files[0]) {
        handleFile(e.target.files[0]);
    }
});

function handleFile(file) {
    selectedFile = file;
    document.getElementById('file-name').textContent = file.name;
}

// Media download and WebP options handling
const downloadMediaCheckbox = document.getElementById('opt-download-media');
const webpOptionsDiv = document.getElementById('webp-options');
const webpCheckbox = document.getElementById('opt-webp');
const webpQualityOption = document.getElementById('webp-quality-option');
const webpQualitySlider = document.getElementById('opt-webp-quality');
const webpQualityValue = document.getElementById('webp-quality-value');

downloadMediaCheckbox.addEventListener('change', () => {
    webpOptionsDiv.classList.toggle('hidden', !downloadMediaCheckbox.checked);
    if (!downloadMediaCheckbox.checked) {
        webpCheckbox.checked = false;
        webpQualityOption.style.display = 'none';
    }
});

webpCheckbox.addEventListener('change', () => {
    webpQualityOption.style.display = webpCheckbox.checked ? 'block' : 'none';
});

webpQualitySlider.addEventListener('input', () => {
    webpQualityValue.textContent = webpQualitySlider.value;
});

async function testConnection() {
    const url = document.getElementById('wp-url').value;
    const username = document.getElementById('wp-username').value;
    const password = document.getElementById('wp-password').value;
    const status = document.getElementById('connection-status');

    if (!url) {
        status.textContent = 'Please enter a URL';
        status.className = 'error';
        return;
    }

    status.textContent = 'Testing...';
    status.className = '';

    try {
        const response = await fetch('/admin/import/test-connection', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': '{{ csrf_token }}'
            },
            body: JSON.stringify({ url, username, password })
        });
        const data = await response.json();

        if (data.success) {
            status.textContent = `Connected: ${data.site_name}`;
            status.className = 'success';
        } else {
            status.textContent = data.message || 'Connection failed';
            status.className = 'error';
        }
    } catch (e) {
        status.textContent = 'Connection error';
        status.className = 'error';
    }
}

async function startAnalysis() {
    const formData = new FormData();
    const analyzeBtn = document.getElementById('analyze-btn');

    if (currentSource === 'file') {
        if (!selectedFile) {
            alert('Please select a WXR file');
            return;
        }
        formData.append('file', selectedFile);
        formData.append('source_type', 'wxr');
    } else {
        const url = document.getElementById('wp-url').value;
        if (!url) {
            alert('Please enter a WordPress URL');
            return;
        }
        formData.append('source_type', 'rest');
        formData.append('url', url);
        formData.append('username', document.getElementById('wp-username').value);
        formData.append('password', document.getElementById('wp-password').value);
    }

    // Add options
    formData.append('import_media', document.getElementById('opt-media').checked);
    formData.append('download_media', document.getElementById('opt-download-media').checked);
    formData.append('convert_to_webp', document.getElementById('opt-webp').checked);
    formData.append('webp_quality', document.getElementById('opt-webp-quality').value);
    formData.append('include_drafts', document.getElementById('opt-drafts').checked);
    formData.append('import_comments', document.getElementById('opt-comments').checked);
    formData.append('import_menus', document.getElementById('opt-menus').checked);

    // Show loading state
    analyzeBtn.disabled = true;
    analyzeBtn.innerHTML = '<span class="spinner"></span> Analyzing...';

    try {
        const response = await fetch('/admin/import/analyze', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            },
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            currentJobId = data.job_id;
            showAnalysis(data.analysis);
            document.getElementById('dryrun-btn').disabled = false;
            document.getElementById('diff-btn').disabled = false;
            dryRunCompleted = false;
        } else {
            alert('Analysis failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Analysis error: ' + e.message);
    } finally {
        analyzeBtn.disabled = false;
        analyzeBtn.innerHTML = 'Analyze';
    }
}

async function runDryRun() {
    if (!currentJobId) {
        alert('Please analyze first');
        return;
    }

    document.getElementById('dryrun-btn').disabled = true;
    document.getElementById('dryrun-btn').textContent = 'Running...';

    try {
        const response = await fetch(`/admin/import/${currentJobId}/dry-run`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            showDryRunResults(data);
            dryRunCompleted = true;
            document.getElementById('preview-btn').disabled = false;
            document.getElementById('import-btn').disabled = false;
        } else {
            alert('Dry-run failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Dry-run error: ' + e.message);
    } finally {
        document.getElementById('dryrun-btn').textContent = 'Dry Run';
        document.getElementById('dryrun-btn').disabled = false;
    }
}

function showDryRunResults(result) {
    const card = document.getElementById('dryrun-card');
    const content = document.getElementById('dryrun-content');

    const counts = result.counts || {};
    const items = result.items || {};

    // Count new items by type
    const postCount = (items.posts || []).filter(i => i.status === 'new').length;
    const pageCount = (items.pages || []).filter(i => i.status === 'new').length;
    const mediaCount = (items.media || []).filter(i => i.status === 'new').length;
    const catCount = (items.categories || []).filter(i => i.status === 'new').length;
    const tagCount = (items.tags || []).filter(i => i.status === 'new').length;

    let html = `
        <div class="dryrun-summary">
            <div class="dryrun-item">
                <div class="count new">${counts.new || 0}</div>
                <div class="label">New Items</div>
            </div>
            <div class="dryrun-item">
                <div class="count">${counts.update || 0}</div>
                <div class="label">Updates</div>
            </div>
            <div class="dryrun-item">
                <div class="count">${counts.skip || 0}</div>
                <div class="label">Skip</div>
            </div>
            <div class="dryrun-item">
                <div class="count error">${counts.error || 0}</div>
                <div class="label">Errors</div>
            </div>
        </div>
        <div class="dryrun-details" style="margin-top: 1rem;">
            <table style="width: 100%;">
                <tr><th>Type</th><th>New</th><th>Skip</th><th>Error</th></tr>
                <tr><td>Posts</td><td>${postCount}</td><td>${(items.posts || []).filter(i => i.status === 'skip').length}</td><td>${(items.posts || []).filter(i => i.status === 'error').length}</td></tr>
                <tr><td>Pages</td><td>${pageCount}</td><td>${(items.pages || []).filter(i => i.status === 'skip').length}</td><td>${(items.pages || []).filter(i => i.status === 'error').length}</td></tr>
                <tr><td>Media</td><td>${mediaCount}</td><td>${(items.media || []).filter(i => i.status === 'skip').length}</td><td>${(items.media || []).filter(i => i.status === 'error').length}</td></tr>
                <tr><td>Categories</td><td>${catCount}</td><td>${(items.categories || []).filter(i => i.status === 'skip').length}</td><td>${(items.categories || []).filter(i => i.status === 'error').length}</td></tr>
                <tr><td>Tags</td><td>${tagCount}</td><td>${(items.tags || []).filter(i => i.status === 'skip').length}</td><td>${(items.tags || []).filter(i => i.status === 'error').length}</td></tr>
            </table>
        </div>
    `;

    if (result.errors && result.errors.length > 0) {
        html += `
            <div class="error-list" style="margin-top: 1rem; padding: 1rem; background: #fee; border-radius: 4px;">
                <h4 style="color: var(--error);">Errors (${result.errors.length})</h4>
                <ul>
                    ${result.errors.slice(0, 10).map(e => `<li>${e}</li>`).join('')}
                </ul>
                ${result.errors.length > 10 ? `<p>... and ${result.errors.length - 10} more</p>` : ''}
            </div>
        `;
    }

    if (result.duplicates && result.duplicates.length > 0) {
        html += `
            <div class="duplicate-list" style="margin-top: 1rem; padding: 1rem; background: #ffd; border-radius: 4px;">
                <h4>Duplicate Slugs (${result.duplicates.length})</h4>
                <ul>
                    ${result.duplicates.slice(0, 10).map(d => `<li>${d.type}: ${d.slug}</li>`).join('')}
                </ul>
            </div>
        `;
    }

    if (result.warnings && result.warnings.length > 0) {
        html += `
            <div class="warning-list" style="margin-top: 1rem; padding: 1rem; background: #ffd; border-radius: 4px;">
                <h4>Warnings (${result.warnings.length})</h4>
                <ul>
                    ${result.warnings.slice(0, 10).map(w => `<li>${w}</li>`).join('')}
                </ul>
                ${result.warnings.length > 10 ? `<p>... and ${result.warnings.length - 10} more</p>` : ''}
            </div>
        `;
    }

    if (!result.has_errors && !result.duplicates?.length) {
        html += `<p style="color: var(--success); text-align: center; margin-top: 1rem;">
            <strong>No issues detected. Ready to import!</strong>
        </p>`;
    }

    content.innerHTML = html;
    card.classList.remove('hidden');
}

async function runPreview() {
    if (!currentJobId) {
        alert('Please analyze first');
        return;
    }

    if (!dryRunCompleted) {
        alert('Please run a dry-run first');
        return;
    }

    document.getElementById('preview-btn').disabled = true;
    document.getElementById('preview-btn').textContent = 'Previewing...';

    try {
        const response = await fetch(`/admin/import/${currentJobId}/preview`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            currentPreviewId = data.preview_id;
            showPreviewResults(data);
        } else {
            alert('Preview failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Preview error: ' + e.message);
    } finally {
        document.getElementById('preview-btn').textContent = 'Preview (3 items)';
        document.getElementById('preview-btn').disabled = false;
    }
}

function showPreviewResults(result) {
    const card = document.getElementById('preview-card');
    const content = document.getElementById('preview-content');

    const items = result.items || [];

    if (items.length === 0) {
        content.innerHTML = `<p style="color: var(--muted); text-align: center;">No items to preview (all items may already exist)</p>`;
        document.getElementById('preview-actions').style.display = 'none';
    } else {
        let html = `
            <p style="margin-bottom: 1rem;">
                Preview ID: <code>${result.preview_id}</code><br>
                ${result.success_count} item(s) imported, ${result.error_count} error(s)
            </p>
        `;

        if (result.errors && result.errors.length > 0) {
            html += `
                <div style="background: #fee; padding: 0.5rem; border-radius: 4px; margin-bottom: 1rem;">
                    <strong>Errors:</strong>
                    <ul>${result.errors.map(e => `<li>${e}</li>`).join('')}</ul>
                </div>
            `;
        }

        html += `<table style="width: 100%;"><tr><th>Type</th><th>Title</th><th>Status</th></tr>`;
        for (const item of items) {
            const statusColor = item.status === 'success' ? 'var(--success)' :
                               item.status === 'error' ? 'var(--error)' : 'var(--muted)';
            html += `
                <tr>
                    <td>${item.entity_type}</td>
                    <td>${item.title}</td>
                    <td style="color: ${statusColor}">${item.status}</td>
                </tr>
            `;
        }
        html += `</table>`;

        html += `<p style="margin-top: 1rem; font-size: 0.875rem; color: var(--muted);">
            Click "Confirm & Continue" to keep these items and proceed with the full import,
            or "Discard" to remove them and try different settings.
        </p>`;

        content.innerHTML = html;
        document.getElementById('preview-actions').style.display = 'flex';
    }

    card.classList.remove('hidden');
    previewCompleted = true;
}

async function confirmPreview() {
    if (!currentPreviewId) {
        alert('No preview to confirm');
        return;
    }

    try {
        const response = await fetch(`/admin/import/preview/${currentPreviewId}/commit`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            alert(`${data.committed_count} preview item(s) confirmed. You can now proceed with the full import.`);
            document.getElementById('preview-card').classList.add('hidden');
            currentPreviewId = null;
        } else {
            alert('Confirm failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Confirm error: ' + e.message);
    }
}

async function discardPreview() {
    if (!currentPreviewId) {
        alert('No preview to discard');
        return;
    }

    if (!confirm('Are you sure you want to discard the preview items?')) {
        return;
    }

    try {
        const response = await fetch(`/admin/import/preview/${currentPreviewId}/rollback`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            alert(`${data.rolled_back_count} preview item(s) discarded.`);
            document.getElementById('preview-card').classList.add('hidden');
            previewCompleted = false;
            currentPreviewId = null;
        } else {
            alert('Discard failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Discard error: ' + e.message);
    }
}

function showAnalysis(analysis) {
    const card = document.getElementById('analysis-card');
    const content = document.getElementById('analysis-content');

    let html = `
        <div class="analysis-grid">
            <div class="analysis-stat">
                <div class="number">${analysis.posts?.total || 0}</div>
                <div class="label">Posts</div>
            </div>
            <div class="analysis-stat">
                <div class="number">${analysis.pages?.total || 0}</div>
                <div class="label">Pages</div>
            </div>
            <div class="analysis-stat">
                <div class="number">${analysis.media?.total_count || 0}</div>
                <div class="label">Media</div>
            </div>
            <div class="analysis-stat">
                <div class="number">${analysis.categories_count || 0}</div>
                <div class="label">Categories</div>
            </div>
            <div class="analysis-stat">
                <div class="number">${analysis.tags_count || 0}</div>
                <div class="label">Tags</div>
            </div>
            <div class="analysis-stat">
                <div class="number">${analysis.users_count || 0}</div>
                <div class="label">Users</div>
            </div>
        </div>
        <p><strong>Estimated Time:</strong> ${analysis.estimated_time || 'Unknown'}</p>
        <p><strong>Estimated Storage:</strong> ${analysis.estimated_storage || 'Unknown'}</p>
    `;

    if (analysis.warnings && analysis.warnings.length > 0) {
        html += `
            <div class="warning-list">
                <h4>Warnings</h4>
                <ul>
                    ${analysis.warnings.map(w => `<li>[${w.code}] ${w.message}</li>`).join('')}
                </ul>
            </div>
        `;
    }

    content.innerHTML = html;
    card.classList.remove('hidden');
}

async function startImport() {
    if (!currentJobId) {
        alert('Please analyze first');
        return;
    }

    if (!dryRunCompleted) {
        alert('Please run a dry-run first to check for potential issues');
        return;
    }

    document.getElementById('import-btn').disabled = true;
    document.getElementById('dryrun-btn').disabled = true;
    document.getElementById('progress-card').classList.remove('hidden');

    try {
        const response = await fetch(`/admin/import/${currentJobId}/start`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            startPolling();
        } else {
            alert('Import failed to start: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Import error: ' + e.message);
    }
}

function startPolling() {
    pollInterval = setInterval(pollProgress, 2000);
}

async function pollProgress() {
    if (!currentJobId) return;

    try {
        const response = await fetch(`/admin/import/${currentJobId}/status`);
        const data = await response.json();

        updateProgress(data);

        if (data.status === 'completed' || data.status === 'failed') {
            clearInterval(pollInterval);
            showResults(data);
        }
    } catch (e) {
        console.error('Poll error:', e);
    }
}

function updateProgress(data) {
    const fill = document.getElementById('progress-fill');
    const phase = document.getElementById('progress-phase');
    const percent = document.getElementById('progress-percent');
    const message = document.getElementById('progress-message');

    const pct = data.progress?.percent || 0;
    fill.style.width = pct + '%';
    percent.textContent = pct + '%';
    phase.textContent = data.phase || 'Processing';
    message.textContent = data.progress?.message || '';
}

function renderErrorDetails(errors, title) {
    // Handle both dict format (new) and array format (legacy)
    if (typeof errors === 'object' && !Array.isArray(errors)) {
        // New dict format with summary, errors, skipped, warnings
        const summary = errors.summary || {};
        let html = `
            <div style="margin-top: 1rem; padding: 1rem; background: var(--bg-secondary); border-radius: 8px;">
                <h4 style="margin-bottom: 0.5rem;">${title}</h4>
                <div style="display: flex; gap: 1rem; margin-bottom: 0.5rem;">
                    <span>Errors: <strong style="color: var(--danger);">${summary.total_errors || 0}</strong></span>
                    <span>Skipped: <strong>${summary.total_skipped || 0}</strong></span>
                    <span>Warnings: <strong style="color: var(--warning);">${summary.total_warnings || 0}</strong></span>
                </div>
                <details>
                    <summary style="cursor: pointer; color: var(--primary);">Copy JSON for debugging</summary>
                    <textarea readonly style="width: 100%; height: 200px; margin-top: 0.5rem; font-family: monospace; font-size: 12px;">${JSON.stringify(errors, null, 2)}</textarea>
                </details>
            </div>
        `;
        return html;
    } else if (Array.isArray(errors)) {
        // Legacy array format
        return `<p>${errors.join('<br>')}</p>`;
    }
    return '';
}

function showResults(data) {
    document.getElementById('progress-card').classList.add('hidden');
    const card = document.getElementById('results-card');
    const content = document.getElementById('results-content');

    if (data.status === 'completed') {
        const results = data.results || {};
        content.innerHTML = `
            <div class="results-grid">
                <div class="result-stat">
                    <div class="number">${results.posts || 0}</div>
                    <div class="label">Posts</div>
                </div>
                <div class="result-stat">
                    <div class="number">${results.pages || 0}</div>
                    <div class="label">Pages</div>
                </div>
                <div class="result-stat">
                    <div class="number">${results.media || 0}</div>
                    <div class="label">Media</div>
                </div>
                <div class="result-stat">
                    <div class="number">${results.categories || 0}</div>
                    <div class="label">Categories</div>
                </div>
                <div class="result-stat">
                    <div class="number">${results.tags || 0}</div>
                    <div class="label">Tags</div>
                </div>
                <div class="result-stat">
                    <div class="number">${results.authors || 0}</div>
                    <div class="label">Authors</div>
                </div>
            </div>
            <p style="text-align: center; margin-top: 1rem;">
                <a href="/admin/post" class="btn btn-primary">View Posts</a>
            </p>
            ${data.errors ? renderErrorDetails(data.errors, 'Import Details') : ''}
        `;

        // Show rollback option
        document.getElementById('results-actions').style.display = 'block';
        document.getElementById('rollback-info').textContent = 'Rollback available for 30 days';
    } else {
        content.innerHTML = `
            <div style="text-align: center; color: var(--danger);">
                <h3>Import Failed</h3>
            </div>
            ${data.errors ? renderErrorDetails(data.errors, 'Error Details') : '<p>Unknown error</p>'}
        `;
        document.getElementById('results-actions').style.display = 'none';
    }

    card.classList.remove('hidden');
}

async function confirmRollback() {
    if (!currentJobId) {
        alert('No import job to rollback');
        return;
    }

    // Get rollback status first
    try {
        const statusResponse = await fetch(`/admin/import/${currentJobId}/rollback-status`);
        const statusData = await statusResponse.json();

        if (!statusData.can_rollback) {
            alert('Cannot rollback: ' + (statusData.reason || 'Unknown reason'));
            return;
        }

        const totalToDelete = statusData.total_to_delete || 0;
        const preview = statusData.preview || {};

        let confirmMsg = `Are you sure you want to rollback this import?\n\n`;
        confirmMsg += `This will delete ${totalToDelete} items:\n`;
        for (const [type, count] of Object.entries(preview)) {
            if (count > 0) {
                confirmMsg += `- ${type}: ${count}\n`;
            }
        }
        confirmMsg += `\nThis action cannot be undone.`;

        if (!confirm(confirmMsg)) {
            return;
        }

        // Perform rollback
        document.getElementById('rollback-btn').disabled = true;
        document.getElementById('rollback-btn').textContent = 'Rolling back...';

        const response = await fetch(`/admin/import/${currentJobId}/rollback`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            alert(`Rollback complete! Deleted ${data.total_deleted} items.`);
            document.getElementById('results-actions').style.display = 'none';
            document.getElementById('results-content').innerHTML = `
                <div style="text-align: center; color: var(--warning);">
                    <h3>Import Rolled Back</h3>
                    <p>All imported data has been deleted.</p>
                </div>
            `;
        } else {
            alert('Rollback failed: ' + (data.error || 'Unknown error'));
            document.getElementById('rollback-btn').disabled = false;
            document.getElementById('rollback-btn').textContent = 'Rollback Import';
        }
    } catch (e) {
        alert('Error: ' + e.message);
        document.getElementById('rollback-btn').disabled = false;
        document.getElementById('rollback-btn').textContent = 'Rollback Import';
    }
}

async function detectDiff() {
    if (!currentJobId) {
        alert('Please analyze first');
        return;
    }

    document.getElementById('diff-btn').disabled = true;
    document.getElementById('diff-btn').textContent = 'Detecting...';

    try {
        const response = await fetch(`/admin/import/${currentJobId}/detect-diff`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            showDiffResults(data);
        } else {
            alert('Diff detection failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Diff detection error: ' + e.message);
    } finally {
        document.getElementById('diff-btn').textContent = 'Detect Diff';
        document.getElementById('diff-btn').disabled = false;
    }
}

function showDiffResults(result) {
    const card = document.getElementById('diff-card');
    const content = document.getElementById('diff-content');

    const summary = result.summary || {};
    const entityTypes = ['posts', 'pages', 'media', 'categories', 'tags', 'authors'];

    let html = `
        <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
            <thead>
                <tr style="border-bottom: 2px solid var(--border);">
                    <th style="text-align: left; padding: 0.5rem;">Type</th>
                    <th style="text-align: center; padding: 0.5rem; color: var(--success);">New</th>
                    <th style="text-align: center; padding: 0.5rem; color: var(--warning);">Updated</th>
                    <th style="text-align: center; padding: 0.5rem; color: var(--muted);">Unchanged</th>
                    <th style="text-align: center; padding: 0.5rem; color: var(--danger);">Deleted</th>
                </tr>
            </thead>
            <tbody>
    `;

    let totalNew = 0, totalUpdated = 0, totalUnchanged = 0, totalDeleted = 0;

    for (const type of entityTypes) {
        const s = summary[type] || {};
        totalNew += s.new || 0;
        totalUpdated += s.updated || 0;
        totalUnchanged += s.unchanged || 0;
        totalDeleted += s.deleted || 0;

        html += `
            <tr style="border-bottom: 1px solid var(--border);">
                <td style="padding: 0.5rem; text-transform: capitalize;">${type}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--success);">${s.new || 0}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--warning);">${s.updated || 0}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--muted);">${s.unchanged || 0}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--danger);">${s.deleted || 0}</td>
            </tr>
        `;
    }

    html += `
            <tr style="font-weight: bold; border-top: 2px solid var(--border);">
                <td style="padding: 0.5rem;">Total</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--success);">${totalNew}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--warning);">${totalUpdated}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--muted);">${totalUnchanged}</td>
                <td style="text-align: center; padding: 0.5rem; color: var(--danger);">${totalDeleted}</td>
            </tr>
        </tbody>
        </table>
    `;

    if (totalNew === 0 && totalUpdated === 0 && totalDeleted === 0) {
        html += `<p style="color: var(--success); text-align: center;">
            <strong>Everything is up to date! No changes to import.</strong>
        </p>`;
        document.getElementById('diff-actions').style.display = 'none';
    } else {
        document.getElementById('diff-actions').style.display = 'flex';
    }

    content.innerHTML = html;
    card.classList.remove('hidden');
}

async function importDiff() {
    if (!currentJobId) {
        alert('Please analyze first');
        return;
    }

    const importNew = document.getElementById('import-new').checked;
    const importUpdated = document.getElementById('import-updated').checked;
    const deleteRemoved = document.getElementById('delete-removed').checked;

    if (!importNew && !importUpdated && !deleteRemoved) {
        alert('Please select at least one option');
        return;
    }

    if (deleteRemoved && !confirm('Warning: This will delete items that no longer exist in WordPress. Continue?')) {
        return;
    }

    document.getElementById('progress-card').classList.remove('hidden');

    try {
        const params = new URLSearchParams({
            import_new: importNew,
            import_updated: importUpdated,
            delete_removed: deleteRemoved
        });

        const response = await fetch(`/admin/import/${currentJobId}/import-diff?${params}`, {
            method: 'POST',
            headers: {
                'X-CSRF-Token': '{{ csrf_token }}'
            }
        });
        const data = await response.json();

        if (data.success) {
            startPolling();
        } else {
            alert('Diff import failed to start: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Error: ' + e.message);
    }
}
</script>
{% endblock %}
