(function() {
    function getPanelOpts() {
        var elAi     = document.getElementById('packshotphoto-session-auto-ai');
        var elEuAi   = document.getElementById('packshotphoto-session-auto-eu-ai');
        var elWebp   = document.getElementById('packshotphoto-session-auto-webp');
        var elAvif   = document.getElementById('packshotphoto-session-auto-avif');
        var elResize = document.getElementById('packshotphoto-session-auto-resize');
        var elWidth  = document.getElementById('packshotphoto-session-resize-width');
        var elCtx    = document.getElementById('packshotphoto-upload-context');

        return {
            packshotphoto_session_auto_ai:     (elAi && elAi.checked) ? '1' : '0',
            packshotphoto_session_auto_eu_ai:  (elEuAi && elEuAi.checked) ? '1' : '0',
            packshotphoto_session_auto_webp:   (elWebp && elWebp.checked) ? '1' : '0',
            packshotphoto_session_auto_avif:   (elAvif && elAvif.checked) ? '1' : '0',
            packshotphoto_session_auto_resize: (elResize && elResize.checked) ? '1' : '0',
            packshotphoto_session_resize_width: (elWidth ? elWidth.value : '') || '1920',
            packshotphoto_upload_context:       (elCtx ? elCtx.value : '') || ''
        };
    }

    function injectParams(up) {
        if (!up) return;
        up.settings = up.settings || {};
        up.settings.multipart_params = up.settings.multipart_params || {};
        var opts = getPanelOpts();
        Object.assign(up.settings.multipart_params, opts);
    }

    function attachPlupload(uploader) {
        if (!uploader || !uploader.bind) return;
        uploader.bind('BeforeUpload', function(up) {
            injectParams(up);
        });
    }

    // 1. Hook existing Plupload instances
    var checkCount = 0;
    var checkInterval = setInterval(function() {
        checkCount++;
        if (typeof wp !== 'undefined' && wp.uploader && wp.uploader.uploader) {
            attachPlupload(wp.uploader.uploader);
            clearInterval(checkInterval);
        }
        if (checkCount > 25) {
            clearInterval(checkInterval);
        }
    }, 200);

    // 2. Hook wp.Uploader constructor prototype if present
    if (typeof wp !== 'undefined' && wp.Uploader) {
        var origInit = wp.Uploader.prototype.init;
        wp.Uploader.prototype.init = function() {
            var res = origInit ? origInit.apply(this, arguments) : null;
            if (this.uploader) {
                attachPlupload(this.uploader);
            }
            return res;
        };
    }

    // Auto-save settings in the background
    var saveTimeout;
    function savePanelSettings() {
        var indicator = document.getElementById('packshotphoto-panel-save-indicator');
        if (indicator) {
            indicator.style.opacity = '1';
            indicator.innerHTML = '<span>⏳</span> Saving settings...';
        }

        var opts = getPanelOpts();
        var nonceVal = (typeof packshotphotoUploadPanelOpts !== 'undefined' && packshotphotoUploadPanelOpts.nonce)
            ? packshotphotoUploadPanelOpts.nonce
            : ((typeof packshotphotoConfig !== 'undefined' && packshotphotoConfig.nonce) ? packshotphotoConfig.nonce : '');

        var data = new FormData();
        data.append('action', 'packshotphoto_save_upload_session_opts');
        data.append('nonce', nonceVal);
        data.append('auto_ai', opts.packshotphoto_session_auto_ai);
        data.append('auto_eu_ai', opts.packshotphoto_session_auto_eu_ai);
        data.append('auto_webp', opts.packshotphoto_session_auto_webp);
        data.append('auto_avif', opts.packshotphoto_session_auto_avif);
        data.append('auto_resize', opts.packshotphoto_session_auto_resize);
        data.append('resize_width', opts.packshotphoto_session_resize_width);
        data.append('context', opts.packshotphoto_upload_context);

        var ajaxEndpoint = (typeof ajaxurl !== 'undefined') ? ajaxurl : (typeof packshotphotoConfig !== 'undefined' ? packshotphotoConfig.ajaxUrl : '/wp-admin/admin-ajax.php');

        fetch(ajaxEndpoint, {
            method: 'POST',
            body: data
        })
        .then(function(res) { return res.json(); })
        .then(function(res) {
            if (res.success && indicator) {
                indicator.innerHTML = '<span>✓</span> Settings saved';
                setTimeout(function() {
                    if (indicator.innerHTML.indexOf('Settings saved') !== -1) {
                        indicator.style.opacity = '0';
                    }
                }, 1500);
            }
        })
        .catch(function() {
            if (indicator) {
                indicator.innerHTML = '<span>❌</span> Connection error';
                setTimeout(function() {
                    indicator.style.opacity = '0';
                }, 3000);
            }
        });
    }

    function debounceSave() {
        clearTimeout(saveTimeout);
        saveTimeout = setTimeout(savePanelSettings, 400);
    }

    // Toggle dependent fields and auto-save on change
    document.addEventListener('change', function(e) {
        if (!e.target) return;
        
        var targetId = e.target.id;
        if (targetId === 'packshotphoto-session-auto-resize') {
            var widthInput = document.getElementById('packshotphoto-session-resize-width');
            if (widthInput) widthInput.disabled = !e.target.checked;
        }
        if (targetId === 'packshotphoto-session-auto-webp' && e.target.checked) {
            var avif = document.getElementById('packshotphoto-session-auto-avif');
            if (avif && !avif.disabled) avif.checked = false;
        }
        if (targetId === 'packshotphoto-session-auto-avif' && e.target.checked) {
            var webp = document.getElementById('packshotphoto-session-auto-webp');
            if (webp && !webp.disabled) webp.checked = false;
        }

        // Trigger auto-save if any of the session inputs changed
        if ([
            'packshotphoto-session-auto-ai',
            'packshotphoto-session-auto-eu-ai',
            'packshotphoto-session-auto-webp',
            'packshotphoto-session-auto-avif',
            'packshotphoto-session-auto-resize'
        ].indexOf(targetId) !== -1) {
            savePanelSettings();
        }
    });

    // Listen to text/number inputs
    document.addEventListener('input', function(e) {
        if (!e.target) return;
        var targetId = e.target.id;
        if (targetId === 'packshotphoto-session-resize-width' || targetId === 'packshotphoto-upload-context') {
            debounceSave();
        }
    });

    // Save on load to guarantee backend transient is present
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', savePanelSettings);
    } else {
        savePanelSettings();
    }

    // Init width field state
    document.addEventListener('DOMContentLoaded', function() {
        var resizeToggle = document.getElementById('packshotphoto-session-auto-resize');
        var widthInput   = document.getElementById('packshotphoto-session-resize-width');
        if (resizeToggle && widthInput) {
            widthInput.disabled = !resizeToggle.checked;
        }
    });

    // Real-time Upload Tracker for PMM
    var trackedItems = {};

    function checkMediaItems() {
        var items = document.querySelectorAll('#media-items .media-item');
        if (!items.length) return;
        
        items.forEach(function(item) {
            if (item.classList.contains('packshotphoto-bound')) return;
            
            var match = item.id.match(/^media-item-(\d+)$/);
            if (!match) return;
            
            var attachmentId = match[1];
            item.classList.add('packshotphoto-bound');
            
            initAttachmentDashboard(attachmentId, item);
        });
    }

    // Run scan loop every 500ms
    var scanInterval = setInterval(checkMediaItems, 500);

    function initAttachmentDashboard(id, element) {
        var dashboard = document.createElement('div');
        dashboard.className = 'packshotphoto-upload-item-dashboard';
        dashboard.id = 'packshotphoto-dashboard-' + id;
        element.appendChild(dashboard);

        // Check active session options from the panel fields
        var autoAi = document.getElementById('packshotphoto-session-auto-ai') ? document.getElementById('packshotphoto-session-auto-ai').checked : false;
        var autoEuAi = document.getElementById('packshotphoto-session-auto-eu-ai') ? document.getElementById('packshotphoto-session-auto-eu-ai').checked : false;
        var autoWebp = document.getElementById('packshotphoto-session-auto-webp') ? document.getElementById('packshotphoto-session-auto-webp').checked : false;
        var autoAvif = document.getElementById('packshotphoto-session-auto-avif') ? document.getElementById('packshotphoto-session-auto-avif').checked : false;
        
        var isProcessing = autoAi || autoEuAi || autoWebp || autoAvif;

        if (isProcessing) {
            renderProcessingState(dashboard, id);
            pollAttachmentStatus(id, dashboard);
        } else {
            fetchInitialState(id, dashboard);
        }
    }

    function renderProcessingState(dashboard, id) {
        dashboard.innerHTML = 
            '<div class="packshotphoto-dashboard-header">' +
                '<div class="packshotphoto-dashboard-title">🖼️ PackshotPhoto AI</div>' +
                '<span class="packshotphoto-dashboard-status-badge status-processing">' +
                    '<span class="packshotphoto-spinner-bullet"></span> ⏳ AI &amp; Optimization processing...' +
                '</span>' +
            '</div>' +
            '<div style="font-size: 11px; color: #64748b; text-align: center; padding: 12px 0; font-style: italic;">' +
                'Generating AI metadata descriptions, converting formats and running optimizations in the background. Please wait...' +
            '</div>';
    }

    function fetchInitialState(id, dashboard) {
        var data = new FormData();
        data.append('action', 'packshotphoto_check_item_status');
        data.append('nonce', packshotphotoUploadPanelOpts.nonce);
        data.append('id', id);

        fetch(ajaxurl, {
            method: 'POST',
            body: data
        })
        .then(function(res) { return res.json(); })
        .then(function(res) {
            if (res.success) {
                renderDashboardContent(dashboard, id, res.data, false);
            }
        })
        .catch(function(err) {
            console.error('PMM Fetch State Error:', err);
        });
    }

    function pollAttachmentStatus(id, dashboard) {
        var attempts = 0;
        var maxAttempts = 60; // 2 minutes max

        var poll = function() {
            var data = new FormData();
            data.append('action', 'packshotphoto_check_item_status');
            data.append('nonce', packshotphotoUploadPanelOpts.nonce);
            data.append('id', id);

            fetch(ajaxurl, {
                method: 'POST',
                body: data
            })
            .then(function(res) { return res.json(); })
            .then(function(res) {
                if (res.success) {
                    if (res.data.processing && attempts < maxAttempts) {
                        attempts++;
                        setTimeout(poll, 2000);
                    } else {
                        // Background processing complete!
                        renderDashboardContent(dashboard, id, res.data, true);

                        // Accumulate details for CSV log
                        var actions = [];
                        if (res.data.alt || res.data.caption || res.data.desc) {
                            actions.push('AI_DESC');
                        }
                        if (res.data.mime_type) {
                            var formatLabel = res.data.mime_type.split('/')[1].toUpperCase();
                            actions.push('FORMAT_' + formatLabel);
                        }
                        var act = actions.join(' & ') || 'UPLOAD_PROCESS';

                        if (typeof window.packshotphotoAddLogEntry === 'function') {
                            window.packshotphotoAddLogEntry({
                                id: id,
                                original_filename: res.data.filename || ('ID ' + id),
                                new_filename: res.data.filename || ('ID ' + id),
                                action: act,
                                status: 'Success',
                                original_size: '-',
                                new_size: '-',
                                savings: '-',
                                width_change: '-',
                                height_change: '-',
                                alt: res.data.alt || '-',
                                caption: res.data.caption || '-',
                                message: 'Uploaded and processed successfully'
                            });
                        }
                    }
                } else {
                    setTimeout(poll, 2000);
                }
            })
            .catch(function() {
                setTimeout(poll, 2000);
            });
        };

        // Start polling after 1.5 seconds to let async start
        setTimeout(poll, 1500);
    }

    function renderDashboardContent(dashboard, id, data, highlightSuccess) {
        var statusHtml = '';
        if (highlightSuccess) {
            statusHtml = 
                '<span class="packshotphoto-dashboard-status-badge status-complete">' +
                    '✓ Complete!' +
                '</span>';
        } else {
            statusHtml = 
                '<span class="packshotphoto-dashboard-status-badge status-idle">' +
                    '✓ Ready' +
                '</span>';
        }

        var mime = data.mime_type || '';
        var isWebp = mime === 'image/webp';
        var isAvif = mime === 'image/avif';
        var isConvertible = ['image/jpeg', 'image/png', 'image/gif'].indexOf(mime) !== -1;
        var targetFormat = isWebp ? 'avif' : 'webp';

        var convertButtonHtml = '';
        if (isWebp || isAvif || isConvertible) {
            convertButtonHtml = 
                '<button type="button" ' +
                        'class="button button-small packshotphoto-convert-btn" ' +
                        'data-id="' + id + '" ' +
                        'data-nonce="' + data.edit_nonce + '" ' +
                        'data-filesize="0" ' +
                        'data-target-format="' + targetFormat + '">' +
                    '<span class="packshotphoto-btn-text">🔄 Convert</span>' +
                '</button>';
        }

        var restoreButtonHtml = '';
        if (data.show_restore) {
            restoreButtonHtml = 
                '<button type="button" ' +
                        'class="button button-small packshotphoto-restore-btn" ' +
                        'data-id="' + id + '" ' +
                        'data-nonce="' + data.edit_nonce + '" ' +
                        'data-has-ai-backup="1" ' +
                        'data-has-file-backup="1" ' +
                        'data-has-original-filename="1">' +
                    '<span class="packshotphoto-btn-text">↩️ Restore</span>' +
                '</button>';
        }

        dashboard.innerHTML = 
            '<div class="packshotphoto-dashboard-header">' +
                '<div class="packshotphoto-dashboard-title">🖼️ PackshotPhoto AI</div>' +
                statusHtml +
            '</div>' +
            
            '<div class="packshotphoto-dashboard-fields-grid">' +
                '<div class="packshotphoto-dashboard-field-box">' +
                    '<span class="packshotphoto-dashboard-field-label">Alt Text</span>' +
                    '<div class="packshotphoto-cell-wrapper">' +
                        '<textarea class="packshotphoto-editable" data-id="' + id + '" data-field="alt" data-nonce="' + data.edit_nonce + '" placeholder="Alt text...">' + (data.alt || '') + '</textarea>' +
                        '<span class="packshotphoto-skeleton"></span>' +
                        '<span class="packshotphoto-save-indicator">Saving...</span>' +
                    '</div>' +
                '</div>' +
                
                '<div class="packshotphoto-dashboard-field-box">' +
                    '<span class="packshotphoto-dashboard-field-label">Caption</span>' +
                    '<div class="packshotphoto-cell-wrapper">' +
                        '<textarea class="packshotphoto-editable" data-id="' + id + '" data-field="caption" data-nonce="' + data.edit_nonce + '" placeholder="Caption...">' + (data.caption || '') + '</textarea>' +
                        '<span class="packshotphoto-skeleton"></span>' +
                        '<span class="packshotphoto-save-indicator">Saving...</span>' +
                    '</div>' +
                '</div>' +
                
                '<div class="packshotphoto-dashboard-field-box">' +
                    '<span class="packshotphoto-dashboard-field-label">Description</span>' +
                    '<div class="packshotphoto-cell-wrapper">' +
                        '<textarea class="packshotphoto-editable" data-id="' + id + '" data-field="description" data-nonce="' + data.edit_nonce + '" placeholder="Description...">' + (data.desc || data.description || '') + '</textarea>' +
                        '<span class="packshotphoto-skeleton"></span>' +
                        '<span class="packshotphoto-save-indicator">Saving...</span>' +
                    '</div>' +
                '</div>' +
            '</div>' +

            '<div class="packshotphoto-dashboard-actions">' +
                '<button type="button" ' +
                        'class="button button-small packshotphoto-ai-btn" ' +
                        'data-id="' + id + '" ' +
                        'data-nonce="' + data.edit_nonce + '" ' +
                        'data-language="auto">' +
                    '<span class="packshotphoto-ai-text">🤖 Generate AI</span>' +
                '</button>' +
                
                convertButtonHtml +
                
                '<button type="button" ' +
                        'class="button button-small packshotphoto-manual-resize-trigger" ' +
                        'data-id="' + id + '" ' +
                        'data-nonce="' + data.edit_nonce + '">' +
                    '<span class="packshotphoto-btn-text">📐 Resize</span>' +
                '</button>' +

                restoreButtonHtml +
            '</div>';
    }
}());
