{% extends "layout.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1>Edit Preset: {{ preset.name }}</h1>
    <a href="{{ url_for('preset_detail', slug=preset.slug) }}" class="btn btn-outline-secondary">Cancel</a>
</div>

{% macro toggle_group(name, val) %}
{# 3-way toggle: OFF / RNG / ON — renders as Bootstrap btn-group radio #}
{% set v = val | string | lower %}
<div class="btn-group btn-group-sm toggle-group" role="group" data-field="{{ name }}">
    <input type="radio" class="btn-check" name="{{ name }}" id="{{ name }}_off" value="false" autocomplete="off" {% if v == 'false' %}checked{% endif %}>
    <label class="btn btn-outline-secondary" for="{{ name }}_off">OFF</label>

    <input type="radio" class="btn-check" name="{{ name }}" id="{{ name }}_rng" value="random" autocomplete="off" {% if v == 'random' %}checked{% endif %}>
    <label class="btn btn-outline-warning" for="{{ name }}_rng">RNG</label>

    <input type="radio" class="btn-check" name="{{ name }}" id="{{ name }}_on" value="true" autocomplete="off" {% if v not in ['false', 'random'] %}checked{% endif %}>
    <label class="btn btn-outline-success" for="{{ name }}_on">ON</label>
</div>
{% endmacro %}

{% macro entity_select(name, items, id_attr, current_val, include_random=true) %}
<select class="form-select form-select-sm" name="{{ name }}">
    <option value="">— None —</option>
    {% if include_random %}<option value="random" {% if current_val == 'random' %}selected{% endif %}>🎲 Random</option>{% endif %}
    {% for item in items %}
    {% set item_id = item | attr(id_attr) %}
    <option value="{{ item_id }}" {% if current_val == item_id %}selected{% endif %}>{{ item.name }}</option>
    {% endfor %}
</select>
{% endmacro %}

<form action="{{ url_for('edit_preset', slug=preset.slug) }}" method="post">
{% set d = preset.data %}
{% set char_cfg = d.get('character', {}) %}
{% set char_fields = char_cfg.get('fields', {}) %}
{% set id_fields = char_fields.get('identity', {}) %}
{% set def_fields = char_fields.get('defaults', {}) %}
{% set wd_cfg = char_fields.get('wardrobe', {}) %}
{% set wd_fields = wd_cfg.get('fields', {}) %}

<div class="row">
    <div class="col-md-8">

        <!-- Basic Info -->
        <div class="card mb-4">
            <div class="card-header bg-dark text-white">Basic Information</div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Preset Name</label>
                    <input type="text" class="form-control" name="preset_name" value="{{ preset.name }}" required>
                </div>
                <div class="mb-3">
                    <label class="form-label text-muted small">Preset ID</label>
                    <input type="text" class="form-control form-control-sm" value="{{ preset.preset_id }}" disabled>
                </div>
                <div class="mb-3">
                    <label class="form-label">Extra Tags <span class="text-muted small">(comma-separated)</span></label>
                    <input type="text" class="form-control" name="tags" value="{{ d.get('tags', []) | join(', ') }}">
                </div>
            </div>
        </div>

        <!-- Character -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <strong>Character</strong>
                <div class="form-check form-switch mb-0">
                    <input class="form-check-input" type="checkbox" name="char_use_lora" id="char_use_lora" {% if char_cfg.get('use_lora', true) %}checked{% endif %}>
                    <label class="form-check-label text-white small" for="char_use_lora">Use LoRA</label>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Character</label>
                    {{ entity_select('char_character_id', characters, 'character_id', char_cfg.get('character_id')) }}
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Identity Fields</label>
                    <div class="row g-2">
                        {% for k in ['base','head','upper_body','lower_body','hands','feet','additional'] %}
                        <div class="col-6 col-sm-4 col-md-4">
                            <div class="d-flex justify-content-between align-items-center border rounded p-2">
                                <small>{{ k | replace('_', ' ') }}</small>
                                {{ toggle_group('id_' + k, id_fields.get(k, true)) }}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Default Fields</label>
                    <div class="row g-2">
                        {% for k in ['expression','pose','scene'] %}
                        <div class="col-6 col-sm-4">
                            <div class="d-flex justify-content-between align-items-center border rounded p-2">
                                <small>{{ k }}</small>
                                {{ toggle_group('def_' + k, def_fields.get(k, false)) }}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>

                <div>
                    <label class="form-label fw-semibold">Wardrobe Fields</label>
                    <div class="mb-2">
                        <label class="form-label small text-muted">Active outfit name</label>
                        <input type="text" class="form-control form-control-sm" name="wardrobe_outfit"
                               value="{{ wd_cfg.get('outfit', 'default') }}" placeholder="default">
                    </div>
                    <div class="row g-2">
                        {% for k in ['base','head','upper_body','lower_body','hands','feet','additional'] %}
                        <div class="col-6 col-sm-4">
                            <div class="d-flex justify-content-between align-items-center border rounded p-2">
                                <small>{{ k | replace('_', ' ') }}</small>
                                {{ toggle_group('wd_' + k, wd_fields.get(k, true)) }}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- Action -->
        {% set act = d.get('action', {}) %}
        <div class="card mb-4">
            <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                <strong>Action</strong>
                <div class="form-check form-switch mb-0">
                    <input class="form-check-input" type="checkbox" name="action_use_lora" id="action_use_lora" {% if act.get('use_lora', true) %}checked{% endif %}>
                    <label class="form-check-label text-white small" for="action_use_lora">Use LoRA</label>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Action</label>
                    {{ entity_select('action_id', actions, 'action_id', act.get('action_id')) }}
                </div>
                <label class="form-label fw-semibold">Fields</label>
                <div class="row g-2">
                    {% for k in ['base','head','upper_body','lower_body','hands','feet','additional'] %}
                    <div class="col-6 col-sm-4">
                        <div class="d-flex justify-content-between align-items-center border rounded p-2">
                            <small>{{ k | replace('_', ' ') }}</small>
                            {{ toggle_group('act_' + k, act.get('fields', {}).get(k, true)) }}
                        </div>
                    </div>
                    {% endfor %}
                </div>
                <hr class="my-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="fw-semibold">Suppress Wardrobe</small>
                        <div class="form-text mt-0">Strip all clothing/wardrobe prompts from generation</div>
                    </div>
                    {% set sw = act.get('suppress_wardrobe') %}
                    <select class="form-select form-select-sm" name="act_suppress_wardrobe" style="width:auto">
                        <option value="default" {% if sw is none %}selected{% endif %}>Action default</option>
                        <option value="true" {% if sw == true %}selected{% endif %}>Always</option>
                        <option value="false" {% if sw == false %}selected{% endif %}>Never</option>
                        <option value="random" {% if sw == 'random' %}selected{% endif %}>Random</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Style / Scene / Detailer -->
        <div class="row g-3 mb-4">
            {% set sty = d.get('style', {}) %}
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-header bg-info text-white d-flex justify-content-between align-items-center py-2">
                        <strong>Style</strong>
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" name="style_use_lora" id="style_use_lora" {% if sty.get('use_lora', true) %}checked{% endif %}>
                            <label class="form-check-label text-white" for="style_use_lora" style="font-size:0.75rem">LoRA</label>
                        </div>
                    </div>
                    <div class="card-body">
                        {{ entity_select('style_id', styles, 'style_id', sty.get('style_id')) }}
                    </div>
                </div>
            </div>

            {% set det = d.get('detailer', {}) %}
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-header bg-info text-white d-flex justify-content-between align-items-center py-2">
                        <strong>Detailer</strong>
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" name="detailer_use_lora" id="detailer_use_lora" {% if det.get('use_lora', true) %}checked{% endif %}>
                            <label class="form-check-label text-white" for="detailer_use_lora" style="font-size:0.75rem">LoRA</label>
                        </div>
                    </div>
                    <div class="card-body">
                        {{ entity_select('detailer_id', detailers, 'detailer_id', det.get('detailer_id')) }}
                    </div>
                </div>
            </div>

            {% set lk = d.get('look', {}) %}
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-header bg-warning text-dark py-2"><strong>Look</strong> <small class="text-muted">(overrides char LoRA)</small></div>
                    <div class="card-body">
                        {{ entity_select('look_id', looks, 'look_id', lk.get('look_id')) }}
                    </div>
                </div>
            </div>
        </div>

        <!-- Scene -->
        {% set scn = d.get('scene', {}) %}
        <div class="card mb-4">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <strong>Scene</strong>
                <div class="form-check form-switch mb-0">
                    <input class="form-check-input" type="checkbox" name="scene_use_lora" id="scene_use_lora" {% if scn.get('use_lora', true) %}checked{% endif %}>
                    <label class="form-check-label text-white small" for="scene_use_lora">Use LoRA</label>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Scene</label>
                    {{ entity_select('scene_id', scenes, 'scene_id', scn.get('scene_id')) }}
                </div>
                <label class="form-label fw-semibold">Fields</label>
                <div class="row g-2">
                    {% for k in ['background','foreground','furniture','colors','lighting','theme'] %}
                    <div class="col-6 col-sm-4">
                        <div class="d-flex justify-content-between align-items-center border rounded p-2">
                            <small>{{ k }}</small>
                            {{ toggle_group('scn_' + k, scn.get('fields', {}).get(k, true)) }}
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- Outfit + Checkpoint -->
        <div class="row g-3 mb-4">
            {% set out = d.get('outfit', {}) %}
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center py-2">
                        <strong>Outfit</strong>
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" name="outfit_use_lora" id="outfit_use_lora" {% if out.get('use_lora', true) %}checked{% endif %}>
                            <label class="form-check-label text-white" for="outfit_use_lora" style="font-size:0.75rem">LoRA</label>
                        </div>
                    </div>
                    <div class="card-body">
                        {{ entity_select('outfit_id', outfits, 'outfit_id', out.get('outfit_id')) }}
                        <small class="text-muted">Selecting an outfit overrides the character's wardrobe.</small>
                    </div>
                </div>
            </div>

            {% set ckpt = d.get('checkpoint', {}) %}
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-header py-2"><strong>Checkpoint</strong></div>
                    <div class="card-body">
                        <select class="form-select form-select-sm" name="checkpoint_path">
                            <option value="">— Use session default —</option>
                            <option value="random" {% if ckpt.get('checkpoint_path') == 'random' %}selected{% endif %}>🎲 Random</option>
                            {% for ck in checkpoints %}
                            <option value="{{ ck.checkpoint_path }}" {% if ckpt.get('checkpoint_path') == ck.checkpoint_path %}selected{% endif %}>{{ ck.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <!-- Resolution -->
        {% set res = d.get('resolution', {}) %}
        <div class="card mb-4">
            <div class="card-header py-2 d-flex justify-content-between align-items-center">
                <strong>Resolution</strong>
                <div class="form-check form-switch mb-0">
                    <input class="form-check-input" type="checkbox" name="res_random" id="res_random" {% if res.get('random', false) %}checked{% endif %}>
                    <label class="form-check-label small" for="res_random">Random aspect ratio</label>
                </div>
            </div>
            <div class="card-body" id="res-fields">
                <div class="d-flex flex-wrap gap-1 mb-2">
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="1024" data-h="1024">1:1</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="1152" data-h="896">4:3 L</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="896" data-h="1152">4:3 P</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="1344" data-h="768">16:9 L</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="768" data-h="1344">16:9 P</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="1280" data-h="800">16:10 L</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="800" data-h="1280">16:10 P</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="1792" data-h="768">21:9 L</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary res-preset" data-w="768" data-h="1792">21:9 P</button>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <label class="form-label mb-0 small fw-semibold">W</label>
                    <input type="number" class="form-control form-control-sm" name="res_width" id="res-width"
                           value="{{ res.get('width', 1024) }}" min="64" max="4096" step="64" style="width:88px">
                    <span class="text-muted">&times;</span>
                    <label class="form-label mb-0 small fw-semibold">H</label>
                    <input type="number" class="form-control form-control-sm" name="res_height" id="res-height"
                           value="{{ res.get('height', 1024) }}" min="64" max="4096" step="64" style="width:88px">
                </div>
            </div>
        </div>

        <div class="d-flex gap-2 pb-4">
            <button type="submit" class="btn btn-primary">Save Preset</button>
            <a href="{{ url_for('preset_detail', slug=preset.slug) }}" class="btn btn-outline-secondary">Cancel</a>
        </div>
    </div>
</div>
</form>
{% endblock %}

{% block scripts %}
<script>
// Resolution preset buttons
document.querySelectorAll('.res-preset').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('res-width').value = btn.dataset.w;
        document.getElementById('res-height').value = btn.dataset.h;
        document.querySelectorAll('.res-preset').forEach(b => {
            b.classList.remove('btn-secondary');
            b.classList.add('btn-outline-secondary');
        });
        btn.classList.remove('btn-outline-secondary');
        btn.classList.add('btn-secondary');
    });
});

// Highlight the matching preset button on load
(function() {
    const w = document.getElementById('res-width').value;
    const h = document.getElementById('res-height').value;
    document.querySelectorAll('.res-preset').forEach(btn => {
        if (btn.dataset.w === w && btn.dataset.h === h) {
            btn.classList.remove('btn-outline-secondary');
            btn.classList.add('btn-secondary');
        }
    });

    // Toggle resolution fields visibility based on random checkbox
    const randomCb = document.getElementById('res_random');
    const resFields = document.getElementById('res-fields');
    function toggleResFields() {
        resFields.querySelectorAll('input, button.res-preset').forEach(el => {
            el.disabled = randomCb.checked;
        });
        resFields.style.opacity = randomCb.checked ? '0.5' : '1';
    }
    randomCb.addEventListener('change', toggleResFields);
    toggleResFields();
})();
</script>
{% endblock %}
