{% extends "layout.html" %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-5">
            <div id="progress-container" class="mb-3 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">
                <div class="card-header bg-primary text-white">Multi-Character Generator</div>
                <div class="card-body">
                    <form id="multi-form" action="{{ url_for('multi_char') }}" method="post">

                        <!-- Controls bar -->
                        <div class="d-flex align-items-center gap-2 flex-wrap mb-3 pb-3 border-bottom">
                            <button type="submit" class="btn btn-primary" id="generate-btn" data-requires="comfyui">Generate</button>
                            <input type="number" id="num-images" value="1" min="1" max="999"
                                   class="form-control form-control-sm" style="width:65px" title="Number of images">
                            <div class="input-group input-group-sm" style="width:180px">
                                <span class="input-group-text">Seed</span>
                                <input type="number" class="form-control" id="seed-input" name="seed" 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="button" class="btn btn-outline-warning" id="endless-btn">Endless</button>
                            <button type="button" class="btn btn-danger d-none" id="stop-btn">Stop</button>
                            <div class="ms-auto form-check mb-0">
                                <input type="checkbox" class="form-check-input" id="lucky-dip">
                                <label class="form-check-label" for="lucky-dip">Lucky Dip</label>
                            </div>
                        </div>

                        <!-- Character A -->
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <label for="char_a" class="form-label mb-0">Character A</label>
                                <button type="button" class="btn btn-sm btn-outline-secondary random-char-btn" data-target="char_a">Random</button>
                            </div>
                            <select class="form-select" id="char_a" name="char_a" required>
                                <option value="" disabled {% if not selected_char_a %}selected{% endif %}>Select character A...</option>
                                {% for char in characters %}
                                <option value="{{ char.slug }}" {% if selected_char_a == char.slug %}selected{% endif %}>{{ char.name }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- Character B -->
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <label for="char_b" class="form-label mb-0">Character B</label>
                                <button type="button" class="btn btn-sm btn-outline-secondary random-char-btn" data-target="char_b">Random</button>
                            </div>
                            <select class="form-select" id="char_b" name="char_b" required>
                                <option value="" disabled {% if not selected_char_b %}selected{% endif %}>Select character B...</option>
                                {% for char in characters %}
                                <option value="{{ char.slug }}" {% if selected_char_b == char.slug %}selected{% endif %}>{{ char.name }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- Checkpoint -->
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <label for="checkpoint" class="form-label mb-0">Checkpoint Model</label>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="random-ckpt-btn">Random</button>
                            </div>
                            <select class="form-select" id="checkpoint" name="checkpoint" required>
                                {% for ckpt in checkpoints %}
                                <option value="{{ ckpt }}">{{ ckpt }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- Mix & Match -->
                        <div class="mb-3">
                            <label class="form-label">Mix &amp; Match
                                <small class="text-muted fw-normal ms-1">— first checked per category applies its LoRA</small>
                            </label>
                            <div class="accordion" id="mixAccordion">
                                {% set mix_categories = [
                                    ('Actions', 'action', actions, 'action_slugs'),
                                    ('Scenes', 'scene', scenes, 'scene_slugs'),
                                    ('Styles', 'style', styles, 'style_slugs'),
                                    ('Detailers', 'detailer', detailers, 'detailer_slugs'),
                                ] %}
                                {% for cat_label, cat_key, cat_items, field_name in mix_categories %}
                                <div class="accordion-item">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button collapsed py-2" type="button"
                                                data-bs-toggle="collapse" data-bs-target="#mix-{{ cat_key }}">
                                            {{ cat_label }}
                                            <span class="badge bg-secondary rounded-pill ms-2" id="badge-{{ cat_key }}">0</span>
                                            <span class="badge bg-light text-secondary border ms-2 px-2 py-1"
                                                  style="cursor:pointer;font-size:.7rem;font-weight:normal"
                                                  onclick="event.stopPropagation(); randomizeCategory('{{ field_name }}', '{{ cat_key }}')">Random</span>
                                        </button>
                                    </h2>
                                    <div id="mix-{{ cat_key }}" class="accordion-collapse collapse">
                                        <div class="accordion-body p-2">
                                            <input type="text" class="form-control form-control-sm mb-2"
                                                   placeholder="Search {{ cat_label | lower }}..."
                                                   oninput="filterMixCategory(this, 'mixlist-{{ cat_key }}')">
                                            <div id="mixlist-{{ cat_key }}" style="max-height:220px;overflow-y:auto;">
                                                {% for item in cat_items %}
                                                <label class="mix-item d-flex align-items-center gap-2 px-2 py-1 rounded"
                                                       data-name="{{ item.name | lower }}" style="cursor:pointer;">
                                                    <input type="checkbox" class="form-check-input flex-shrink-0"
                                                           name="{{ field_name }}" value="{{ item.slug }}"
                                                           onchange="updateMixBadge('{{ cat_key }}', '{{ field_name }}')">
                                                    {% if item.image_path %}
                                                    <img src="{{ url_for('static', filename='uploads/' + item.image_path) }}"
                                                         class="rounded flex-shrink-0" style="width:32px;height:32px;object-fit:cover">
                                                    {% else %}
                                                    <span class="rounded bg-light flex-shrink-0 d-inline-flex align-items-center justify-content-center text-muted"
                                                          style="width:32px;height:32px;font-size:9px;">N/A</span>
                                                    {% endif %}
                                                    <span class="small text-truncate">{{ item.name }}</span>
                                                </label>
                                                {% else %}
                                                <p class="text-muted small p-2 mb-0">No {{ cat_label | lower }} found.</p>
                                                {% endfor %}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>

                        <!-- Resolution -->
                        <div class="mb-3">
                            <label class="form-label">Resolution</label>
                            <div class="d-flex flex-wrap gap-1 mb-2">
                                <button type="button" class="btn btn-sm btn-outline-secondary preset-btn" data-w="1024" data-h="1024">1:1</button>
                                <button type="button" class="btn btn-sm btn-secondary preset-btn" data-w="1152" data-h="896">4:3 L</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary preset-btn" data-w="896" data-h="1152">4:3 P</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary preset-btn" data-w="1344" data-h="768">16:9 L</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary preset-btn" data-w="768" data-h="1344">16:9 P</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary preset-btn" data-w="1792" data-h="768">21:9 L</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary preset-btn" 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="width" id="res-width"
                                       value="1152" 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="height" id="res-height"
                                       value="896" min="64" max="4096" step="64" style="width:88px">
                            </div>
                        </div>

                        <!-- Prompt Previews -->
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <label class="form-label mb-0">Prompt Previews</label>
                                <div class="d-flex gap-1">
                                    <button type="button" class="btn btn-sm btn-outline-primary" id="build-preview-btn">Build</button>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="clear-preview-btn">Clear</button>
                                </div>
                            </div>
                            <div class="form-text mb-2" id="preview-status"></div>

                            <label class="form-label mb-0 small text-muted">Main (KSampler)</label>
                            <div class="tag-widget-container d-none mb-2" id="prompt-tags"></div>
                            <textarea class="form-control form-control-sm font-monospace mb-2" id="prompt-preview"
                                      name="override_prompt" rows="4"
                                      placeholder="Click Build to preview — this is the combined prompt sent to KSampler."></textarea>

                            <label class="form-label mb-0 small text-muted">Person A Detailer (left)</label>
                            <div class="tag-widget-container d-none mb-2" id="char-a-main-tags"></div>
                            <textarea class="form-control form-control-sm font-monospace mb-2" id="char-a-main-preview"
                                      name="override_char_a_main" rows="2"
                                      placeholder="Character A body prompt for person ADetailer."></textarea>

                            <label class="form-label mb-0 small text-muted">Person B Detailer (right)</label>
                            <div class="tag-widget-container d-none mb-2" id="char-b-main-tags"></div>
                            <textarea class="form-control form-control-sm font-monospace mb-2" id="char-b-main-preview"
                                      name="override_char_b_main" rows="2"
                                      placeholder="Character B body prompt for person ADetailer."></textarea>

                            <label class="form-label mb-0 small text-muted">Face A Detailer (left)</label>
                            <div class="tag-widget-container d-none mb-2" id="char-a-face-tags"></div>
                            <textarea class="form-control form-control-sm font-monospace mb-2" id="char-a-face-preview"
                                      name="override_char_a_face" rows="2"
                                      placeholder="Character A face prompt."></textarea>

                            <label class="form-label mb-0 small text-muted">Face B Detailer (right)</label>
                            <div class="tag-widget-container d-none mb-2" id="char-b-face-tags"></div>
                            <textarea class="form-control form-control-sm font-monospace mb-2" id="char-b-face-preview"
                                      name="override_char_b_face" rows="2"
                                      placeholder="Character B face prompt."></textarea>
                        </div>

                        <!-- Additional prompts -->
                        <div class="mb-3">
                            <label for="positive_prompt" class="form-label">Additional Positive Prompt</label>
                            <textarea class="form-control" id="positive_prompt" name="positive_prompt" rows="2" placeholder="e.g. standing together, park, daylight"></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="negative_prompt" class="form-label">Additional Negative Prompt</label>
                            <textarea class="form-control" id="negative_prompt" name="negative_prompt" rows="2" placeholder="e.g. bad hands, extra digits"></textarea>
                        </div>

                    </form>
                </div>
            </div>

        </div>

        <div class="col-md-7">
            <div class="card">
                <div class="card-header bg-dark text-white">Result</div>
                <div class="card-body p-0 d-flex align-items-center justify-content-center" style="min-height: 500px;" id="result-container">
                    <div class="text-center text-muted" id="placeholder-text">
                        <p>Select two characters and click Generate</p>
                    </div>
                    <div class="img-container w-100 h-100 d-none">
                        <img src="" alt="Generated Result" class="img-fluid w-100" id="result-img">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // --- Filtering ---
    function filterMixCategory(input, listId) {
        const query = input.value.toLowerCase();
        document.querySelectorAll(`#${listId} .mix-item`).forEach(el => {
            el.style.display = el.dataset.name.includes(query) ? '' : 'none';
        });
    }

    function updateMixBadge(key, fieldName) {
        const count = document.querySelectorAll(`input[name="${fieldName}"]:checked`).length;
        const badge = document.getElementById(`badge-${key}`);
        badge.textContent = count;
        badge.className = count > 0
            ? 'badge bg-primary rounded-pill ms-2'
            : 'badge bg-secondary rounded-pill ms-2';
    }

    // --- Randomizers ---
    function randomizeCategory(fieldName, catKey) {
        const cbs = Array.from(document.querySelectorAll(`input[name="${fieldName}"]`));
        cbs.forEach(cb => cb.checked = false);
        if (cbs.length) cbs[Math.floor(Math.random() * cbs.length)].checked = true;
        updateMixBadge(catKey, fieldName);
    }

    function randomizeSelect(selectId) {
        const opts = Array.from(document.getElementById(selectId).options).filter(o => o.value);
        if (opts.length)
            document.getElementById(selectId).value = opts[Math.floor(Math.random() * opts.length)].value;
    }

    function applyLuckyDip() {
        randomizeSelect('char_a');
        randomizeSelect('char_b');
        randomizeSelect('checkpoint');

        const presets = Array.from(document.querySelectorAll('.preset-btn'));
        if (presets.length) presets[Math.floor(Math.random() * presets.length)].click();

        [['action_slugs', 'action'], ['scene_slugs', 'scene'],
         ['style_slugs', 'style'], ['detailer_slugs', 'detailer']].forEach(([field, key]) => {
            randomizeCategory(field, key);
        });
    }

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

    ['res-width', 'res-height'].forEach(id => {
        document.getElementById(id).addEventListener('input', () => {
            document.querySelectorAll('.preset-btn').forEach(b => {
                b.classList.remove('btn-secondary');
                b.classList.add('btn-outline-secondary');
            });
        });
    });

    // --- Tag Widget System ---
    function populateTagWidgets(containerId, textareaId, promptStr, opts = {}) {
        const container = document.getElementById(containerId);
        const textarea = document.getElementById(textareaId);
        container.innerHTML = '';

        if (!promptStr || !promptStr.trim()) {
            container.classList.add('d-none');
            return;
        }

        // Split on commas but preserve BREAK as a visual separator
        const rawParts = promptStr.split(',').map(t => t.trim()).filter(Boolean);
        rawParts.forEach(part => {
            // Check if this part contains BREAK (e.g. "tag1 BREAK tag2")
            if (part.includes('BREAK')) {
                const breakParts = part.split(/\s+BREAK\s+/);
                breakParts.forEach((bp, i) => {
                    if (bp.trim()) {
                        addTagEl(container, containerId, textareaId, bp.trim(), opts.readonly);
                    }
                    if (i < breakParts.length - 1) {
                        const sep = document.createElement('span');
                        sep.className = 'tag-widget';
                        sep.style.cssText = 'background:var(--accent-glow);color:var(--accent-bright);cursor:default;font-weight:600;pointer-events:none;';
                        sep.textContent = 'BREAK';
                        sep.dataset.break = 'true';
                        container.appendChild(sep);
                    }
                });
            } else {
                addTagEl(container, containerId, textareaId, part, opts.readonly);
            }
        });
        container.classList.remove('d-none');
        textarea.classList.add('d-none');
    }

    function addTagEl(container, containerId, textareaId, tag, readonly) {
        const el = document.createElement('span');
        el.className = 'tag-widget active';
        el.textContent = tag;
        el.dataset.tag = tag;
        if (!readonly) {
            el.addEventListener('click', () => {
                el.classList.toggle('active');
                el.classList.toggle('inactive');
                rebuildFromTags(containerId, textareaId);
            });
        } else {
            el.style.cursor = 'default';
        }
        container.appendChild(el);
    }

    function rebuildFromTags(containerId, textareaId) {
        const container = document.getElementById(containerId);
        const textarea = document.getElementById(textareaId);
        const parts = [];
        let currentGroup = [];
        container.querySelectorAll('.tag-widget').forEach(el => {
            if (el.dataset.break) {
                if (currentGroup.length) parts.push(currentGroup.join(', '));
                currentGroup = [];
            } else if (el.classList.contains('active')) {
                currentGroup.push(el.dataset.tag);
            }
        });
        if (currentGroup.length) parts.push(currentGroup.join(', '));
        textarea.value = parts.join(' BREAK ');
    }

    function clearTagWidgets(containerId, textareaId) {
        const container = document.getElementById(containerId);
        const textarea = document.getElementById(textareaId);
        container.innerHTML = '';
        container.classList.add('d-none');
        textarea.classList.remove('d-none');
        textarea.value = '';
    }

    const TAG_PAIRS = [
        ['prompt-tags', 'prompt-preview'],
        ['char-a-main-tags', 'char-a-main-preview'],
        ['char-b-main-tags', 'char-b-main-preview'],
        ['char-a-face-tags', 'char-a-face-preview'],
        ['char-b-face-tags', 'char-b-face-preview'],
    ];

    // --- Prompt preview ---
    async function buildPromptPreview() {
        const charA = document.getElementById('char_a').value;
        const charB = document.getElementById('char_b').value;
        const status = document.getElementById('preview-status');
        if (!charA || !charB) { status.textContent = 'Select both characters first.'; return; }

        status.textContent = 'Building...';
        const formData = new FormData(document.getElementById('multi-form'));
        try {
            const resp = await fetch('/multi/preview_prompt', { method: 'POST', body: formData });
            const data = await resp.json();
            if (data.error) {
                status.textContent = 'Error: ' + data.error;
            } else {
                document.getElementById('prompt-preview').value = data.prompt;
                document.getElementById('char-a-main-preview').value = data.char_a_main || '';
                document.getElementById('char-b-main-preview').value = data.char_b_main || '';
                document.getElementById('char-a-face-preview').value = data.char_a_face || '';
                document.getElementById('char-b-face-preview').value = data.char_b_face || '';
                populateTagWidgets('prompt-tags', 'prompt-preview', data.prompt);
                populateTagWidgets('char-a-main-tags', 'char-a-main-preview', data.char_a_main || '');
                populateTagWidgets('char-b-main-tags', 'char-b-main-preview', data.char_b_main || '');
                populateTagWidgets('char-a-face-tags', 'char-a-face-preview', data.char_a_face || '');
                populateTagWidgets('char-b-face-tags', 'char-b-face-preview', data.char_b_face || '');
                status.textContent = 'Click tags to toggle — Clear to reset.';
            }
        } catch (err) {
            status.textContent = 'Request failed.';
        }
    }

    document.getElementById('build-preview-btn').addEventListener('click', buildPromptPreview);
    document.getElementById('clear-preview-btn').addEventListener('click', () => {
        TAG_PAIRS.forEach(([c, t]) => clearTagWidgets(c, t));
        document.getElementById('preview-status').textContent = '';
    });

    // --- Main generation logic ---
    document.addEventListener('DOMContentLoaded', () => {
        const form         = document.getElementById('multi-form');
        const progressBar  = document.getElementById('progress-bar');
        const progressCont = document.getElementById('progress-container');
        const progressLbl  = document.getElementById('progress-label');
        const generateBtn  = document.getElementById('generate-btn');
        const endlessBtn   = document.getElementById('endless-btn');
        const stopBtn      = document.getElementById('stop-btn');
        const numInput     = document.getElementById('num-images');
        const resultImg    = document.getElementById('result-img');
        const placeholder  = document.getElementById('placeholder-text');

        let currentJobId = null;
        let stopRequested = false;

        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') progressLbl.textContent = 'Generating\u2026';
                        else progressLbl.textContent = 'Queued\u2026';
                    } catch (err) {}
                }, 1500);
            });
        }

        function setGeneratingState(active) {
            generateBtn.disabled = active;
            endlessBtn.disabled  = active;
            stopBtn.classList.toggle('d-none', !active);
            if (!active) progressCont.classList.add('d-none');
        }

        async function runOne(label) {
            if (document.getElementById('lucky-dip').checked) applyLuckyDip();

            progressCont.classList.remove('d-none');
            progressBar.style.width = '100%'; progressBar.textContent = '';
            progressBar.classList.add('progress-bar-striped', 'progress-bar-animated');
            progressLbl.textContent = label;

            const fd = new FormData(form);

            const resp = await fetch(form.action, {
                method: 'POST', body: fd,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await resp.json();
            if (data.error) throw new Error(data.error);

            currentJobId = data.job_id;
            progressLbl.textContent = 'Queued\u2026';

            const jobResult = await waitForJob(currentJobId);
            currentJobId = null;

            if (jobResult.result && jobResult.result.image_url) {
                resultImg.src = jobResult.result.image_url;
                resultImg.parentElement.classList.remove('d-none');
                if (placeholder) placeholder.classList.add('d-none');
            }
            updateSeedFromResult(jobResult.result);
            progressBar.classList.remove('progress-bar-striped', 'progress-bar-animated');
        }

        async function runLoop(endless) {
            const total = endless ? Infinity : (parseInt(numInput.value) || 1);
            stopRequested = false;
            setGeneratingState(true);
            let n = 0;
            try {
                while (!stopRequested && n < total) {
                    n++;
                    const lbl = endless          ? `Generating #${n} (endless)...`
                              : total === 1      ? 'Starting...'
                                                 : `Generating ${n} / ${total}...`;
                    await runOne(lbl);
                }
            } catch (err) {
                console.error(err);
                alert('Generation failed: ' + err.message);
            } finally {
                setGeneratingState(false);
            }
        }

        form.addEventListener('submit', (e) => { e.preventDefault(); runLoop(false); });
        endlessBtn.addEventListener('click', () => runLoop(true));
        stopBtn.addEventListener('click', () => {
            stopRequested = true;
            progressLbl.textContent = 'Stopping after current image...';
        });

        // Random character buttons
        document.querySelectorAll('.random-char-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                randomizeSelect(btn.dataset.target);
            });
        });

        document.getElementById('random-ckpt-btn').addEventListener('click', () => {
            randomizeSelect('checkpoint');
        });

        document.getElementById('char_a').addEventListener('change', buildPromptPreview);
        document.getElementById('char_b').addEventListener('change', buildPromptPreview);

        document.getElementById('seed-clear-btn').addEventListener('click', () => {
            document.getElementById('seed-input').value = '';
        });
    });
</script>
{% endblock %}
