{% extends "base.html" %}

{% block title %}Dashboard — Finite State Report Kit{% endblock %}

{% block content %}
{% include "components/_status_bar.html" %}
{% include "components/_dir_browser.html" %}
{% include "components/_scope_dropdowns.html" %}

<div class="dashboard-layout dashboard-3col">
    <!-- Left column: Scan Queue (live) -->
    <section class="queue-section">
        <h2 class="section-heading">Scan Queue</h2>
        <div id="scan-queue-container"
             hx-get="/api/queue"
             hx-trigger="load delay:500ms, every 30s"
             hx-swap="innerHTML"
             hx-on::response-error="this.innerHTML='<div class=queue-error><span class=queue-error-icon>⚠</span> Could not load queue</div>'">
            <div class="queue-loading">Loading&hellip;</div>
        </div>
    </section>

    <!-- Center column: Workflow cards -->
    <section class="workflows-section">
        <h2 class="section-heading">Workflows</h2>
        <div class="workflow-grid">
            {% for wf in workflows %}
            <div class="workflow-card">
                <div class="workflow-icon">{{ wf.icon }}</div>
                <div class="workflow-info">
                    <h3>{{ wf.title }}</h3>
                    <p>{{ wf.description }}</p>
                </div>
                <form method="post" action="/api/run/prerun"
                      hx-post="/api/run/prerun"
                      hx-target="#prerun-container"
                      hx-swap="innerHTML"
                      hx-indicator="#prerun-spinner">
                    <input type="hidden" name="recipes" value="{{ wf.recipes | join(',') }}">
                    <input type="hidden" name="workflow_title" value="{{ wf.title }}">
                    <input type="hidden" name="_csrf" value="{{ nonce }}">
                    <button type="submit" class="btn btn-primary btn-sm">Configure &rarr;</button>
                </form>
            </div>
            {% endfor %}
        </div>
    </section>

    <!-- Right column: Recipe checkboxes -->
    <section class="recipes-section">
        <h2 class="section-heading">Recipes</h2>
        <form id="recipe-form" x-data="recipeSelector()">
            <div class="recipe-list">
                {% for r in recipes %}
                <label class="recipe-item">
                    <input type="checkbox"
                           name="recipe"
                           value="{{ r.name }}"
                           {% if saved_recipes %}{% if r.name in saved_recipes %}checked{% endif %}{% elif r.auto_run %}checked{% endif %}
                           data-auto-run="{% if r.auto_run %}1{% endif %}"
                           @change="updateSelection()">
                    <div class="recipe-info">
                        <span class="recipe-name">{{ r.name }}</span>
                        <span class="recipe-category">{{ r.category }}</span>
                        {% if r.description %}
                        <span class="recipe-desc">{{ r.description }}</span>
                        {% endif %}
                    </div>
                </label>
                {% endfor %}
            </div>

            <div class="recipe-actions">
                <button type="button" class="btn btn-primary" @click="runSelected()"
                        :disabled="selectedCount === 0">
                    Run Selected (<span x-text="selectedCount">0</span>)
                </button>
                <button type="button" class="btn btn-default" @click="runAll()">
                    Run All
                </button>
            </div>
        </form>
    </section>
</div>

<!-- Pre-run form container (populated by htmx) -->
<div id="prerun-container" class="prerun-overlay"></div>
<div id="prerun-spinner" class="htmx-indicator">Loading...</div>

<script>
var NONCE = '{{ nonce }}';

/* ── Recipe selector (Alpine component) ────────────────────── */
function recipeSelector() {
    /* Restore saved recipe selections from sessionStorage */
    var saved = sessionStorage.getItem('fs_recipes');
    if (saved) {
        try {
            var savedList = JSON.parse(saved);
            document.querySelectorAll('#recipe-form input[type=checkbox]').forEach(function(cb) {
                cb.checked = savedList.indexOf(cb.value) !== -1;
            });
        } catch(e) { /* ignore bad data */ }
    }

    return {
        selectedCount: document.querySelectorAll('#recipe-form input[type=checkbox]:checked').length,
        updateSelection() {
            this.selectedCount = document.querySelectorAll('#recipe-form input[type=checkbox]:checked').length;
            this._persist();
        },
        _persist() {
            var sel = this.getSelected();
            sessionStorage.setItem('fs_recipes', JSON.stringify(sel));
        },
        getSelected() {
            return Array.from(document.querySelectorAll('#recipe-form input[type=checkbox]:checked'))
                .map(function(cb) { return cb.value; });
        },
        runSelected() {
            var recipes = this.getSelected();
            if (recipes.length === 0) return;
            loadPrerun(recipes);
        },
        runAll() {
            var recipes = Array.from(document.querySelectorAll('#recipe-form input[type=checkbox]'))
                .map(function(cb) { return cb.value; });
            loadPrerun(recipes);
        },
    };
}

/* ── Form value persistence ────────────────────────────────── */
function _saveFormValues() {
    var form = document.getElementById('prerun-submit-form');
    if (!form) return;
    var data = {};
    form.querySelectorAll('input, select').forEach(function(el) {
        if (el.type === 'hidden') return;
        if (el.type === 'checkbox') {
            data[el.name] = el.checked;
        } else {
            data[el.name] = el.value;
        }
    });
    sessionStorage.setItem('fs_prerun', JSON.stringify(data));
}

