{% load i18n %}
{{ form.media }}
    <div class="row">

<div class="container-fluid">

        <div class="col-12">
             {% if messages %}
                <ul class="messages">
                    {% for message in messages %}
                        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
                            {{ message }}
                        </li>
                    {% endfor %}
                </ul>
             {% endif %}
            <div class="card">

                <div class="card-body">
                    <form hx-boost="true" method="post" id="email-compose-form" action="{% url 'compose_candidate_email' job.slug %}"
                        hx-include="#candidate-form"
                        hx-target="#messageContent"
                        hx-select="#messageContent"
                        hx-push-url="false"
                        hx-swap="outerHTML"
                        hx-on::after-request="new bootstrap.Modal('#emailModal')).hide()">
                        {% csrf_token %}
                         <!-- Recipients Field -->
                        <!-- Recipients Field -->
                        <div class="mb-3">
                            <label class="form-label fw-bold">
                                {% trans "To" %}
                            </label>
                            <div class="border rounded p-3 bg-light" style="max-height: 200px; overflow-y: auto;">
                                {% for choice in form.to %}
                                    <div class="form-check mb-2">
                                        {{ choice }}
                                    </div>
                                {% endfor %}
                            </div>
                            {% if form.to.errors %}
                                <div class="text-danger small mt-1">
                                    {% for error in form.to.errors %}
                                        <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>


                        <!-- Subject Field -->
                        <div class="mb-3">
                            <label for="{{ form.subject.id_for_label }}" class="form-label fw-bold">
                                {% trans "Subject" %}
                            </label>
                            {{ form.subject }}
                            {% if form.subject.errors %}
                                <div class="text-danger small mt-1">
                                    {% for error in form.subject.errors %}
                                        <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>



                        <!-- Message Field -->
                        <div class="mb-3">
                            <label for="{{ form.message.id_for_label }}" class="form-label fw-bold">
                                {% trans "Message" %}
                            </label>
                            {{ form.message }}
                            {% if form.message.errors %}
                                <div class="text-danger small mt-1">
                                    {% for error in form.message.errors %}
                                        <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>

                        <!-- Form Actions -->
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="text-muted small">
                                <i class="fas fa-info-circle me-1"></i>
                                {% trans "Email will be sent to all selected recipients" %}
                            </div>
                            <div>
                                <button type="button"
                                        class="btn btn-secondary me-2"
                                        data-bs-dismiss="modal">
                                    <i class="fas fa-times me-1"></i>
                                    {% trans "Cancel" %}
                                </button>
                                <button type="submit"
                                        class="btn btn-primary"
                                        id="send-email-btn">
                                    <i class="fas fa-paper-plane me-1"></i>
                                    {% trans "Send Email" %}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="email-loading-overlay" class="d-none">
        <div class="d-flex justify-content-center align-items-center" style="min-height: 200px;">
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">{% trans "Loading..." %}</span>
                </div>
                <div class="mt-2">
                    {% trans "Sending email..." %}
                </div>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages Container -->
    <div id="email-messages-container"></div>
</div>

<style>
.card {
    border: none;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    border-radius: 8px;
}

.card-header {
    border-radius: 8px 8px 0 0 !important;
    border-bottom: none;
}

.form-control:focus {
    border-color: #00636e;
    box-shadow: 0 0 0 0.2rem rgba(0,99,110,0.25);
}

.btn-primary {
    background-color: #00636e;
    border-color: #00636e;
}

.btn-primary:hover {
    background-color: #004a53;
    border-color: #004a53;
}

.form-check-input:checked {
    background-color: #00636e;
    border-color: #00636e;
}

.border {
    border-color: #dee2e6 !important;
}

.bg-light {
    background-color: #f8f9fa !important;
}

.text-danger {
    color: #dc3545 !important;
}

