{% load i18n static %}<!DOCTYPE html>
<html>
<head>
    <title>{% trans "Popup closing…" %}</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 20px; }
        .success { color: #16a34a; }
        .error { color: #dc2626; }
        .info { color: #2563eb; margin: 10px 0; font-size: 14px; }
        button { padding: 10px 20px; font-size: 16px; cursor: pointer; margin-top: 15px; }
    </style>
</head>
<body>
<p>{% trans "Processing..." %}</p>

<!-- Django provides this data -->
<script type="application/json" id="django-admin-popup-response-constants">{{ popup_response_data|safe }}</script>

<script type="text/javascript">
(function() {
    'use strict';
    
    // Debug info
    console.log('=== Popup Response Debug ===');
    console.log('window.name:', window.name);
    console.log('window.opener:', window.opener);
    
    var dataElement = document.getElementById("django-admin-popup-response-constants");
    console.log('Data element:', dataElement);
    console.log('Data content:', dataElement ? dataElement.textContent : 'NO ELEMENT');
    
    var initData;
    try {
        var rawData = dataElement.textContent;
        console.log('Raw data:', rawData);
        initData = JSON.parse(rawData);
        console.log('Parsed data:', initData);
    } catch(e) {
        console.error('JSON parse error:', e);
        // Show debug info to help diagnose
        document.body.innerHTML = '<div>' +
            '<p class="error"><strong>Debug Info - JSON Parse Failed</strong></p>' +
            '<p class="info">Raw data: <code>' + (dataElement ? dataElement.textContent : 'no element') + '</code></p>' +
            '<p class="info">Error: ' + e.message + '</p>' +
            '<p>The category was likely saved. Please close this window and refresh the parent page.</p>' +
            '<button onclick="window.close()">Close Window</button>' +
            '</div>';
        return;
    }
    
    var action = initData.action || 'add';
    var value = initData.value;
    var obj = initData.obj;
    var newValue = initData.new_value;
    
    console.log('Action:', action, 'Value:', value, 'Obj:', obj);
    
    // Method 1: Standard Django opener approach
    function tryOpener() {
        if (!window.opener) {
            console.log('No window.opener');
            return false;
        }
        
        try {
            if (action === 'change' && typeof window.opener.dismissChangeRelatedObjectPopup === 'function') {
                window.opener.dismissChangeRelatedObjectPopup(window, value, obj, newValue);
                return true;
            } else if (action === 'delete' && typeof window.opener.dismissDeleteRelatedObjectPopup === 'function') {
                window.opener.dismissDeleteRelatedObjectPopup(window, value);
                return true;
            } else if (typeof window.opener.dismissAddRelatedObjectPopup === 'function') {
                console.log('Calling dismissAddRelatedObjectPopup');
                window.opener.dismissAddRelatedObjectPopup(window, value, obj);
                return true;
            }
            console.log('Opener exists but no dismiss function found');
            console.log('Available functions:', Object.keys(window.opener).filter(k => k.indexOf('dismiss') !== -1));
            return false;
        } catch(e) {
            console.log('Opener access error:', e);
            return false;
        }
    }
    
    // Method 2: postMessage
    function tryPostMessage() {
        if (!window.opener) return false;
        
        try {
            var message = {
                type: 'adminita-popup-response',
                action: action,
                value: value,
                obj: obj,
                newValue: newValue,
                windowName: window.name
            };
            window.opener.postMessage(message, '*');
            console.log('postMessage sent');
            setTimeout(function() { window.close(); }, 150);
            return true;
        } catch(e) {
            console.log('postMessage error:', e);
            return false;
        }
    }
    
    // Method 3: Direct DOM manipulation
    function tryDirectDOM() {
        if (!window.opener) return false;
        
        try {
            var selectId = window.name.replace(/__popup$/, '');
            console.log('Looking for select:', selectId);
            var select = window.opener.document.getElementById(selectId);
            
            if (!select) {
                console.log('Select not found');
                return false;
            }
            
            if (action === 'add' || action === 'default') {
                var option = window.opener.document.createElement('option');
                option.value = value;
                option.textContent = obj;
                option.selected = true;
                
                for (var i = 0; i < select.options.length; i++) {
                    select.options[i].selected = false;
                }
                
                select.appendChild(option);
                console.log('Direct DOM update successful');
                window.close();
                return true;
            }
            return false;
        } catch(e) {
            console.log('Direct DOM error:', e);
            return false;
        }
    }
    
    // Try all methods
    var success = tryOpener();
    
    if (!success) {
        console.log('Trying postMessage...');
        success = tryPostMessage();
    }
    
    if (!success) {
        console.log('Trying direct DOM...');
        success = tryDirectDOM();
    }
    
    if (!success) {
        console.log('All methods failed');
        document.body.innerHTML = '<div style="text-align: center;">' +
            '<p class="success" style="font-size: 18px; font-weight: bold;">✓ Saved successfully!</p>' +
            '<p style="margin: 15px 0;">The new item was saved but the dropdown could not be updated automatically.</p>' +
            '<p><strong>Please close this window and refresh the parent page.</strong></p>' +
            '<button onclick="window.close()">Close Window</button>' +
            '</div>';
    }
})();
</script>
</body>
</html>