<?php $pageTitle = 'Image Optimization'; require __DIR__ . '/../layout/header.php'; ?>

<div class="content-body">
    <div class="container-fluid">

        <!-- Page Header -->
        <div class="mb-4 d-flex justify-content-between align-items-center flex-wrap gap-3">
            <div>
                <h2 class="h3 font-bold mb-1">Bulk Image Optimization (WebP)</h2>
                <p class="text-muted small mb-0">Convert and optimize multiple images to WebP format simultaneously. Faster page loads, better SEO.</p>
            </div>
            <div class="d-flex align-items-center gap-3 bg-white p-2 rounded-4 shadow-sm border">
                <button class="btn btn-light btn-sm rounded-pill fw-bold border" onclick="showHistory()">
                    <i class="bi bi-clock-history me-1"></i> History
                </button>
                <div class="vr mx-1"></div>
                <span class="small fw-bold text-muted ps-1"><i class="bi bi-globe me-1"></i> Target Domain:</span>
                <input type="text" id="targetDomain" class="form-control form-control-sm border-0 shadow-none bg-light" placeholder="No project selected" style="width: 150px;" readonly>
            </div>
        </div>

        <div class="row g-4">
            <div class="col-12">
                <!-- Upload & URL Area -->
                <div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4">
                    <div class="card-body p-4 p-md-5">
                        <div class="row g-4">
                            <div class="col-lg-12">
                                <div class="h-100 d-flex flex-column justify-content-center p-4 border rounded-4 bg-light bg-opacity-10">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="fw-bold mb-0"><i class="bi bi-link-45deg me-2 text-primary"></i> Batch Add via URL / CSV</h6>
                                        <button class="btn btn-link btn-sm p-0 text-decoration-none" onclick="document.getElementById('csvInput').click()">
                                            <i class="bi bi-filetype-csv me-1"></i> Upload CSV
                                        </button>
                                        <input type="file" id="csvInput" accept=".csv" class="d-none" onchange="handleCsvUpload(this)">
                                    </div>
                                    <textarea id="urlInput" class="form-control border shadow-sm py-3 px-4 mb-2 resize-none bg-white" rows="3" placeholder="Paste image URLs here (one per line)..."></textarea>
                                    <button class="btn btn-primary w-100 py-2 rounded-3 fw-bold" type="button" id="fetchUrlBtn" onclick="fetchImagesFromUrls()">
                                        <i class="bi bi-cloud-arrow-down me-2"></i> Fetch All Images
                                    </button>
                                    <p class="text-muted extra-small mb-0 mt-2">
                                        <i class="bi bi-info-circle me-1"></i> Paste multiple direct links or upload a CSV with URLs in the first column.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bulk Actions -->
                <div id="bulk-actions" class="d-none mb-4 animate-in">
                    <div class="card border-0 shadow-sm rounded-4">
                        <div class="card-body p-3 d-flex flex-wrap justify-content-between align-items-center gap-3">
                            <div class="d-flex align-items-center gap-3">
                                <div class="form-check ms-2">
                                    <input class="form-check-input" type="checkbox" id="selectAllImages" onchange="toggleSelectAll(this)">
                                    <label class="form-check-label small fw-bold text-muted" for="selectAllImages">Select All</label>
                                </div>
                                <span class="badge bg-primary rounded-pill px-3 py-2" id="total-count">0 Images</span>
                                <span class="text-muted small" id="total-savings">Total Savings: 0%</span>
                            </div>
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" onclick="clearAll()" class="btn btn-outline-secondary px-3 rounded-pill fw-bold btn-sm">
                                    <i class="bi bi-trash3 me-1"></i> Clear All
                                </button>
                                <button type="button" onclick="generateAISuggestionsSelected()" class="btn btn-outline-primary px-3 rounded-pill fw-bold btn-sm">
                                    <i class="bi bi-magic me-1"></i> Fetch Selected AI
                                </button>
                                <button type="button" onclick="generateAISuggestionsAll()" class="btn btn-primary px-3 rounded-pill fw-bold btn-sm">
                                    <i class="bi bi-magic me-1"></i> Fetch All AI
                                </button>
                                <button type="button" onclick="convertToWebPAll()" id="convert-all-btn" class="btn btn-savit px-4 rounded-pill fw-bold btn-sm">
                                    <i class="bi bi-magic me-1"></i> Convert & Download All
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Image List -->
                <div id="image-list-container" class="d-none animate-in">
                    <div class="row g-4" id="image-grid">
                        <!-- Image cards will be injected here -->
                    </div>
                </div>

                <!-- Empty State -->
                <div id="empty-state" class="text-center py-5">
                    <div class="opacity-25 mb-3">
                        <i class="bi bi-images" style="font-size: 4rem;"></i>
                    </div>
                    <h5 class="text-muted">No images selected yet</h5>
                    <p class="text-muted small">Upload some images to begin the optimization process</p>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- History Modal -->
