{% extends "admin/base.html" %}
{% load i18n admin_urls static admin_modify %}

{% block breadcrumbs %}
{% endblock %}

{% block content_title %}
    {% if add %}
        {% blocktrans with name=opts.verbose_name %}Add {{ name }}{% endblocktrans %}
    {% else %}
        {% blocktrans with name=opts.verbose_name %}Change {{ name }}{% endblocktrans %}
    {% endif %}
{% endblock %}

{% block content %}
    {# Object Tools (History, View on Site) #}
    {% if change and not is_popup %}
    <div class="mb-6 flex items-center justify-end space-x-3">
        <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg font-medium text-sm transition-colors">
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            {% trans 'History' %}
        </a>
        {% if has_absolute_url %}
        <a href="{{ absolute_url }}" class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium text-sm transition-colors" target="_blank">
            {% trans 'View on site' %}
            <svg class="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/>
            </svg>
        </a>
        {% endif %}
    </div>
    {% endif %}

    <form method="post" id="{{ opts.model_name }}_form" enctype="multipart/form-data" class="space-y-6">
    {% csrf_token %}
    {% if is_popup %}<input type="hidden" name="_popup" value="1">{% endif %}
    {% if to_field %}<input type="hidden" name="_to_field" value="{{ to_field }}">{% endif %}
    
    {# Form Errors #}
    {% if errors %}
    <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
        <div class="flex items-start">
            <svg class="w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 mr-3 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
            </svg>
            <div>
                <h3 class="text-sm font-medium text-red-800 dark:text-red-200">
                    {% trans "Please correct the errors below." %}
                </h3>
                {{ adminform.form.non_field_errors }}
            </div>
        </div>
    </div>
    {% endif %}
    
    {# Main Form Fieldsets #}
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
        {% block field_sets %}
        {% for fieldset in adminform %}
            {% include "admin/includes/fieldset.html" %}
        {% endfor %}
        {% endblock %}
    </div>
    
    {# Inline Forms - Uses stacked.html or tabular.html templates #}
    {% block inline_field_sets %}
    {% for inline_admin_formset in inline_admin_formsets %}
        {% include inline_admin_formset.opts.template %}
    {% endfor %}
    {% endblock %}
    
    {# Submit Buttons #}
    {% block submit_buttons_bottom %}
    {% include "admin/submit_line.html" %}
    {% endblock %}
    
    </form>
{% endblock %}

{% block extrastyle %}
    {{ block.super }}
    {{ adminform.form.media.css }}
{% endblock %}

{% block extrajs %}
    <script src="{% url 'admin:jsi18n' %}"></script>
    <script src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script>
    <script src="{% static 'admin/js/jquery.init.js' %}"></script>
    <script src="{% static 'admin/js/core.js' %}"></script>
    <script src="{% static 'admin/js/urlify.js' %}"></script>
    <script src="{% static 'admin/js/prepopulate.js' %}"></script>
    <script src="{% static 'admin/js/vendor/xregexp/xregexp.min.js' %}"></script>
    <script src="{% static 'admin/js/inlines.js' %}"></script>
    <script src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>
    {{ media.js }}
    {% if add %}{% prepopulated_fields_js %}{% endif %}
    
    <script>
    // Fieldset toggle functionality
    function toggleFieldset(header) {
        const fieldset = header.closest('fieldset');
        const content = fieldset.querySelector('.fieldset-content');
        const description = fieldset.querySelector('.fieldset-description');
        const icon = header.querySelector('.collapse-icon');
        
        if (content.classList.contains('hidden')) {
            content.classList.remove('hidden');
            if (description) description.classList.remove('hidden');
            icon.classList.remove('-rotate-90');
        } else {
            content.classList.add('hidden');
            if (description) description.classList.add('hidden');
            icon.classList.add('-rotate-90');
        }
    }
    
    // Auto-expand fieldsets that contain validation errors
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('fieldset.module').forEach(function(fieldset) {
            const hasErrors = fieldset.querySelector('.text-red-600, .text-red-400, .errorlist');
            if (hasErrors) {
                const content = fieldset.querySelector('.fieldset-content');
                const description = fieldset.querySelector('.fieldset-description');
                const icon = fieldset.querySelector('.collapse-icon');
                
                if (content && content.classList.contains('hidden')) {
                    content.classList.remove('hidden');
                    if (description) description.classList.remove('hidden');
                    if (icon) icon.classList.remove('-rotate-90');
                }
            }
        });
    });
    </script>

    <script>
    // ===========================================
    // POPUP HANDLER - Fixes Django's popup system for Adminita
    // ===========================================
    (function() {
        'use strict';
        
        // Skip if we're inside a popup
        if (window.name && window.name.indexOf('__') !== -1) {
            console.log('Inside popup, skipping parent page handlers');
            return;
        }
        
        // Global function that popup_response.html calls
        window.dismissAddRelatedObjectPopup = function(win, newId, newRepr) {
            console.log('dismissAddRelatedObjectPopup called:', newId, newRepr);
            
            var selectId = null;
            
            // Try to get select ID from window name
            if (win && win.name) {
                selectId = win.name.replace(/__popup$/, '');
            }
            
            // Find the select element
            var select = selectId ? document.getElementById(selectId) : null;
            
            if (select) {
                // Add the new option
                var option = document.createElement('option');
                option.value = newId;
                option.textContent = newRepr;
                option.selected = true;
                
                // Deselect other options
                for (var i = 0; i < select.options.length; i++) {
                    select.options[i].selected = false;
                }
                
                select.appendChild(option);
                
                // Trigger change event
                //var event = new Event('change', { bubbles: true });
                //select.dispatchEvent(event);
                
                console.log('New option added to:', selectId);
            } else {
                console.log('Could not find select element:', selectId);
            }
            
            // Close the popup window
            if (win && typeof win.close === 'function') {
                try {
                    win.close();
                } catch(e) {
                    console.log('Could not close popup:', e);
                }
            }
        };
        
        window.dismissChangeRelatedObjectPopup = function(win, objId, newRepr, newId) {
            console.log('dismissChangeRelatedObjectPopup called');
            
            var selectId = null;
            if (win && win.name) {
                selectId = win.name.replace(/__popup$/, '');
            }
            
            var select = selectId ? document.getElementById(selectId) : null;
            
            if (select) {
                var id = newId || objId;
                for (var i = 0; i < select.options.length; i++) {
                    if (select.options[i].value == id) {
                        select.options[i].textContent = newRepr;
                        break;
                    }
                }
            }
            
            if (win && typeof win.close === 'function') {
                try { win.close(); } catch(e) {}
            }
        };
        
        window.dismissDeleteRelatedObjectPopup = function(win, objId) {
            console.log('dismissDeleteRelatedObjectPopup called');
            
            var selectId = null;
            if (win && win.name) {
                selectId = win.name.replace(/__popup$/, '');
            }
            
            var select = selectId ? document.getElementById(selectId) : null;
            
            if (select) {
                for (var i = select.options.length - 1; i >= 0; i--) {
                    if (select.options[i].value == objId) {
                        select.remove(i);
                        break;
                    }
                }
            }
            
            if (win && typeof win.close === 'function') {
                try { win.close(); } catch(e) {}
            }
        };
        
        // Listen for postMessage from popup (fallback method)
        window.addEventListener('message', function(event) {
            if (!event.data || event.data.type !== 'adminita-popup-response') {
                return;
            }
            
            console.log('Received postMessage from popup:', event.data);
            
            var data = event.data;
            var selectId = data.windowName ? data.windowName.replace(/__popup$/, '') : null;
            var select = selectId ? document.getElementById(selectId) : null;
            
            if (!select) {
                console.log('Could not find select for postMessage:', selectId);
                return;
            }
            
            if (data.action === 'add' || !data.action) {
                var option = document.createElement('option');
                option.value = data.value;
                option.textContent = data.obj;
                option.selected = true;
                
                for (var i = 0; i < select.options.length; i++) {
                    select.options[i].selected = false;
                }
                
                select.appendChild(option);
                
                console.log('postMessage: New option added');
            } else if (data.action === 'change') {
                var id = data.newValue || data.value;
                for (var i = 0; i < select.options.length; i++) {
                    if (select.options[i].value == id) {
                        select.options[i].textContent = data.obj;
                        break;
                    }
                }
            } else if (data.action === 'delete') {
                for (var i = select.options.length - 1; i >= 0; i--) {
                    if (select.options[i].value == data.value) {
                        select.remove(i);
                        break;
                    }
                }
            }
        });
        
        // Initialize popup links on DOM ready
        document.addEventListener('DOMContentLoaded', function() {
            initPopupLinks();
        });
        
        function initPopupLinks() {
            // Find all "add related" links using multiple selectors
            var addLinks = document.querySelectorAll(
                '.related-widget-wrapper a[href*="_popup=1"], ' +
                '.related-widget-wrapper a[href*="add/"], ' +
                'a.add-related, ' +
                'a[data-popup="yes"]'
            );
            
            console.log('Found popup links:', addLinks.length);
            
            addLinks.forEach(function(link) {
                // Get the associated select field ID
                var wrapper = link.closest('.related-widget-wrapper');
                var select = wrapper ? wrapper.querySelector('select') : null;
                var selectId = select ? select.id : null;
                
                if (!selectId) {
                    // Try to extract from link ID (e.g., "add_id_category" -> "id_category")
                    if (link.id && link.id.indexOf('add_') === 0) {
                        selectId = link.id.replace('add_', '');
                    }
                }
                
                // Clone to remove existing handlers
                var newLink = link.cloneNode(true);
                link.parentNode.replaceChild(newLink, link);
                
                newLink.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var href = this.href;
                    
                    // Ensure _popup=1 is in the URL
                    if (href.indexOf('_popup=1') === -1) {
                        href += (href.indexOf('?') === -1 ? '?' : '&') + '_popup=1';
                    }
                    
                    // Use the select ID for window name
                    var windowName = (selectId || 'popup_' + Date.now()) + '__popup';
                    
                    console.log('Opening popup:', href, 'Window name:', windowName);
                    
                    // Calculate popup dimensions and position
                    var width = 800;
                    var height = 600;
                    var left = Math.max(0, (screen.width - width) / 2);
                    var top = Math.max(0, (screen.height - height) / 2);
                    
                    // Open the popup
                    var popup = window.open(
                        href,
                        windowName,
                        'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=yes,resizable=yes,toolbar=no,menubar=no'
                    );
                    
                    if (popup) {
                        popup.focus();
                    } else {
                        alert('Popup was blocked. Please allow popups for this site.');
                    }
                    
                    return false;
                });
            });
            
            // Also handle change/edit links
            var changeLinks = document.querySelectorAll(
                '.related-widget-wrapper a[href*="change/"], ' +
                'a.change-related'
            );
            
            changeLinks.forEach(function(link) {
                var wrapper = link.closest('.related-widget-wrapper');
                var select = wrapper ? wrapper.querySelector('select') : null;
                var selectId = select ? select.id : null;
                
                if (!selectId && link.id && link.id.indexOf('change_') === 0) {
                    selectId = link.id.replace('change_', '');
                }
                
                var newLink = link.cloneNode(true);
                link.parentNode.replaceChild(newLink, link);
                
                newLink.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var href = this.href;
                    if (href.indexOf('_popup=1') === -1) {
                        href += (href.indexOf('?') === -1 ? '?' : '&') + '_popup=1';
                    }
                    
                    var windowName = (selectId || 'popup_' + Date.now()) + '__popup';
                    
                    var width = 800;
                    var height = 600;
                    var left = Math.max(0, (screen.width - width) / 2);
                    var top = Math.max(0, (screen.height - height) / 2);
                    
                    var popup = window.open(
                        href,
                        windowName,
                        'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=yes,resizable=yes,toolbar=no,menubar=no'
                    );
                    
                    if (popup) popup.focus();
                    
                    return false;
                });
            });
        }
    })();
    </script>

    <script>
    // ===========================================
    // FORM AUTOSAVE - Preserves content across page refresh
    // ===========================================
    (function() {
        'use strict';
        
        // Don't run in popups
        if (window.name && window.name.indexOf('__') !== -1) {
            return;
        }
        
        var form = null;
        var formId = window.location.pathname;
        var storageKey = 'adminFormData_' + formId.replace(/\//g, '_');
        var saveInterval = null;
        
        function getFormFields() {
            if (!form) return [];
            return form.querySelectorAll(
                'input[type="text"], input[type="email"], input[type="url"], input[type="number"], ' +
                'textarea, select'
            );
        }
        
        function saveFormData() {
            if (!form) return;
            
            var data = {};
            var fields = getFormFields();
            
            fields.forEach(function(field) {
                if (field.name && field.value && field.value !== '---------' && field.value !== '') {
                    data[field.name] = field.value;
                }
            });
            
            // Save TinyMCE/rich text editor content
            if (typeof tinymce !== 'undefined' && tinymce.editors && tinymce.editors.length > 0) {
                tinymce.editors.forEach(function(editor) {
                    try {
                        var content = editor.getContent();
                        if (content) {
                            var textarea = document.getElementById(editor.id);
                            if (textarea && textarea.name) {
                                data[textarea.name] = content;
                            }
                            data['_tinymce_' + editor.id] = content;
                        }
                    } catch(e) {}
                });
            }
            
            if (Object.keys(data).length > 0) {
                try {
                    localStorage.setItem(storageKey, JSON.stringify(data));
                    console.log('Form data saved:', Object.keys(data).length, 'fields');
                } catch(e) {
                    console.log('localStorage error:', e);
                }
            }
        }
        
        function restoreFormData() {
            var saved = null;
            try {
                saved = localStorage.getItem(storageKey);
            } catch(e) {
                return;
            }
            
            if (!saved) {
                console.log('No saved form data found');
                return;
            }
            
            console.log('Restoring form data...');
            
            try {
                var data = JSON.parse(saved);
                
                // Restore regular fields immediately
                Object.keys(data).forEach(function(name) {
                    if (name.indexOf('_tinymce_') === 0) return;
                    
                    var field = form.querySelector('[name="' + name + '"]');
                    if (field && field.type !== 'hidden' && field.type !== 'file') {
                        if (!field.value || field.value === '---------' || field.value === '') {
                            field.value = data[name];
                            console.log('Restored field:', name);
                        }
                    }
                });
                
                // Restore TinyMCE with retry
                var tinymceAttempts = 0;
                var maxAttempts = 20; // Try for 10 seconds
                
                function restoreTinyMCE() {
                    tinymceAttempts++;
                    
                    if (typeof tinymce === 'undefined' || !tinymce.editors || tinymce.editors.length === 0) {
                        if (tinymceAttempts < maxAttempts) {
                            setTimeout(restoreTinyMCE, 500);
                        }
                        return;
                    }
                    
                    tinymce.editors.forEach(function(editor) {
                        // Wait for editor to be fully initialized
                        if (!editor.initialized) {
                            editor.on('init', function() {
                                restoreEditorContent(editor, data);
                            });
                        } else {
                            restoreEditorContent(editor, data);
                        }
                    });
                }
                
                function restoreEditorContent(editor, data) {
                    try {
                        var content = data['_tinymce_' + editor.id];
                        if (!content) {
                            var textarea = document.getElementById(editor.id);
                            if (textarea && textarea.name) {
                                content = data[textarea.name];
                            }
                        }
                        
                        if (content && !editor.getContent()) {
                            editor.setContent(content);
                            console.log('Restored TinyMCE content for:', editor.id);
                        }
                    } catch(e) {
                        console.log('TinyMCE restore error:', e);
                    }
                }
                
                restoreTinyMCE();
                
            } catch(e) {
                console.log('Form restore error:', e);
            }
        }
        
        function clearFormData() {
            try {
                localStorage.removeItem(storageKey);
                console.log('Form data cleared');
            } catch(e) {}
        }
        
        function initAutosave() {
            form = document.querySelector('form[method="post"]');
            if (!form) {
                console.log('No form found for autosave');
                return;
            }
            
            console.log('Initializing autosave for:', storageKey);
            
            // Restore saved data
            restoreFormData();
            
            // Save on input/change
            form.addEventListener('input', function() {
                setTimeout(saveFormData, 100);
            });
            form.addEventListener('change', function() {
                setTimeout(saveFormData, 100);
            });
            
            // Periodic save every 2 seconds (catches TinyMCE and other dynamic changes)
            saveInterval = setInterval(saveFormData, 2000);
            
            // Clear on successful submit
            form.addEventListener('submit', function() {
                clearFormData();
                if (saveInterval) {
                    clearInterval(saveInterval);
                }
            });
        }
        
        // Initialize when DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initAutosave);
        } else {
            initAutosave();
        }
    })();
    </script>

{% endblock %}