function _restoreFormValues() {
    var raw = sessionStorage.getItem('fs_prerun');
    if (!raw) return;
    try {
        var data = JSON.parse(raw);
    } catch(e) { return; }
    var form = document.getElementById('prerun-submit-form');
    if (!form) return;
    Object.keys(data).forEach(function(name) {
        var el = form.querySelector('[name="' + name + '"]');
        if (!el || el.type === 'hidden') return;
        if (el.type === 'checkbox') {
            el.checked = !!data[name];
        } else if (el.tagName === 'SELECT') {
            el.value = data[name];
        } else {
            el.value = data[name];
        }
    });
}

/* ── Load pre-run form into side panel ─────────────────────── */
function loadPrerun(recipes) {
    var container = document.getElementById('prerun-container');
    container.innerHTML = '<div class="prerun-loading"><span class="spinner"></span> Loading...</div>';
    container.classList.add('active');
    var formData = new FormData();
    formData.append('recipes', recipes.join(','));
    formData.append('_csrf', NONCE);
    fetch('/api/run/prerun', {
        method: 'POST',
        headers: { 'X-FS-Session': NONCE },
        body: formData,
    })
    .then(function(r) { return r.text(); })
    .then(function(html) {
        container.innerHTML = html;
        _restoreFormValues();
        _initPrerunWidgets();
    });
}

/* ── Event delegation: handle Run / Cancel in prerun panel ── */
document.addEventListener('click', function(e) {
    /* Run button */
    if (e.target && e.target.id === 'btn-run-submit') {
        e.preventDefault();
        var btn = e.target;
        var form = document.getElementById('prerun-submit-form');
        if (!form) return;
        _hidePrerunError();
        _syncFindingTypes();
        _saveFormValues();
        var formData = new FormData(form);
        btn.disabled = true;
        btn.textContent = 'Starting\u2026';
        fetch('/api/run', {
            method: 'POST',
            headers: { 'X-FS-Session': NONCE },
            body: formData,
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.run_id) {
                sessionStorage.removeItem('fs_prerun');
                sessionStorage.removeItem('fs_recipes');
                window.location.href = '/run/' + data.run_id;
            } else {
                _showPrerunError(data.error || 'Unknown error');
                btn.disabled = false;
                btn.textContent = btn.getAttribute('data-label') || 'Run';
            }
        })
        .catch(function(err) {
            _showPrerunError('Failed to start run: ' + err);
            btn.disabled = false;
            btn.textContent = btn.getAttribute('data-label') || 'Run';
        });
    }

    /* Cancel / close button */
    if (e.target && e.target.classList.contains('prerun-close')) {
        _hidePrerunError();
        document.getElementById('prerun-container').classList.remove('active');
        document.getElementById('prerun-container').innerHTML = '';
    }
});

/* ── Inline error helpers ──────────────────────────────────── */
function _showPrerunError(msg) {
    var el = document.getElementById('prerun-error');
    if (el) { el.textContent = msg; el.style.display = 'block'; }
}
function _hidePrerunError() {
    var el = document.getElementById('prerun-error');
    if (el) { el.style.display = 'none'; el.textContent = ''; }
}

/* ── Sync finding-type checkboxes to hidden field ─────────── */
function _syncFindingTypes() {
    var cbs = document.querySelectorAll('input[name="ft_cb"]:checked');
    var hidden = document.getElementById('pre-ft');
    if (!hidden || cbs.length === 0) return;
    hidden.value = Array.from(cbs).map(function(cb) { return cb.value; }).join(',');
}

/* ── Init dir browser + scope dropdowns in prerun panel ──── */
function _initPrerunWidgets() {
    var runBtn = document.getElementById('btn-run-submit');
    if (runBtn) runBtn.setAttribute('data-label', runBtn.textContent);
    initDirBrowser('pre-output', 'pre-output-browse');
    initScopeDropdowns({
        projectId: 'pre-project',
        folderId:  'pre-folder',
        versionId: 'pre-version',
        cvoId:     'pre-cvo',
    });
    initVersionPicker({
        projectSelId: 'pre-bv-project',
        versionSelId: 'pre-bv-version',
        inputId: 'pre-bv',
    });
    initVersionPicker({
        projectSelId: 'pre-cv-project',
        versionSelId: 'pre-cv-version',
        inputId: 'pre-cv',
    });
    /* Character counter for deployment notes textarea */
    var ta = document.getElementById('pre-deploy-notes');
    var counter = document.getElementById('pre-deploy-notes-count');
    if (ta && counter) {
        ta.addEventListener('input', function() {
            counter.textContent = ta.value.length;
        });
    }
}

/* ── Sync side column heights to workflow column ───────────── */
function _syncColumnHeights() {
    var wf = document.querySelector('.workflows-section');
    if (!wf) return;
    var h = wf.offsetHeight;
    var queue = document.querySelector('.queue-section');
    var recipes = document.querySelector('.recipes-section');
    if (queue) queue.style.maxHeight = h + 'px';
    if (recipes) recipes.style.maxHeight = h + 'px';
}
window.addEventListener('load', _syncColumnHeights);
window.addEventListener('resize', _syncColumnHeights);

/* ── Also activate panel after htmx swaps (workflow cards) ── */
document.addEventListener('htmx:afterSwap', function(e) {
    if (e.detail.target && e.detail.target.id === 'prerun-container') {
        e.detail.target.classList.add('active');
        _restoreFormValues();
        _initPrerunWidgets();
    }
});
</script>
{% endblock %}