<div class="modal fade" id="historyModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow rounded-4">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold p-3"><i class="bi bi-clock-history me-2 text-primary"></i> Optimization History</h5>
                <button type="button" class="btn-close shadow-none me-3" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <!-- Filters Bar -->
                <div class="d-flex flex-wrap align-items-center justify-content-between mb-4 gap-3">
                    <div class="d-flex gap-2 flex-wrap align-items-center">
                        <div class="date-filter-wrapper position-relative">
                            <button class="btn btn-white btn-sm border d-flex align-items-center gap-2" id="history-date-picker">
                                <i class="bi bi-calendar3 text-muted"></i>
                                <span id="history-selected-date-text">All Time</span>
                                <i class="bi bi-chevron-down small opacity-50"></i>
                            </button>
                            <input type="hidden" id="history-date-range-input">
                        </div>
                    </div>

                    <div class="d-flex gap-2 flex-wrap align-items-center ms-auto">
                        <div class="input-group input-group-sm" style="width: 250px;">
                            <input type="text" id="history-search" class="form-control border-end-0" placeholder="Search filename, domain, tags...">
                            <span class="input-group-text bg-white border-start-0 text-muted">
                                <i class="bi bi-search"></i>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-middle custom-history-table">
                        <thead class="table-light">
                            <tr>
                                <th>Date</th>
                                <th>Original Name</th>
                                <th>Target Domain</th>
                                <th>Suggested Alt</th>
                                <th>Suggested Title</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="historyTableBody">
                            <!-- Loaded via AJAX -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<style>
/* ── Custom History Styles ─────────────────────────────────── */
.custom-history-table thead th {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: #6c757d;
    border-bottom: 2px solid #f1f1f1;
    padding: 1rem;
}

.custom-history-table tbody td {
    padding: 1rem;
    font-size: 0.85rem;
}

.history-url {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
    font-size: 0.7rem;
    color: #999;
}

/* ── Custom Styles ────────────────────────────────────────── */
.image-card {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.image-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.08) !important;
}

