{% extends "layout.html" %}

{% block content %}
<!-- Image Modal -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content bg-transparent border-0">
            <div class="modal-body p-0 text-center">
                <img id="modalImage" src="" alt="Enlarged Image" class="img-fluid" style="max-height: 90vh;">
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="img-container" style="height: auto; min-height: 400px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#imageModal" onclick="showImage(this.querySelector('img').src)">
                {% if character.image_path %}
                <img src="{{ url_for('static', filename='uploads/' + character.image_path) }}" alt="{{ character.name }}" class="img-fluid">
                {% else %}
                <span class="text-muted">No Image Attached</span>
                {% endif %}
            </div>
            <div class="card-body">
                <form action="{{ url_for('upload_image', slug=character.slug) }}" method="post" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="image" class="form-label">Update Image</label>
                        <input class="form-control" type="file" id="image" name="image" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 mb-2">Upload</button>
                </form>
                <div class="d-grid gap-2">
                    <button type="submit" name="action" value="preview" class="btn btn-success" form="generate-form">Generate Preview</button>
                    <button type="submit" form="generate-form" formaction="{{ url_for('save_defaults', slug=character.slug) }}" class="btn btn-sm btn-outline-secondary mt-2">Save as Default Selection</button>
                </div>
            </div>
        </div>

        <div id="progress-container" class="mb-4 d-none">
            <label id="progress-label" class="form-label">Generating...</label>
            <div class="progress" role="progressbar" aria-label="Generation Progress" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                <div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%">0%</div>
            </div>
        </div>

        {% if preview_image %}
        <div class="card mb-4 border-success">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <span>Latest Preview</span>
                <form action="{{ url_for('replace_cover_from_preview', slug=character.slug) }}" method="post" class="m-0">
                    <button type="submit" class="btn btn-sm btn-outline-light">Replace Cover</button>
                </form>
            </div>
            <div class="card-body p-0">
                <div class="img-container" style="height: auto; min-height: 400px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#imageModal" onclick="showImage(this.querySelector('img').src)">
                    <img id="preview-img" src="{{ url_for('static', filename='uploads/' + preview_image) }}" alt="Preview" class="img-fluid">
                </div>
            </div>
        </div>
        {% else %}
        <div class="card mb-4 border-secondary d-none" id="preview-card">
            <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                <span>Latest Preview</span>
                <form action="{{ url_for('replace_cover_from_preview', slug=character.slug) }}" method="post" class="m-0" id="replace-cover-form">
                    <button type="submit" class="btn btn-sm btn-outline-light" id="replace-cover-btn" disabled>Replace Cover</button>
                </form>
            </div>
            <div class="card-body p-0">
                <div class="img-container" style="height: auto; min-height: 400px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#imageModal" onclick="showImage(this.querySelector('img').src)">
                    <img id="preview-img" src="" alt="Preview" class="img-fluid">
                </div>
            </div>
        </div>
        {% endif %}
        
        <div class="card mb-4">
            <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                <span>Tags</span>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" name="include_field" value="special::tags" id="includeTags" form="generate-form" 
                    {% if preferences is not none %}
                        {% if 'special::tags' in preferences %}checked{% endif %}
                    {% elif character.default_fields is not none %}
                        {% if 'special::tags' in character.default_fields %}checked{% endif %}
                    {% else %}
                        checked
                    {% endif %}>
                    <label class="form-check-label text-white small" for="includeTags">Include</label>
                </div>
            </div>
            <div class="card-body">
                {% for tag in character.data.tags %}
                <span class="badge bg-secondary">{{ tag }}</span>
                {% endfor %}
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="mb-0">{{ character.name }}</h1>
                <a href="{{ url_for('edit_character', slug=character.slug) }}" class="btn btn-sm btn-link text-decoration-none">Edit Profile</a>
            </div>
            <a href="/" class="btn btn-outline-secondary">Back to Gallery</a>
        </div>

        <!-- Outfit Switcher -->
        {% set outfits = character.get_available_outfits() %}
        {% if outfits|length > 1 %}
        <div class="card mb-4 border-primary">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <span><i class="bi bi-shirt"></i> Active Outfit</span>
                <span class="badge bg-light text-primary">{{ character.active_outfit or 'default' }}</span>
            </div>
            <div class="card-body">
                <form action="{{ url_for('switch_outfit', slug=character.slug) }}" method="post" class="row g-2">
                    <div class="col-auto flex-grow-1">
                        <select name="outfit" class="form-select" id="outfit-select">
                            {% for outfit in outfits %}
                            <option value="{{ outfit }}" {% if outfit == character.active_outfit %}selected{% endif %}>
                                {{ outfit }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-primary">Switch</button>
                    </div>
                </form>
            </div>
        </div>
        {% endif %}

        <form id="generate-form" action="{{ url_for('generate_image', slug=character.slug) }}" method="post">
            {% for section, details in character.data.items() %}
                {% if section == 'wardrobe' %}
                    {# Special handling for wardrobe - show active outfit #}
                    {% set active_wardrobe = character.get_active_wardrobe() %}
                    <div class="card mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <strong>
                                Wardrobe
                                {% if outfits|length > 1 %}
                                <span class="badge bg-secondary ms-2">{{ character.active_outfit or 'default' }}</span>
                                {% endif %}
                            </strong>
                            {% if outfits|length > 1 %}
                            <a href="{{ url_for('edit_character', slug=character.slug) }}#outfits" class="btn btn-sm btn-outline-secondary">Manage Outfits</a>
                            {% endif %}
                        </div>
                        <div class="card-body">
                            <dl class="row mb-0">
                                {% for key, value in active_wardrobe.items() %}
                                <dt class="col-sm-4 text-capitalize">
                                    <input class="form-check-input me-1" type="checkbox" name="include_field" value="wardrobe::{{ key }}" 
                                    {% if preferences is not none %}
                                        {% if 'wardrobe::' + key in preferences %}checked{% endif %}
                                    {% elif character.default_fields is not none %}
                                        {% if 'wardrobe::' + key in character.default_fields %}checked{% endif %}
                                    {% else %}
                                        {% if value %}checked{% endif %}
                                    {% endif %}>
                                    {{ key.replace('_', ' ') }}
                                </dt>
                                <dd class="col-sm-8">{{ value if value else '--' }}</dd>
                                {% endfor %}
                            </dl>
                        </div>
                    </div>
                {% elif section not in ['character_id', 'tags', 'name'] and details is mapping %}
                <div class="card mb-4">
                    <div class="card-header bg-light text-capitalize"><strong>{{ section.replace('_', ' ') }}</strong></div>
                    <div class="card-body">
                        <dl class="row mb-0">
                            {% if section == 'identity' %}
                            <dt class="col-sm-4 text-capitalize">
                                <input class="form-check-input me-1" type="checkbox" name="include_field" value="special::name" 
                                {% if preferences is not none %}
                                    {% if 'special::name' in preferences %}checked{% endif %}
                                {% elif character.default_fields is not none %}
                                    {% if 'special::name' in character.default_fields %}checked{% endif %}
                                {% else %}
                                    checked
                                {% endif %}>
                                Character ID
                            </dt>
                            <dd class="col-sm-8">{{ character.character_id }}</dd>
                            {% endif %}
                            
                            {% for key, value in details.items() %}
                            <dt class="col-sm-4 text-capitalize">
                                <input class="form-check-input me-1" type="checkbox" name="include_field" value="{{ section }}::{{ key }}" 
                                {% if preferences is not none %}
                                    {% if section + '::' + key in preferences %}checked{% endif %}
                                {% elif character.default_fields is not none %}
                                    {% if section + '::' + key in character.default_fields %}checked{% endif %}
                                {% else %}
                                    {% if value %}checked{% endif %}
                                {% endif %}>
                                {{ key.replace('_', ' ') }}
                            </dt>
                            <dd class="col-sm-8">{{ value if value else '--' }}</dd>
                            {% endfor %}
                        </dl>
                    </div>
                </div>
                {% endif %}
            {% endfor %}
        </form>
    </div>
</div>

{% set sg_entity = character %}
{% set sg_category = 'characters' %}
{% set sg_has_lora = character.data.get('lora', {}).get('lora_name', '') != '' %}
{% include 'partials/strengths_gallery.html' %}
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const form = document.getElementById('generate-form');
        const progressBar = document.getElementById('progress-bar');
        const progressContainer = document.getElementById('progress-container');
        const progressLabel = document.getElementById('progress-label');
        const previewCard = document.getElementById('preview-card');
        const previewImg = document.getElementById('preview-img');

        let currentJobId = null;
        let currentAction = null;

        async function waitForJob(jobId) {
            return new Promise((resolve, reject) => {
                const poll = setInterval(async () => {
                    try {
                        const resp = await fetch(`/api/queue/${jobId}/status`);
                        const data = await resp.json();
                        if (data.status === 'done') {
                            clearInterval(poll);
                            resolve(data);
                        } else if (data.status === 'failed' || data.status === 'removed') {
                            clearInterval(poll);
                            reject(new Error(data.error || 'Job failed'));
                        } else if (data.status === 'processing') {
                            progressLabel.textContent = 'Generating…';
                        } else {
                            progressLabel.textContent = 'Queued…';
                        }
                    } catch (err) { console.error('Poll error:', err); }
                }, 1500);
            });
        }

        form.addEventListener('submit', async (e) => {
            // Only intercept generate actions
            const submitter = e.submitter;
            if (!submitter || submitter.value !== 'preview') {
                return;
            }
            
            e.preventDefault();
            
            currentAction = submitter.value;
            const formData = new FormData(form);
            formData.append('action', currentAction);
            
            // UI Reset
            progressContainer.classList.remove('d-none');
            progressBar.style.width = '100%';
            progressBar.textContent = '';
            progressBar.classList.add('progress-bar-striped', 'progress-bar-animated');
            progressLabel.textContent = 'Queuing…';
            
            try {
                const response = await fetch(form.getAttribute('action'), {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                
                const data = await response.json();
                
                if (data.error) {
                    alert('Error: ' + data.error);
                    progressContainer.classList.add('d-none');
                    return;
                }
                
                currentJobId = data.job_id;
                progressLabel.textContent = 'Queued…';

                // Wait for the background worker to finish
                const jobResult = await waitForJob(currentJobId);
                currentJobId = null;

                // Image is already saved — just display it
                if (jobResult.result && jobResult.result.image_url) {
                    previewImg.src = jobResult.result.image_url;
                    if (previewCard) previewCard.classList.remove('d-none');
                    const replaceBtn = document.getElementById('replace-cover-btn');
                    if (replaceBtn) replaceBtn.disabled = false;
                }
                
            } catch (err) {
                console.error(err);
                alert('Generation failed: ' + err.message);
            } finally {
                progressContainer.classList.add('d-none');
                progressBar.classList.remove('progress-bar-striped', 'progress-bar-animated');
            }
        });
    });
    
    // Image modal function
    function showImage(src) {
        document.getElementById('modalImage').src = src;
    }
</script>
{% endblock %}