.spinner-border {
    width: 3rem;
    height: 3rem;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('email-compose-form1');
    const sendBtn = document.getElementById('send-email-btn1');
    const loadingOverlay = document.getElementById('email-loading-overlay');
    const messagesContainer = document.getElementById('email-messages-container');

    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            // Show loading state
            if (sendBtn) {
                sendBtn.disabled = true;
                sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> {% trans "Sending..." %}';
            }

            if (loadingOverlay) {
                loadingOverlay.classList.remove('d-none');
            }

            // Clear previous messages
            if (messagesContainer) {
                messagesContainer.innerHTML = '';
            }

            // Submit form via fetch
            const formData = new FormData(form);

            fetch(form.action || window.location.href, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'HX-Request': 'true'
                }
            })
            .then(response => response.json())
            .then(data => {
                // Hide loading state
                if (sendBtn) {
                    sendBtn.disabled = false;
                    sendBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i> {% trans "Send Email" %}';
                }

                if (loadingOverlay) {
                    loadingOverlay.classList.add('d-none');
                }

                // Show result message
                if (data.success) {
                    showMessage(data.message || 'Email sent successfully!', 'success');

                    // Close modal after a short delay
                    setTimeout(() => {
                        const modal = form.closest('.modal');
                        if (modal) {
                            const bootstrapModal = bootstrap.Modal.getInstance(modal);
                            if (bootstrapModal) {
                                bootstrapModal.hide();
                            }
                        }
                    }, 1500);
                } else {
                    showMessage(data.error || 'Failed to send email. Please try again.', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);

                // Hide loading state
                if (sendBtn) {
                    sendBtn.disabled = false;
                    sendBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i> {% trans "Send Email" %}';
                }

                if (loadingOverlay) {
                    loadingOverlay.classList.add('d-none');
                }

                showMessage('An error occurred while sending the email. Please try again.', 'danger');
            });
        });
    }

    function showMessage(message, type) {
        if (!messagesContainer) return;

        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle';

        const messageHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                <i class="fas ${icon} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;

        messagesContainer.innerHTML = messageHtml;

        // Auto-hide success messages after 5 seconds
        if (type === 'success') {
            setTimeout(() => {
                const alert = messagesContainer.querySelector('.alert');
                if (alert) {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }
            }, 5000);
        }
    }

    // Form validation
    function validateForm() {
        let isValid = true;
        const subject = form.querySelector('#{{ form.subject.id_for_label }}');
        const message = form.querySelector('#{{ form.message.id_for_label }}');
        const recipients = form.querySelectorAll('input[name="{{ form.recipients.name }}"]:checked');

        // Clear previous validation states
        form.querySelectorAll('.is-invalid').forEach(field => {
            field.classList.remove('is-invalid');
        });
        form.querySelectorAll('.invalid-feedback').forEach(feedback => {
            feedback.remove();
        });

        // Validate subject
        if (!subject || !subject.value.trim()) {
            showFieldError(subject, 'Subject is required');
            isValid = false;
        }

        // Validate message
        if (!message || !message.value.trim()) {
            showFieldError(message, 'Message is required');
            isValid = false;
        }

        // Validate recipients
        if (recipients.length === 0) {
            const recipientsContainer = form.querySelector('.border.rounded.p-3.bg-light');
            if (recipientsContainer) {
                recipientsContainer.classList.add('border-danger');
                showFieldError(recipientsContainer, 'Please select at least one recipient');
            }
            isValid = false;
        }

        return isValid;
    }

    function showFieldError(field, message) {
        if (!field) return;

        field.classList.add('is-invalid');

        const feedback = document.createElement('div');
        feedback.className = 'invalid-feedback';
        feedback.textContent = message;

        if (field.classList.contains('border')) {
            // For container elements (like recipients)
            field.parentNode.appendChild(feedback);
        } else {
            // For form fields
            field.parentNode.appendChild(feedback);
        }
    }

    // Character counter for message field
    function setupCharacterCounter() {
        const messageField = form.querySelector('#{{ form.message.id_for_label }}');
        if (!messageField) return;

        const counter = document.createElement('div');
        counter.className = 'text-muted small mt-1';
        counter.id = 'message-counter';

        messageField.parentNode.appendChild(counter);

        function updateCounter() {
            const length = messageField.value.length;
            const maxLength = 5000; // Adjust as needed
            counter.textContent = `${length} / ${maxLength} characters`;

            if (length > maxLength * 0.9) {
                counter.classList.add('text-warning');
                counter.classList.remove('text-muted');
            } else {
                counter.classList.remove('text-warning');
                counter.classList.add('text-muted');
            }
        }

        messageField.addEventListener('input', updateCounter);
        updateCounter(); // Initial count
    }

    // Auto-save functionality
    let autoSaveTimer;
    function setupAutoSave() {
        const subject = form.querySelector('#{{ form.subject.id_for_label }}');
        const message = form.querySelector('#{{ form.message.id_for_label }}');

        if (!subject || !message) return;

        function saveDraft() {
            const draftData = {
                subject: subject.value,
                message: message.value,
                recipients: Array.from(form.querySelectorAll('input[name="{{ form.recipients.name }}"]:checked')).map(cb => cb.value),
                include_candidate_info: form.querySelector('#{{ form.include_candidate_info.id_for_label }}').checked,
                include_meeting_details: form.querySelector('#{{ form.include_meeting_details.id_for_label }}').checked
            };

            localStorage.setItem('email_draft_' + window.location.pathname, JSON.stringify(draftData));
        }

        function autoSave() {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(saveDraft, 2000); // Save after 2 seconds of inactivity
        }

        [subject, message].forEach(field => {
            field.addEventListener('input', autoSave);
        });

        form.addEventListener('change', autoSave);
    }

    function loadDraft() {
        const draftData = localStorage.getItem('email_draft_' + window.location.pathname);
        if (!draftData) return;

        try {
            const draft = JSON.parse(draftData);

            const subject = form.querySelector('#{{ form.subject.id_for_label }}');
            const message = form.querySelector('#{{ form.message.id_for_label }}');

            if (subject && draft.subject) subject.value = draft.subject;
            if (message && draft.message) message.value = draft.message;

            // Restore recipients
            if (draft.recipients) {
                form.querySelectorAll('input[name="{{ form.recipients.name }}"]').forEach(cb => {
                    cb.checked = draft.recipients.includes(cb.value);
                });
            }

            // Restore checkboxes
            if (draft.include_candidate_info) {
                form.querySelector('#{{ form.include_candidate_info.id_for_label }}').checked = draft.include_candidate_info;
            }
            if (draft.include_meeting_details) {
                form.querySelector('#{{ form.include_meeting_details.id_for_label }}').checked = draft.include_meeting_details;
            }

            // Show draft restored notification
            showMessage('Draft restored from local storage', 'success');
        } catch (e) {
            console.error('Error loading draft:', e);
        }
    }

    function clearDraft() {
        localStorage.removeItem('email_draft_' + window.location.pathname);
    }

    // Initialize form enhancements
    setupCharacterCounter();
    setupAutoSave();

    // Load draft on page load
    setTimeout(loadDraft, 100);

    // Clear draft on successful submission
    const originalSubmitHandler = form.onsubmit;
    form.addEventListener('submit', function(e) {
        const isValid = validateForm();
        if (!isValid) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        // Clear draft on successful submission
        setTimeout(clearDraft, 2000);
    });

    // Add keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + Enter to submit
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
            const activeElement = document.activeElement;
            if (activeElement && (activeElement.tagName === 'TEXTAREA' || activeElement.tagName === 'INPUT')) {
                form.dispatchEvent(new Event('submit'));
            }
        }

        // Escape to cancel/close modal
        if (e.key === 'Escape') {
            const modal = form.closest('.modal');
            if (modal) {
                const bootstrapModal = bootstrap.Modal.getInstance(modal);
                if (bootstrapModal) {
                    bootstrapModal.hide();
                }
            }
        }
    });

    console.log('Email compose form initialized');
});