.preview-thumbnail {
    width: 100%;
    height: 180px;
    object-fit: cover;
    background: #f1f5f9;
    border-radius: 0.75rem 0.75rem 0 0;
    background-image: linear-gradient(45deg, #e2e8f0 25%, transparent 25%), 
                      linear-gradient(-45deg, #e2e8f0 25%, transparent 25%), 
                      linear-gradient(45deg, transparent 75%, #e2e8f0 75%), 
                      linear-gradient(-45deg, transparent 75%, #e2e8f0 75%);
    background-size: 10px 10px;
}

.animate-in {
    animation: fadeInScale 0.4s ease-out forwards;
}

@keyframes fadeInScale {
    from { opacity: 0; transform: scale(0.98); }
    to { opacity: 1; transform: scale(1); }
}

.btn-savit {
    background: linear-gradient(135deg, #FF6B35 0%, #FF8C42 100%) !important;
    color: white !important;
    border: none;
    transition: all 0.2s;
    box-shadow: 0 4px 12px rgba(255, 107, 53, 0.25);
}
.btn-savit:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(255, 107, 53, 0.35);
}

.remove-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(255, 255, 255, 0.9);
    border: none;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    color: #ef4444;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 10;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.remove-btn:hover {
    background: #ef4444;
    color: white;
}

.extra-small { font-size: 11px; }

.suggested-field {
    background-color: #fff9f5;
    border-color: #ffedd5;
}
.suggested-field:focus {
    background-color: #fff4eb;
    border-color: #ff6b35;
    box-shadow: 0 0 0 0.25rem rgba(255, 107, 53, 0.1);
}
</style>

<script>
let uploadedImages = [];

// Initialize Target Domain from Active Project
document.addEventListener('DOMContentLoaded', function() {
    if (window.savitProject) {
        const project = window.savitProject.get();
        if (project && project.domain) {
            const domain = project.domain.replace(/^https?:\/\//, '').replace(/\/$/, '').split('/')[0];
            document.getElementById('targetDomain').value = domain;
        }
    }
});

const imageGrid = document.getElementById('image-grid');
const emptyState = document.getElementById('empty-state');
const bulkActions = document.getElementById('bulk-actions');
const imageListContainer = document.getElementById('image-list-container');

async function fetchImagesFromUrls() {
    const rawValue = document.getElementById('urlInput').value.trim();
    if (!rawValue) return;

    const urls = rawValue.split('\n').map(u => u.trim()).filter(u => u !== '');
    if (urls.length === 0) return;

    const btn = document.getElementById('fetchUrlBtn');
    const originalContent = btn.innerHTML;
    btn.disabled = true;
    
    let successCount = 0;
    for (let i = 0; i < urls.length; i++) {
        btn.innerHTML = `<i class="bi bi-arrow-repeat spin me-2"></i> Fetching ${i + 1}/${urls.length}...`;
        try {
            await fetchImageFromUrl(urls[i]);
            successCount++;
        } catch (err) {
            console.error(`Failed to fetch ${urls[i]}:`, err);
        }
    }

    btn.disabled = false;
    btn.innerHTML = originalContent;
    document.getElementById('urlInput').value = '';

    if (successCount > 0) {
        Swal.fire({
            icon: 'success',
            title: 'Batch Fetch Complete',
            text: `Successfully added ${successCount} images from URLs.`,
            confirmButtonColor: '#FF6B35'
        });
    }
}

function handleCsvUpload(input) {
    const file = input.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(e) {
        const text = e.target.result;
        const lines = text.split(/\r?\n/);
        const urls = lines.map(line => {
            const parts = line.split(',');
            return parts[0].replace(/"/g, '').trim();
        }).filter(url => url.startsWith('http'));

        if (urls.length > 0) {
            document.getElementById('urlInput').value = urls.join('\n');
            fetchImagesFromUrls();
        } else {
            Swal.fire('Error', 'No valid image URLs found in CSV.', 'error');
        }
    };
    reader.readAsText(file);
    input.value = '';
}

async function fetchImageFromUrl(url) {
    try {
        const targetDomain = document.getElementById('targetDomain').value.trim();
        let urlDomain = '';
        try {
            urlDomain = new URL(url).hostname.replace('www.', '');
        } catch (e) {
            throw new Error('Invalid URL format');
        }

        if (targetDomain && urlDomain !== targetDomain) {
            console.warn(`Skipping URL: ${url} (Domain mismatch: ${urlDomain} vs ${targetDomain})`);
            return; // Neglect if domain doesn't match
        }

        const proxyUrl = `<?= BASE_URL ?>/api/image-optimization/proxy-fetch?url=${encodeURIComponent(url)}`;
        const response = await fetch(proxyUrl);
        if (!response.ok) throw new Error('Failed to fetch image');
        
        const blob = await response.blob();
        if (!blob.type.startsWith('image/')) throw new Error('URL is not a valid image');

        const fileName = url.split('/').pop().split('?')[0] || 'image-' + Date.now();
        const baseName = fileName.split('.').slice(0, -1).join('.') || fileName;
        const formatted = baseName.replace(/[-_]/g, ' ');

        const file = new File([blob], fileName, { type: blob.type });
        
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.onload = function(event) {
                const imageObj = {
                    id: Date.now() + Math.random().toString(36).substr(2, 9),
                    file: file,
                    src: event.target.result,
                    url: url,
                    name: baseName,
                    alt: formatted,
                    title: formatted,
                    suggestedAlt: '',
                    suggestedTitle: '',
                    originalSize: blob.size,
                    optimizedSize: 0,
                    status: 'pending',
                    aiStatus: 'idle'
                };

                uploadedImages.push(imageObj);
                renderImages();
                resolve();
            };
            reader.readAsDataURL(blob);
        });

    } catch (err) {
        throw err;
    }
}

function renderImages() {
    if (uploadedImages.length > 0) {
        emptyState.classList.add('d-none');
        bulkActions.classList.remove('d-none');
        imageListContainer.classList.remove('d-none');
    } else {
        emptyState.classList.remove('d-none');
        bulkActions.classList.add('d-none');
        imageListContainer.classList.add('d-none');
    }

    document.getElementById('total-count').textContent = `${uploadedImages.length} Image${uploadedImages.length > 1 ? 's' : ''}`;
    
    imageGrid.innerHTML = '';
    uploadedImages.forEach((img, index) => {
        const col = document.createElement('div');
        col.className = 'col-12 animate-in';
        col.style.animationDelay = `${index * 0.05}s`;
        
        const sizeKB = (img.originalSize / 1024).toFixed(1);
        const optSizeKB = img.optimizedSize ? (img.optimizedSize / 1024).toFixed(1) : '-';
        const savings = img.optimizedSize ? ((img.originalSize - img.optimizedSize) / img.originalSize * 100).toFixed(1) : 0;

        col.innerHTML = `
            <div class="card border-0 shadow-sm rounded-4 h-100 image-card overflow-hidden position-relative">
                <div class="position-absolute top-0 start-0 p-3" style="z-index: 10;">
                    <input class="form-check-input shadow-sm image-checkbox" type="checkbox" value="${img.id}" ${img.selected ? 'checked' : ''} onchange="toggleImageSelection('${img.id}', this.checked)">
                </div>
                <button type="button" class="remove-btn" onclick="removeImage('${img.id}')">
                    <i class="bi bi-x"></i>
                </button>
                <div class="row g-0 h-100">
                    <div class="col-md-4">
                        <img src="${img.src}" class="preview-thumbnail h-100 w-100" style="min-height: 200px;">
                    </div>
                    <div class="col-md-8">
                        <div class="card-body p-4">
                            <div class="mb-3">
                                <label class="form-label small text-muted text-uppercase fw-bold mb-1">File Name</label>
                                <div class="input-group input-group-sm">
                                    <input type="text" class="form-control border-end-0" value="${img.name}" onchange="updateImageMetadata('${img.id}', 'name', this.value)">
                                    <span class="input-group-text bg-light border-start-0 text-muted">.webp</span>
                                </div>
                            </div>
                            
                            <div class="row g-3 mb-3">
                                <div class="col-6">
                                    <label class="form-label small text-muted text-uppercase fw-bold mb-1">User Alt Text</label>
                                    <input type="text" class="form-control form-control-sm" value="${img.alt}" onchange="updateImageMetadata('${img.id}', 'alt', this.value)">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small text-muted text-uppercase fw-bold mb-1">User Title</label>
                                    <input type="text" class="form-control form-control-sm" value="${img.title}" onchange="updateImageMetadata('${img.id}', 'title', this.value)">
                                </div>
                            </div>

                            <div class="row g-3 mb-3">
                                <div class="col-6">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <label class="form-label small text-primary text-uppercase fw-bold mb-0">Suggested Alt</label>
                                        ${img.suggestedAlt ? `
                                        <button class="btn btn-link p-0 text-decoration-none extra-small" onclick="generateAISuggestions('${img.id}')" title="Regenerate">
                                            <i class="bi bi-arrow-clockwise ${img.aiStatus === 'loading' ? 'spin' : ''}"></i>
                                        </button>` : ''}
                                    </div>
                                    <input type="text" class="form-control form-control-sm suggested-field" value="${img.suggestedAlt || ''}" placeholder="${img.aiStatus === 'loading' ? 'Generating...' : 'Not generated'}" onchange="updateImageMetadata('${img.id}', 'suggestedAlt', this.value)">
                                </div>
                                <div class="col-6">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <label class="form-label small text-primary text-uppercase fw-bold mb-0">Suggested Title</label>
                                        ${img.suggestedTitle ? `
                                        <button class="btn btn-link p-0 text-decoration-none extra-small" onclick="generateAISuggestions('${img.id}')" title="Regenerate">
                                            <i class="bi bi-arrow-clockwise ${img.aiStatus === 'loading' ? 'spin' : ''}"></i>
                                        </button>` : ''}
                                    </div>
                                    <input type="text" class="form-control form-control-sm suggested-field" value="${img.suggestedTitle || ''}" placeholder="${img.aiStatus === 'loading' ? 'Generating...' : 'Not generated'}" onchange="updateImageMetadata('${img.id}', 'suggestedTitle', this.value)">
                                </div>
                            </div>

                            ${!img.suggestedAlt && !img.suggestedTitle && img.aiStatus !== 'loading' ? `
                            <div class="mb-3">
                                <button class="btn btn-sm btn-outline-primary w-100 py-2 rounded-3 border-dashed" onclick="generateAISuggestions('${img.id}')">
                                    <i class="bi bi-magic me-2"></i> Get AI Suggestions (1 Credit)
                                </button>
                            </div>
                            ` : ''}

                            <div class="d-flex justify-content-between align-items-center pt-2 border-top mt-auto">
                                <div class="small text-muted">
                                    <i class="bi bi-weight me-1"></i> ${sizeKB} KB
                                    ${img.optimizedSize ? ` <i class="bi bi-arrow-right mx-1"></i> <span class="text-success fw-bold">${optSizeKB} KB</span>` : ''}
                                </div>
                                <div class="d-flex gap-2 align-items-center">
                                    <div id="status-${img.id}">
                                        ${img.status === 'pending' ? '<span class="badge bg-light text-muted border">Pending</span>' : 
                                          img.status === 'processing' ? '<span class="badge bg-warning-subtle text-warning border border-warning-subtle"><i class="bi bi-arrow-repeat spin me-1"></i></span>' :
                                          `<span class="badge bg-success-subtle text-success border border-success-subtle">-${savings}%</span>`}
                                    </div>
                                    <button class="btn btn-sm btn-outline-primary rounded-circle" onclick="convertAndDownloadSingle('${img.id}')" title="Download Optimized">
                                        <i class="bi bi-download"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        imageGrid.appendChild(col);
    });

    updateTotalSavings();
}

function updateImageMetadata(id, field, value) {
    const img = uploadedImages.find(i => i.id === id);
    if (img) img[field] = value;
}

function toggleImageSelection(id, isSelected) {
    const img = uploadedImages.find(i => i.id === id);
    if (img) img.selected = isSelected;
    const allSelected = uploadedImages.length > 0 && uploadedImages.every(i => i.selected);
    document.getElementById('selectAllImages').checked = allSelected;
}

function toggleSelectAll(checkbox) {
    uploadedImages.forEach(img => img.selected = checkbox.checked);
    renderImages();
}

function removeImage(id) {
    uploadedImages = uploadedImages.filter(i => i.id !== id);
    renderImages();
}

function clearAll() {
    if (uploadedImages.length === 0) return;
    Swal.fire({
        title: 'Are you sure?',
        text: "This will remove all images from the queue.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#FF6B35',
        confirmButtonText: 'Yes, clear all!'
    }).then((result) => {
        if (result.isConfirmed) {
            uploadedImages = [];
            renderImages();
        }
    });
}

function updateTotalSavings() {
    const optimized = uploadedImages.filter(i => i.optimizedSize > 0);
    if (optimized.length === 0) {
        document.getElementById('total-savings').textContent = 'Total Savings: 0%';
        return;
    }
    const totalOrig = optimized.reduce((sum, i) => sum + i.originalSize, 0);
    const totalOpt = optimized.reduce((sum, i) => sum + i.optimizedSize, 0);
    const savings = ((totalOrig - totalOpt) / totalOrig * 100).toFixed(1);
    document.getElementById('total-savings').textContent = `Total Savings: ${savings}%`;
}

async function convertToWebPAll() {
    if (uploadedImages.length === 0) return;
    const btn = document.getElementById('convert-all-btn');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-arrow-repeat spin me-2"></i> Converting...';

    for (let imgObj of uploadedImages) {
        if (imgObj.status === 'success') continue;
        imgObj.status = 'processing';
        renderImages();
        try {
            await convertAndDownload(imgObj);
            imgObj.status = 'success';
        } catch (err) {
            imgObj.status = 'error';
        }
        renderImages();
        await new Promise(r => setTimeout(r, 500));
    }

    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-check-all me-2"></i> All Completed!';
    setTimeout(() => { btn.innerHTML = originalText; }, 3000);
}

async function generateAISuggestions(id) {
    const img = uploadedImages.find(i => i.id === id);
    if (!img) return;
    const domain = document.getElementById('targetDomain').value.trim();
    img.aiStatus = 'loading';
    renderImages();
    try {
        const formData = new FormData();
        formData.append('filename', img.name);
        formData.append('url', img.url || '');
        formData.append('domain', domain);
        
        const response = await fetch('<?= BASE_URL ?>/api/image-optimization/generate-meta', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();
        if (data.success) {
            img.suggestedAlt = data.data.alt;
            img.suggestedTitle = data.data.title;
            img.aiStatus = 'success';
        } else {
            img.aiStatus = 'error';
        }
    } catch (err) {
        img.aiStatus = 'error';
    }
    renderImages();
}

async function generateAISuggestionsAll() {
    for (let img of uploadedImages) {
        if (!img.suggestedAlt && !img.suggestedTitle && img.aiStatus !== 'loading') {
            await generateAISuggestions(img.id);
        }
    }
}

async function generateAISuggestionsSelected() {
    const selected = uploadedImages.filter(img => img.selected);
    if (selected.length === 0) {
        Swal.fire('No selection', 'Please select at least one image.', 'warning');
        return;
    }
    for (let img of selected) {
        if (img.aiStatus !== 'loading') {
            await generateAISuggestions(img.id);
        }
    }
}

async function convertAndDownloadSingle(id) {
    const imgObj = uploadedImages.find(i => i.id === id);
    if (!imgObj) return;
    imgObj.status = 'processing';
    renderImages();
    try {
        await convertAndDownload(imgObj);
        imgObj.status = 'success';
    } catch (err) {
        imgObj.status = 'error';
    }
    renderImages();
}

function convertAndDownload(imgObj) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = "anonymous";
        img.onload = function() {
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(function(blob) {
                if (!blob) { reject('Blob creation failed'); return; }
                imgObj.optimizedSize = blob.size;
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = (imgObj.name || 'image') + ".webp";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                setTimeout(() => URL.revokeObjectURL(url), 100);
                resolve();
            }, 'image/webp', 0.8);
        };
        img.onerror = () => reject('Image load failed');
        img.src = imgObj.src;
    });
}

async function showHistory() {
    const modalEl = document.getElementById('historyModal');
    const modal = new bootstrap.Modal(modalEl);
    const body = document.getElementById('historyTableBody');
    
    if (!window.historyFiltersInitialized) {
        window.historyFiltersInitialized = true;
        flatpickr("#history-date-picker", {
            mode: "range",
            dateFormat: "Y-m-d",
            onClose: function(selectedDates, dateStr) {
                if (selectedDates.length === 2) {
                    document.getElementById('history-selected-date-text').innerText = dateStr;
                    document.getElementById('history-date-range-input').value = dateStr;
                    refreshHistoryTable();
                } else if (selectedDates.length === 0) {
                    document.getElementById('history-selected-date-text').innerText = "All Time";
                    document.getElementById('history-date-range-input').value = "";
                    refreshHistoryTable();
                }
            }
        });
        let historySearchTimer;
        document.getElementById('history-search').addEventListener('input', function() {
            clearTimeout(historySearchTimer);
            historySearchTimer = setTimeout(refreshHistoryTable, 300);
        });
    }

    body.innerHTML = '<tr><td colspan="6" class="text-center py-5"><i class="bi bi-arrow-repeat spin fs-2 text-muted"></i></td></tr>';
    modal.show();
    refreshHistoryTable();
}

async function refreshHistoryTable() {
    const body = document.getElementById('historyTableBody');
    const search = document.getElementById('history-search').value;
    const dateRange = document.getElementById('history-date-range-input').value;
    const domain = document.getElementById('targetDomain').value.trim();

    try {
        const response = await fetch(`<?= BASE_URL ?>/api/image-optimization/history?search=${encodeURIComponent(search)}&date_range=${encodeURIComponent(dateRange)}&domain=${encodeURIComponent(domain)}`);
        const data = await response.json();
        
        if (data.success) {
            if (data.data.history.length === 0) {
                body.innerHTML = '<tr><td colspan="6" class="text-center py-5 text-muted">No history found.</td></tr>';
                return;
            }
            
            body.innerHTML = data.data.history.map(item => `
                <tr>
                    <td>
                        <div class="fw-bold text-dark" style="font-size: 0.8rem;">${new Date(item.created_at).toLocaleDateString()}</div>
                        <div class="extra-small text-muted">${new Date(item.created_at).toLocaleTimeString()}</div>
                    </td>
                    <td>
                        <div class="fw-bold text-dark truncate-2" style="max-width: 200px;">${item.original_filename}</div>
                        ${item.source_url ? `<a href="${item.source_url}" target="_blank" class="history-url">${item.source_url}</a>` : ''}
                    </td>
                    <td><span class="badge bg-light text-dark border font-monospace" style="font-size: 0.7rem;">${item.target_domain || '-'}</span></td>
                    <td style="max-width: 250px;"><div class="small text-muted border-start ps-2">${item.suggested_alt || ''}</div></td>
                    <td style="max-width: 250px;"><div class="small fw-bold border-start ps-2 text-primary">${item.suggested_title || ''}</div></td>
                    <td>
                        <button class="btn btn-sm btn-light border shadow-none" onclick="copyHistoryItem('${item.id}')" title="Copy Details">
                            <i class="bi bi-copy"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
            
            window.historyData = data.data.history;
        }
    } catch (err) {
        body.innerHTML = '<tr><td colspan="6" class="text-center py-5 text-danger">Failed to load history.</td></tr>';
    }
}

function copyHistoryItem(id) {
    const item = window.historyData.find(i => i.id == id);
    if (!item) return;
    const text = `Alt: ${item.suggested_alt}\nTitle: ${item.suggested_title}`;
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({
            icon: 'success',
            title: 'Copied!',
            text: 'Suggestions copied to clipboard',
            toast: true,
            position: 'top-end',
            timer: 2000,
            showConfirmButton: false
        });
    });
}
</script>

<style>
.spin { animation: spin 1s linear infinite; }
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.border-dashed { border-style: dashed !important; }
</style>

<?php require __DIR__ . '/../layout/footer.php'; ?>
