{% extends "base.html" %}
{% block title %}Dashboard - circus{% endblock %}
{% block topbar %}
{% endblock %}
{% block topbar_title %}Dashboard{% endblock %}
{% block topbar_context %}Nix evaluations, builds, workers, and queue state{% endblock %}
{% block content %}
    <header class="page-header operator-header">
        <div>
            <div class="dashboard-title-row">
                <h1>Dashboard</h1>
            </div>
            <p class="page-subtitle">Evaluations, builds, agents, and project health.</p>
        </div>
        <div class="operator-header-actions">
            {% if !auth_name.is_empty() %}
                <span class="auth-user">{{ auth_name }}</span>
                <form method="POST" action="/logout">
                    <button class="btn-ghost" type="submit">Logout</button>
                </form>
            {% else %}
                <a class="btn btn-secondary" href="/login">Login</a>
            {% endif %}
        </div>
        <form class="operator-toolbar" method="get" action="/builds">
            <input class="dashboard-search"
                   type="search"
                   name="job_name"
                   placeholder="Filter builds by job name"
                   aria-label="Filter builds by job name">
            <select class="dashboard-system" name="system" aria-label="Filter builds by system">
                <option value="">All systems</option>
                {% for system in system_filters %}
                    <option value="{{ system }}">{{ system }}</option>
                {% endfor %}
            </select>
            <button class="btn btn-small btn-secondary" type="submit">View builds</button>
        </form>
    </header>

    {% if !announcements.is_empty() %}
        <div class="announcements" role="status">
            {% for item in announcements %}
                <div class="announcement-line" data-announcement>
                    <span>
                        <strong>{{ item.title }}</strong>: {{ item.content }}
                    </span>
                    <button type="button"
                            class="btn-ghost announcement-close"
                            aria-label="Dismiss announcement"
                            onclick="this.parentElement.remove()">
                        &times;
                    </button>
                </div>
            {% endfor %}
        </div>
    {% endif %}

    {% let finished_builds = total_builds - running_builds - pending_builds %}
    <section class="metric-strip" aria-label="Build farm metrics">
        <a class="metric-cell" href="/builds">
            <span>Total builds</span>
            <strong>{{ total_builds }}</strong><small>all tracked builds</small>
        </a>
        <a class="metric-cell metric-success" href="/builds?status=succeeded">
            <span>Succeeded</span>
            <strong>{{ completed_builds }}</strong><small>
            {% if total_builds > 0 %}
                {{ completed_builds * 100 / total_builds }}% of all builds
            {% else %}
                0% of all builds
            {% endif %}
            </small>
        </a>
        <a class="metric-cell metric-failed" href="/builds?status=failed">
            <span>Failed</span>
            <strong>{{ failed_builds }}</strong><small>
            {% if total_builds > 0 %}
                {{ failed_builds * 100 / total_builds }}% of all builds
            {% else %}
                0% of all builds
            {% endif %}
            </small>
        </a>
        <a class="metric-cell metric-running" href="/builds?status=running">
            <span>Running</span>
            <strong>{{ running_builds }}</strong><small>currently running</small>
        </a>
        <a class="metric-cell" href="/queue">
            <span>Queued</span>
            <strong>{{ pending_builds }}</strong><small>pending now</small>
        </a>
        <a class="metric-cell metric-success" href="/builds?status=succeeded">
            <span>Success rate</span>
            <strong>
            {% if finished_builds > 0 %}
                {{ completed_builds * 100 / finished_builds }}%
            {% else %}
                -
            {% endif %}
            </strong><small>completed / finished</small>
        </a>
    </section>
    <section class="dashboard-grid" aria-label="Build farm overview">
        <div class="operator-primary">
            <section class="panel projects-panel">
                <div class="panel-header">
                    <h2>Projects</h2>
                    <span class="panel-actions">
                        <a href="/projects">all projects</a>
                        {% if is_admin %}<a href="/projects/new">new project</a>{% endif %}
                    </span>
                </div>
                {% if projects.is_empty() %}
                    <div class="empty compact-empty">
                        <div class="empty-title">No projects yet</div>
                        {% if is_admin %}
                            <div class="empty-hint">
                                <a href="/projects/new">Create a project</a>
                                to get started.
                            </div>
                        {% endif %}
                    </div>
                {% else %}
                    <div class="table-wrap compact-table-wrap">
                        <table class="data-table dense-table">
                            <thead>
                                <tr>
                                    <th>Project</th>
                                    <th class="numeric" style="width:5rem">Jobsets</th>
                                    <th>Last eval</th>
                                    <th>Eval status</th>
                                    <th class="numeric" style="width:6rem">Failing jobs</th>
                                    <th class="numeric" style="width:5rem">Queued</th>
                                    <th>Systems</th>
                                    <th>Updated</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for p in projects %}
                                    <tr>
                                        <td class="truncate" title="{{ p.name }}">
                                            <a href="/project/{{ p.id }}">{{ p.name }}</a>
                                        </td>
                                        <td class="numeric">{{ p.jobset_count }}</td>
                                        <td class="mono nowrap">{{ p.last_eval_time }}</td>
                                        <td>
                                            <span class="status status-{{ p.last_eval_class }}">
                                                {{ p.last_eval_status }}
                                            </span>
                                        </td>
                                        <td class="numeric">
                                            <a href="/builds?status=failed">{{ p.failing_jobs }}</a>
                                        </td>
                                        <td class="numeric">
                                            <a href="/queue">{{ p.queued_jobs }}</a>
                                        </td>
                                        <td class="mono truncate" title="{{ p.systems }}">{{ p.systems }}</td>
                                        <td class="mono nowrap">{{ p.updated_at }}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% endif %}
            </section>

            <section class="panel panel-recent">
                <div class="panel-header">
                    <h2>Builds</h2>
                    <a href="/builds">all builds</a>
                </div>
                <form class="filter-bar" data-table-filter="recent-builds">
                    <input type="search"
                           id="recent-builds-filter"
                           name="q"
                           aria-label="Filter recent builds"
                           placeholder="filter project, job, system"
                           data-filter-text>
                    <select id="recent-builds-status"
                            name="status"
                            aria-label="Filter recent builds by status"
                            data-filter-status>
                        <option value="">All status</option>
                        <option value="failed">Failed</option>
                        <option value="succeeded">Succeeded</option>
                        <option value="running">Running</option>
                        <option value="pending">Queued</option>
                    </select>
                    <a class="btn btn-small btn-secondary" href="/builds" data-open-selected>Open selected</a>
                </form>
                {% if recent_builds.is_empty() %}
                    <div class="empty compact-empty">
                        <div class="empty-title">No builds yet</div>
                        <div class="empty-hint">Builds appear once an evaluation produces jobs.</div>
                    </div>
                {% else %}
                    <div class="table-wrap compact-table-wrap">
                        <table class="data-table dense-table selectable-table" id="recent-builds" data-keyboard-table>
                            <thead>
                                <tr>
                                    <th>Build</th>
                                    <th>Project</th>
                                    <th>Job</th>
                                    <th>System</th>
                                    <th>Status</th>
                                    <th>Duration</th>
                                    <th>Created</th>
                                    <th>Log</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for b in recent_builds %}
                                    <tr tabindex="0"
                                        data-href="/build/{{ b.id }}"
                                        data-status="{{ b.status_class }}"
                                        data-project="{{ b.project_name }}"
                                        data-system="{{ b.system }}"
                                        data-job="{{ b.job_name }}">
                                        <td class="mono">
                                            <a href="/build/{{ b.id }}"
                                               title="{{ b.id }}"
                                               aria-label="Build {{ b.id }}">#{{ b.id_short }}</a>
                                        </td>
                                        <td class="truncate" title="{{ b.project_name }}">
                                            {% match b.project_id %}
                                                {% when Some with (project_id) %}
                                                    <a href="/project/{{ project_id }}">{{ b.project_name }}</a>
                                                {% when None %}
                                                    -
                                            {% endmatch %}
                                        </td>
                                        <td class="mono truncate" title="{{ b.job_name }}">{{ b.job_name }}</td>
                                        <td class="mono nowrap">{{ b.system }}</td>
                                        <td>
                                            <span class="status status-{{ b.status_class }}">{{ b.status_text }}</span>
                                        </td>
                                        <td class="mono">{{ b.duration }}</td>
                                        <td class="mono nowrap">{{ b.created_at }}</td>
                                        <td>
                                            {% if b.has_log %}
                                                <a href="/build/{{ b.id }}/log">log</a>
                                            {% else %}
                                                -
                                            {% endif %}
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% endif %}
            </section>

            <section class="panel panel-agents">
                <div class="panel-header">
                    <h2>Agents</h2>
                    <a href="/admin#agents">manage</a>
                </div>
                {% if workers.is_empty() %}
                    <div class="empty compact-empty">
                        <div class="empty-title">No agents</div>
                        <div class="empty-hint">No agent sessions have checked in.</div>
                    </div>
                {% else %}
                    <div class="table-wrap compact-table-wrap">
                        <table class="data-table dense-table">
                            <thead>
                                <tr>
                                    <th>Agent</th>
                                    <th>System</th>
                                    <th>Status</th>
                                    <th>Load</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for w in workers %}
                                    <tr>
                                        <td class="truncate">
                                            {% if !auth_name.is_empty() %}
                                                <strong title="{{ w.name }}">{{ w.name }}</strong>
                                            {% else %}
                                                <strong>Agent #{{ loop.index }}</strong>
                                            {% endif %}
                                        </td>
                                        <td class="mono nowrap">{{ w.system }}</td>
                                        <td>
                                            <span class="status status-{{ w.status_class }}">{{ w.status_text }}</span>
                                        </td>
                                        <td class="mono nowrap">{{ w.current_jobs }}/{{ w.max_jobs }}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% endif %}
            </section>
        </div>

        <aside class="operator-sidebar" aria-label="Build farm inspector">
            <section class="panel panel-queue">
                <div class="panel-header">
                    <h2>Queue</h2>
                    <a href="/queue">queue</a>
                </div>
                <h3>Queued by system</h3>
                {% if queue_by_system.is_empty() %}
                    <div class="section-empty">No queued builds.</div>
                {% else %}
                    <ul class="summary-list">
                        {% for item in queue_by_system %}
                            <li>
                                <a href="/builds?status=pending&system={{ item.system }}">
                                    <span class="mono">{{ item.system }}</span>
                                    <strong class="numeric">{{ item.count }}</strong>
                                </a>
                            </li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </section>

            <section class="panel panel-recent-evals">
                <div class="panel-header">
                    <h2>Recent evaluations</h2>
                    <a href="/evaluations">all</a>
                </div>
                {% if recent_evals.is_empty() %}
                    <div class="section-empty">No recent evaluations.</div>
                {% else %}
                    <ul class="summary-list">
                        {% for e in recent_evals %}
                            <li>
                                <a href="/evaluation/{{ e.id }}">
                                    <span class="mono">{{ e.commit_short }}</span>
                                    <span class="status status-{{ e.status_class }}">{{ e.status_text }}</span>
                                </a>
                            </li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </section>
        </aside>
    </section>
{% endblock %}
{% block scripts %}
    <script>
        (function() {
            function rowsFor(table) {
                return Array.prototype.slice.call(
                    table.querySelectorAll('tbody tr[data-href]')
                );
            }

            function rowText(row) {
                return [
                    row.getAttribute('data-project') || '',
                    row.getAttribute('data-job') || '',
                    row.getAttribute('data-system') || '',
                    row.textContent || ''
                ].join(' ').toLowerCase();
            }

            function statusMatches(rowStatus, wanted) {
                if (!wanted) return true;
                if (wanted === rowStatus) return true;
                return wanted === 'succeeded' && rowStatus === 'completed';
            }

            function selectedRow(table) {
                return table.querySelector('tbody tr[aria-selected="true"]');
            }

            function visibleRows(table) {
                return rowsFor(table).filter(function(row) {
                    return !row.hidden;
                });
            }

            function selectRow(table, row, shouldFocus) {
                rowsFor(table).forEach(function(item) {
                    item.removeAttribute('aria-selected');
                });

                if (!row) return;

                row.setAttribute('aria-selected', 'true');
                if (shouldFocus) row.focus();
                updateOpenSelected(table);
            }

            function updateOpenSelected(table) {
                var form = document.querySelector('[data-table-filter="' + table.id + '"]');
                if (!form) return;

                var openLink = form.querySelector('[data-open-selected]');
                if (!openLink) return;

                var row = selectedRow(table);
                if (row) {
                    openLink.href = row.getAttribute('data-href');
                    openLink.removeAttribute('aria-disabled');
                } else {
                    openLink.href = '/builds';
                    openLink.setAttribute('aria-disabled', 'true');
                }
            }

            function applyFilter(form) {
                var table = document.getElementById(form.getAttribute('data-table-filter'));
                if (!table) return;

                var textInput = form.querySelector('[data-filter-text]');
                var statusInput = form.querySelector('[data-filter-status]');
                var query = textInput ? textInput.value.trim().toLowerCase() : '';
                var status = statusInput ? statusInput.value : '';

                rowsFor(table).forEach(function(row) {
                    var matchesText = !query || rowText(row).indexOf(query) !== -1;
                    var matchesStatus = statusMatches(
                        row.getAttribute('data-status') || '',
                        status
                    );
                    row.hidden = !(matchesText && matchesStatus);
                });

                var current = selectedRow(table);
                if (!current || current.hidden) {
                    selectRow(table, visibleRows(table)[0], false);
                }
                updateOpenSelected(table);
            }

            document.querySelectorAll('[data-keyboard-table]').forEach(function(table) {
                var rows = rowsFor(table);
                selectRow(table, rows[0], false);

                rows.forEach(function(row) {
                    row.addEventListener('click', function(event) {
                        if (event.target.closest('a, button, input, select, textarea, label')) {
                            return;
                        }

                        selectRow(table, row, false);
                        window.location.href = row.getAttribute('data-href');
                    });

                    row.addEventListener('focus', function() {
                        selectRow(table, row, false);
                    });

                    row.addEventListener('keydown', function(event) {
                        var visible = visibleRows(table);
                        var index = visible.indexOf(row);

                        if (event.key === 'Enter' || event.key === ' ') {
                            event.preventDefault();
                            window.location.href = row.getAttribute('data-href');
                        } else if (event.key === 'ArrowDown' && index < visible.length - 1) {
                            event.preventDefault();
                            selectRow(table, visible[index + 1], true);
                        } else if (event.key === 'ArrowUp' && index > 0) {
                            event.preventDefault();
                            selectRow(table, visible[index - 1], true);
                        }
                    });
                });
            });

            document.querySelectorAll('[data-table-filter]').forEach(function(form) {
                form.addEventListener('submit', function(event) {
                    event.preventDefault();
                    applyFilter(form);
                });

                form.addEventListener('input', function() {
                    applyFilter(form);
                });

                form.addEventListener('change', function() {
                    applyFilter(form);
                });

                applyFilter(form);
            });
        })();
    </script>
{% endblock %}
