{% 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 — {{ ckpt.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">{{ ckpt.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>

<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 ckpt.image_path %}
                <img src="{{ url_for('static', filename='uploads/' + ckpt.image_path) }}" alt="{{ ckpt.name }}" class="img-fluid"
                     data-preview-path="{{ ckpt.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">
                <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 (Generic) --</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>

                {# 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" id="endless-btn" class="btn btn-outline-success" onclick="window._endlessStart()" data-requires="comfyui">Endless</button>
                    <button type="button" id="endless-stop-btn" class="btn btn-danger d-none" onclick="window._endlessStop()">Stop</button>
                    <small id="endless-counter" class="text-muted d-none"></small>
                </div>
            </div>
        </div>

        <div id="progress-container" class="mb-4 d-none">
            <label id="progress-label" class="form-label">Generating...</label>
            <div class="progress">
                <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_checkpoint_cover_from_preview', slug=ckpt.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 = ckpt.data.tags if ckpt.data is mapping and ckpt.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.art_style %}<span class="badge bg-info">{{ tags.art_style }}</span>{% endif %}
                {% if tags.base_model %}<span class="badge bg-primary">{{ tags.base_model }}</span>{% endif %}
                {% if ckpt.is_nsfw %}<span class="badge bg-danger">NSFW</span>{% endif %}
                {% if ckpt.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">
                    {{ ckpt.name }}
                    <button class="btn btn-sm btn-link text-decoration-none fav-toggle-btn" data-url="/checkpoint/{{ ckpt.slug }}/favourite" title="Toggle favourite">
                        <span style="font-size:1.2rem;">{% if ckpt.is_favourite %}&#9733;{% else %}&#9734;{% endif %}</span>
                    </button>
                </h1>
            </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>
                <a href="{{ url_for('checkpoints_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>
        </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_checkpoint_image', slug=ckpt.slug) }}" method="post">
                    {% set d = ckpt.data or {} %}

                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <strong>Checkpoint Info</strong>
                        </div>
                        <div class="card-body">
                            <dl class="row mb-0">
                                <dt class="col-sm-3">Name</dt>
                                <dd class="col-sm-9">{{ ckpt.name }}</dd>

                                <dt class="col-sm-3">Family</dt>
                                <dd class="col-sm-9">{{ ckpt.checkpoint_path.split('/')[0] }}</dd>

                                <dt class="col-sm-3">File</dt>
                                <dd class="col-sm-9 text-muted small">
                                    <code>{{ ckpt.checkpoint_path }}</code>
                                </dd>
                            </dl>
                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <strong>Generation Settings</strong>
                        </div>
                        <div class="card-body">
                            <dl class="row mb-0">
                                <dt class="col-sm-4">Steps</dt>
                                <dd class="col-sm-8">{{ d.get('steps', 25) }}</dd>

                                <dt class="col-sm-4">CFG</dt>
                                <dd class="col-sm-8">{{ d.get('cfg', 5) }}</dd>

                                <dt class="col-sm-4">Sampler</dt>
                                <dd class="col-sm-8"><code>{{ d.get('sampler_name', 'euler_ancestral') }}</code></dd>

                                <dt class="col-sm-4">Scheduler</dt>
                                <dd class="col-sm-8"><code>{{ d.get('scheduler', 'normal') }}</code></dd>

                                <dt class="col-sm-4">VAE</dt>
                                <dd class="col-sm-8">
                                    {% if d.get('vae', 'integrated') == 'integrated' %}
                                    <span class="badge bg-secondary">Integrated</span>
                                    {% else %}
                                    <code class="small">{{ d.get('vae') }}</code>
                                    {% endif %}
                                </dd>
                            </dl>
                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <strong>Base Prompts</strong>
                        </div>
                        <div class="card-body">
                            <dl class="row mb-0">
                                <dt class="col-sm-4">Positive</dt>
                                <dd class="col-sm-8 small"><code>{{ d.get('base_positive', '') or '--' }}</code></dd>

                                <dt class="col-sm-4">Negative</dt>
                                <dd class="col-sm-8 small"><code>{{ d.get('base_negative', '') or '--' }}</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 preview-img"
                             style="cursor: pointer; aspect-ratio: 1; object-fit: cover; width: 100%;"
                             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>
        </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_checkpoint_json", slug=ckpt.slug) }}'
    });
});
</script>
{% endblock %}
