{% extends "layout.html" %}

{% block content %}
<!-- JSON Editor Modal -->
<div class="modal fade" id="jsonEditorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit JSON — {{ detailer.name }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <ul class="nav nav-tabs mb-3" role="tablist">
                    <li class="nav-item"><button class="nav-link active" id="json-simple-tab" type="button">Simple</button></li>
                    <li class="nav-item"><button class="nav-link" id="json-advanced-tab" type="button">Advanced JSON</button></li>
                </ul>
                <div id="json-editor-error" class="alert alert-danger d-none"></div>
                <div id="json-simple-panel"></div>
                <div id="json-advanced-panel" class="d-none">
                    <textarea id="json-editor-textarea" class="form-control font-monospace" rows="20" spellcheck="false"></textarea>
                </div>
                <script type="application/json" id="json-raw-data">{{ detailer.data | tojson }}</script>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="json-save-btn">Save</button>
            </div>
        </div>
    </div>
</div>

{% macro selection_checkbox(section, key, label, value) %}
<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 detailer.default_fields is not none %}
    {% if section + '::' + key in detailer.default_fields %}checked{% endif %}
{% else %}
    {% if value %}checked{% endif %}
{% endif %}>
{% endmacro %}

<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;" onclick="openGallery([this.querySelector('img') ? this.querySelector('img').src : this.src || ''], 0)">
                {% if detailer.image_path %}
                <img src="{{ url_for('static', filename='uploads/' + detailer.image_path) }}" alt="{{ detailer.name }}" class="img-fluid" data-preview-path="{{ detailer.image_path }}">
                {% else %}
                <div class="d-flex align-items-center justify-content-center bg-light" style="height: 400px;">
                    <span class="text-muted">No Image Attached</span>
                </div>
                {% endif %}
            </div>
            <div class="card-body">
                {# Character Selector #}
                <div class="mb-3">
                    <label for="character_select" class="form-label">Preview with Character</label>
                    <select class="form-select" id="character_select" name="character_slug" form="generate-form">
                        <option value="">-- No Character (Detailer Only) --</option>
                        <option value="__random__" {% if selected_character == '__random__' or not selected_character %}selected{% endif %}>🎲 Random Character</option>
                        {% for char in characters %}
                        <option value="{{ char.slug }}" {% if selected_character == char.slug %}selected{% endif %}>{{ char.name }}</option>
                        {% endfor %}
                    </select>
                </div>

                {# Action Selector #}
                <div class="mb-3">
                    <label for="action_select" class="form-label">Action / Pose LoRA</label>
                    <select class="form-select" id="action_select" name="action_slug" form="generate-form">
                        <option value="">-- No Action --</option>
                        {% for act in actions %}
                        <option value="{{ act.slug }}" {% if selected_action == act.slug %}selected{% endif %}>{{ act.name }}</option>
                        {% endfor %}
                    </select>
                </div>

                {# Additional Prompts #}
                <div class="mb-2">
                    <label for="extra_positive" class="form-label">Additional Positive</label>
                    <textarea class="form-control form-control-sm font-monospace" id="extra_positive" name="extra_positive" rows="2" placeholder="e.g. masterpiece, best quality" form="generate-form">{{ extra_positive or '' }}</textarea>
                </div>
                <div class="mb-3">
                    <label for="extra_negative" class="form-label">Additional Negative</label>
                    <textarea class="form-control form-control-sm font-monospace" id="extra_negative" name="extra_negative" rows="2" placeholder="e.g. blurry, low quality" form="generate-form">{{ extra_negative or '' }}</textarea>
                </div>

                <div class="d-grid gap-2">
                    <div class="input-group input-group-sm mb-1">
                        <span class="input-group-text">Seed</span>
                        <input type="number" class="form-control" id="seed-input" name="seed" form="generate-form" placeholder="Random" min="1" step="1">
                        <button type="button" class="btn btn-outline-secondary" id="seed-clear-btn" title="Clear (random)">&times;</button>
                    </div>
                    <button type="submit" name="action" value="preview" class="btn btn-success" form="generate-form" data-requires="comfyui">Generate Preview</button>
                    <button type="button" class="btn btn-outline-info" id="endless-btn" onclick="window._endlessStart()" data-requires="comfyui">Endless</button>
                    <button type="button" class="btn btn-danger d-none" id="endless-stop-btn" onclick="window._endlessStop()">Stop Endless</button>
                    <small class="text-muted d-none" id="endless-counter"></small>
                    <button type="submit" form="generate-form" formaction="{{ url_for('save_detailer_defaults', slug=detailer.slug) }}" class="btn btn-sm btn-outline-secondary mt-2">Save Selection as Default</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>

        <div class="card mb-4 {% if preview_image %}border-success{% else %}border-secondary d-none{% endif %}" id="preview-card">
            <div class="card-header {% if preview_image %}bg-success{% else %}bg-secondary{% endif %} text-white d-flex justify-content-between align-items-center p-2" id="preview-card-header">
                <small>Selected Preview</small>
                <form action="{{ url_for('replace_detailer_cover_from_preview', slug=detailer.slug) }}" method="post" class="m-0" id="replace-cover-form">
                    <input type="hidden" name="preview_path" id="preview-path" value="{{ preview_image or '' }}">
                    <button type="submit" class="btn btn-sm btn-outline-light" id="replace-cover-btn" {% if not preview_image %}disabled{% endif %}>Replace Cover</button>
                </form>
            </div>
            <div class="card-body p-0">
                <div class="img-container" style="height: auto; min-height: 400px; cursor: pointer;" onclick="openGallery([this.querySelector('img') ? this.querySelector('img').src : this.src || ''], 0)">
                    <img id="preview-img" src="{{ url_for('static', filename='uploads/' + preview_image) if preview_image else '' }}" alt="Preview" class="img-fluid">
                </div>
            </div>
        </div>

        {% set tags = detailer.data.tags if detailer.data.tags is mapping else {} %}
        {% if tags %}
        <div class="card mb-4">
            <div class="card-header bg-dark text-white"><span>Tags</span></div>
            <div class="card-body">
                {% if tags.associated_resource %}<span class="badge bg-info">{{ tags.associated_resource }}</span>{% endif %}
                {% if tags.adetailer_targets %}<span class="badge bg-primary">{{ tags.adetailer_targets | join(', ') }}</span>{% endif %}
                {% if detailer.is_nsfw %}<span class="badge bg-danger">NSFW</span>{% endif %}
                {% if detailer.is_favourite %}<span class="badge bg-warning text-dark">&#9733; Favourite</span>{% endif %}
            </div>
        </div>
        {% endif %}
    </div>

    <div class="col-md-8">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h1 class="mb-0">
                    {{ detailer.name }}
                    <button class="btn btn-sm btn-link text-decoration-none fav-toggle-btn" data-url="/detailer/{{ detailer.slug }}/favourite" title="Toggle favourite">
                        <span style="font-size:1.2rem;">{% if detailer.is_favourite %}&#9733;{% else %}&#9734;{% endif %}</span>
                    </button>
                    {% if detailer.is_nsfw %}<span class="badge bg-danger" style="font-size:0.6rem;vertical-align:middle;">NSFW</span>{% endif %}
                </h1>
                <div class="mt-1">
                    <a href="{{ url_for('edit_detailer', slug=detailer.slug) }}" class="btn btn-sm btn-link text-decoration-none ps-0">Edit Detailer</a>
                </div>
            </div>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#jsonEditorModal">Edit JSON</button>
                <button type="button" class="btn btn-outline-warning" id="regenerate-tags-btn" onclick="regenerateTags('detailers', '{{ detailer.slug }}')">Regenerate Tags</button>
                <a href="{{ url_for('transfer_resource', category='detailers', slug=detailer.slug) }}" class="btn btn-outline-primary">Transfer</a>
                <a href="{{ url_for('detailers_index') }}" class="btn btn-outline-secondary">Back to Library</a>
            </div>
        </div>

        <ul class="nav nav-tabs mb-4" id="detailTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="settings-tab" data-bs-toggle="tab" data-bs-target="#settings-pane" type="button" role="tab">Settings</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="previews-tab" data-bs-toggle="tab" data-bs-target="#previews-pane" type="button" role="tab">
                    Previews{% if existing_previews %} <span class="badge bg-secondary">{{ existing_previews|length }}</span>{% endif %}
                </button>
            </li>
            {% if detailer.data.get('lora', {}).get('lora_name', '') != '' %}
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="strengths-tab" data-bs-toggle="tab" data-bs-target="#strengths-pane" type="button" role="tab">Strengths</button>
            </li>
            {% endif %}
        </ul>

        <div class="tab-content" id="detailTabContent">
            <div class="tab-pane fade show active" id="settings-pane" role="tabpanel">
                <form id="generate-form" action="{{ url_for('generate_detailer_image', slug=detailer.slug) }}" method="post">
                    {# Detailer definition section #}
                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <strong>Detailer Definition</strong>
                        </div>
                        <div class="card-body">
                            <dl class="row mb-0">
                                <dt class="col-sm-4 text-capitalize">
                                    {{ selection_checkbox('special', 'tags', 'Prompt', detailer.data.prompt) }}
                                    Prompt
                                </dt>
                                <dd class="col-sm-8">{{ detailer.data.prompt if detailer.data.prompt else '--' }}</dd>
                            </dl>
                        </div>
                    </div>

                    {# Character Identity/Wardrobe context when character is selected #}
                    <div id="character-context" class="{% if not selected_character or selected_character == '__random__' %}d-none{% endif %}">
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> When a character is selected, their identity and active wardrobe fields will be automatically included.
                        </div>
                    </div>

                    {# LoRA section #}
                    {% set lora = detailer.data.get('lora', {}) %}
                    <div class="card mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <strong>LoRA Integration</strong>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="include_field" value="lora::lora_triggers" id="includeLora"
                                {% if preferences is not none %}
                                    {% if 'lora::lora_triggers' in preferences %}checked{% endif %}
                                {% elif detailer.default_fields is not none %}
                                    {% if 'lora::lora_triggers' in detailer.default_fields %}checked{% endif %}
                                {% else %}
                                    checked
                                {% endif %}>
                                <label class="form-check-label small" for="includeLora">Include Triggers</label>
                            </div>
                        </div>
                        <div class="card-body">
                            <dl class="row mb-0">
                                <dt class="col-sm-4">LoRA Name</dt>
                                <dd class="col-sm-8 text-muted small">{{ lora.get('lora_name') if lora.get('lora_name') else '--' }}</dd>

                                <dt class="col-sm-4">Weight</dt>
                                <dd class="col-sm-8">{{ lora.get('lora_weight', 1.0) }}</dd>

                                <dt class="col-sm-4">Triggers</dt>
                                <dd class="col-sm-8 small"><code>{{ lora.get('lora_triggers') if lora.get('lora_triggers') else '--' }}</code></dd>
                            </dl>
                        </div>
                    </div>
                </form>
            </div>

            <div class="tab-pane fade" id="previews-pane" role="tabpanel">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span class="text-muted small">{{ existing_previews|length }} preview(s)</span>
                    <div class="d-flex gap-2">
                        <button type="button" id="generate-all-btn" class="btn btn-primary btn-sm" data-requires="comfyui">Generate All Characters</button>
                        <button type="button" id="stop-all-btn" class="btn btn-danger btn-sm d-none">Stop</button>
                    </div>
                </div>
                <div id="batch-progress" class="mb-3 d-none">
                    <label id="batch-label" class="form-label small fw-semibold"></label>
                    <div class="progress" style="height: 8px;">
                        <div id="batch-bar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
                    </div>
                </div>
                <div id="preview-gallery" class="row row-cols-2 row-cols-md-3 g-2">
                    {% for img in existing_previews %}
                    <div class="col">
                        <img src="{{ url_for('static', filename='uploads/' + img) }}"
                             class="img-fluid rounded"
                             style="cursor: pointer; aspect-ratio: 1; object-fit: cover; width: 100%;"
                             onclick="openGallery([this.querySelector('img') ? this.querySelector('img').src : this.src || ''], 0)"
                             
                             data-preview-path="{{ img }}">
                    </div>
                    {% else %}
                    <div class="col-12 text-muted small" id="gallery-empty">No previews yet. Generate some!</div>
                    {% endfor %}
                </div>
            </div>

            {% set sg_has_lora = detailer.data.get('lora', {}).get('lora_name', '') != '' %}
            {% if sg_has_lora %}
            <div class="tab-pane fade" id="strengths-pane" role="tabpanel">
                {% set sg_entity = detailer %}
                {% set sg_category = 'detailers' %}
                {% include 'partials/strengths_gallery.html' %}
            </div>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="/static/js/detail-common.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    initDetailPage({
        batchItems: [{% for char in characters %}{ slug: "{{ char.slug }}", name: {{ char.name | tojson }} },{% endfor %}],
        jsonEditorUrl: '{{ url_for("save_detailer_json", slug=detailer.slug) }}'
    });
});
</script>
{% endblock %}
