{% extends "base.html" %}

{% block title %}Dashboard — Langfuse Lens{% endblock %}
{% block page_title %}<span data-i18n="dashboard.title">Dashboard</span>{% endblock %}

{% block content %}
<div class="flex mb-16" style="align-items:center;gap:12px">
  <label class="form-label" style="margin:0;white-space:nowrap" data-i18n="dashboard.langfuseProject">Langfuse Project:</label>
  <select class="form-select" id="dash-project" style="max-width:240px">
    <option value="" data-i18n="dashboard.allProjects">All Projects</option>
  </select>
</div>
<div class="grid-4 mb-20" id="stats-grid">
  <div class="stat-card">
    <div class="stat-label" data-i18n="dashboard.serverStatus">Server Status</div>
    <div class="stat-value" id="stat-status">-</div>
    <div class="stat-detail" id="stat-uptime"></div>
  </div>
  <div class="stat-card">
    <div class="stat-label" data-i18n="dashboard.totalChats">Total Chats</div>
    <div class="stat-value" id="stat-chats">-</div>
  </div>
  <div class="stat-card">
    <div class="stat-label" data-i18n="dashboard.auditEvents">Audit Events</div>
    <div class="stat-value" id="stat-audit">-</div>
  </div>
  <div class="stat-card">
    <div class="stat-label" data-i18n="dashboard.llmKeys">LLM Keys</div>
    <div class="stat-value" id="stat-keys">-</div>
    <div class="stat-detail" id="stat-keys-detail"></div>
  </div>
</div>

<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title" data-i18n="dashboard.recentChats">Recent Chats</div>
      <div class="card-subtitle" data-i18n="dashboard.latestExecutions">Latest agent executions</div>
    </div>
    <a href="/chat" class="btn btn-sm btn-secondary" data-i18n="common.viewAll">View All</a>
  </div>
  <div id="recent-chats">
    <div class="loading-center"><div class="spinner"></div></div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script type="module">
import { api } from '/static/js/api.js';
import { toast, formatDate, timeAgo, statusBadge, showLoading, showEmpty, escapeHtml, t } from '/static/js/common.js';

async function loadStats() {
  try {
    const [health, keys] = await Promise.all([
      api.get('/health'),
      api.get('/api/settings/llm-keys'),
    ]);

    document.getElementById('stat-status').textContent = health.status === 'ok' ? 'OK' : health.status;
    document.getElementById('stat-status').style.color = health.status === 'ok' ? 'var(--success)' : 'var(--danger)';
    if (health.uptime_seconds) {
      const h = Math.floor(health.uptime_seconds / 3600);
      const m = Math.floor((health.uptime_seconds % 3600) / 60);
      document.getElementById('stat-uptime').textContent = t('dashboard.uptime', { h, m });
    }

    const present = keys.present || {};
    const setCount = Object.values(present).filter(Boolean).length;
    const total = Object.keys(present).length;
    document.getElementById('stat-keys').textContent = `${setCount}/${total}`;
    document.getElementById('stat-keys-detail').textContent =
      Object.entries(present).filter(([,v]) => v).map(([k]) => k.replace(/_api_key|_base_url/i, '')).join(', ') || 'None';

  } catch (e) {
    document.getElementById('stat-status').textContent = 'ERR';
    document.getElementById('stat-status').style.color = 'var(--danger)';
  }

  try {
    const threads = await api.get('/api/chat/threads?limit=1');
    const items = threads.data || [];
    document.getElementById('stat-chats').textContent = items.length > 0 ? items.length + '+' : '0';
  } catch { document.getElementById('stat-chats').textContent = '0'; }

  try {
    const audit = await api.get('/api/admin/audit-logs?size=1');
    document.getElementById('stat-audit').textContent = audit.data?.total || '0';
  } catch { document.getElementById('stat-audit').textContent = '-'; }
}

async function loadRecentChats() {
  const el = document.getElementById('recent-chats');
  try {
    const data = await api.get('/api/chat/threads?limit=5');
    const items = data.data || [];
    if (items.length === 0) {
      showEmpty(el, t('dashboard.noChatsYet'));
      return;
    }
    el.innerHTML = `
      <div class="table-wrap">
        <table>
          <thead><tr><th>${t('dashboard.id')}</th><th>${t('common.message')}</th><th>${t('common.created')}</th></tr></thead>
          <tbody>
            ${items.map(r => `
              <tr>
                <td class="td-mono">${escapeHtml(r.thread_id?.slice(0, 16) || '-')}</td>
                <td>${r.msg_count} messages</td>
                <td class="text-muted text-sm">${timeAgo(r.last_at)}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
  } catch {
    showEmpty(el, t('dashboard.couldNotLoadChats'));
  }
}

/* ---- Load Langfuse projects for filter ---- */
async function loadDashProjects() {
  const sel = document.getElementById('dash-project');
  try {
    const data = await api.get('/api/users/me/langfuse-projects');
    const projects = data.data || [];
    projects.forEach(p => {
      const star = p.is_default ? '★ ' : '';
      const opt = document.createElement('option');
      opt.value = p.id;
      opt.textContent = `${star}${p.name}`;
      sel.appendChild(opt);
    });
    const saved = localStorage.getItem('dash_project_id');
    if (saved && sel.querySelector(`option[value="${saved}"]`)) {
      sel.value = saved;
    }
  } catch {}
  sel.addEventListener('change', () => {
    localStorage.setItem('dash_project_id', sel.value);
  });
}

loadDashProjects();
loadStats();
loadRecentChats();
</script>
{% endblock %}
