<%- include("partials/layout-top", { title }) %>
<%
  const filters = logFilters || { range: '86400000', level: 'all', limit: '50', source: 'all', category: 'all', search: '' };
  const summary = logSummary || { total: 0, levels: { error: 0, warn: 0, info: 0, debug: 0 } };
  const facets = logFacets || { sources: [], categories: [] };
  const retention = logRetention || { maxAgeDays: 30, maxEntries: 100000 };
%>
<section class="card">
  <%- include("partials/page-header", {
    eyebrow: "Administration",
    pageTitle: "System logs",
    description: "Review activity from Lumi Core, plugins, commands, integrations, and administrator actions. Sensitive values are removed before entries are stored."
  }) %>

  <div class="dashboard-metric-grid log-summary-grid" aria-label="Log totals for the selected filters">
    <div><span>Matching entries</span><strong data-log-total><%= summary.total %></strong></div>
    <div><span>Errors</span><strong data-log-count="error"><%= summary.levels.error %></strong></div>
    <div><span>Warnings</span><strong data-log-count="warn"><%= summary.levels.warn %></strong></div>
    <div><span>Information</span><strong data-log-count="info"><%= summary.levels.info %></strong></div>
    <div><span>Debug</span><strong data-log-count="debug"><%= summary.levels.debug %></strong></div>
  </div>

  <form method="get" action="/admin/logs" class="log-controls" data-log-filter-form>
    <label>
      <span>Search all matching logs</span>
      <input
        class="table-search"
        type="search"
        name="q"
        value="<%= filters.search || '' %>"
        placeholder="Message, details, event, or request ID"
        aria-label="Search logs"
        data-log-search
      />
    </label>
    <label>
      <span>Severity</span>
      <select class="table-search" name="level" data-log-level aria-label="Filter log severity">
        <option value="all" <%= filters.level === 'all' ? 'selected' : '' %>>All severities</option>
        <option value="error" <%= filters.level === 'error' ? 'selected' : '' %>>Error</option>
        <option value="warn" <%= filters.level === 'warn' ? 'selected' : '' %>>Warning</option>
        <option value="info" <%= filters.level === 'info' ? 'selected' : '' %>>Information</option>
        <option value="debug" <%= filters.level === 'debug' ? 'selected' : '' %>>Debug</option>
      </select>
    </label>
    <label>
      <span>Component</span>
      <select class="table-search" name="source" data-log-source aria-label="Filter log component">
        <option value="all">All components</option>
        <% if (filters.source !== 'all' && !facets.sources.some((item) => item.value === filters.source)) { %>
          <option value="<%= filters.source %>" selected><%= filters.source %> (0)</option>
        <% } %>
        <% facets.sources.forEach((item) => { %>
          <option value="<%= item.value %>" <%= filters.source === item.value ? 'selected' : '' %>><%= item.value %> (<%= item.count %>)</option>
        <% }) %>
      </select>
    </label>
    <label>
      <span>Activity type</span>
      <select class="table-search" name="category" data-log-category aria-label="Filter log activity type">
        <option value="all">All activity types</option>
        <% if (filters.category !== 'all' && !facets.categories.some((item) => item.value === filters.category)) { %>
          <option value="<%= filters.category %>" selected><%= filters.category %> (0)</option>
        <% } %>
        <% facets.categories.forEach((item) => { %>
          <option value="<%= item.value %>" <%= filters.category === item.value ? 'selected' : '' %>><%= item.value %> (<%= item.count %>)</option>
        <% }) %>
      </select>
    </label>
    <label>
      <span>Range</span>
      <select class="table-search" name="range" data-log-range aria-label="Filter by time range">
        <option value="all" <%= filters.range === 'all' ? 'selected' : '' %>>All time</option>
        <option value="<%= 5 * 60 * 1000 %>" <%= filters.range === `${5 * 60 * 1000}` ? 'selected' : '' %>>Last 5 minutes</option>
        <option value="<%= 60 * 60 * 1000 %>" <%= filters.range === `${60 * 60 * 1000}` ? 'selected' : '' %>>Last hour</option>
        <option value="<%= 24 * 60 * 60 * 1000 %>" <%= filters.range === `${24 * 60 * 60 * 1000}` ? 'selected' : '' %>>Last 24 hours</option>
        <option value="<%= 7 * 24 * 60 * 60 * 1000 %>" <%= filters.range === `${7 * 24 * 60 * 60 * 1000}` ? 'selected' : '' %>>Last week</option>
        <option value="<%= 30 * 24 * 60 * 60 * 1000 %>" <%= filters.range === `${30 * 24 * 60 * 60 * 1000}` ? 'selected' : '' %>>Last month</option>
      </select>
    </label>
    <label>
      <span>Entries shown</span>
      <select class="table-search" name="limit" data-log-limit aria-label="Limit log entries">
        <% [50, 100, 250, 500].forEach((amount) => { %>
          <option value="<%= amount %>" <%= filters.limit === `${amount}` ? 'selected' : '' %>><%= amount %> most recent</option>
        <% }) %>
      </select>
    </label>
    <div class="filter-actions button-group">
      <button type="submit" class="button">Apply filters</button>
      <a class="button subtle" href="/admin/logs">Reset</a>
      <button type="button" class="button subtle" data-log-download>Download</button>
    </div>
  </form>

  <div class="log-live-status" data-log-live-status role="status" aria-live="polite">
    <span class="status-indicator">Connecting to live updates</span>
    <button type="button" class="button subtle" data-log-live-refresh hidden>Show new entries</button>
  </div>

  <div class="log-window" data-log-list data-log-limit-value="<%= filters.limit %>">
    <% if (!logs || !logs.length) { %>
      <p class="hint" data-log-empty>No logs match these filters.</p>
    <% } else { %>
      <% logs.forEach((entry) => { %>
      <details
        class="log-entry level-<%= entry.level %>"
        data-log-entry
        data-level="<%= entry.level %>"
        data-source="<%= entry.source || 'core' %>"
        data-category="<%= entry.category || 'general' %>"
        data-timestamp="<%= entry.created_at %>"
        data-search="<%= `${entry.message} ${entry.details || ''} ${entry.source || ''} ${entry.category || ''} ${entry.event || ''} ${entry.request_id || ''}`.toLowerCase() %>"
      >
        <summary>
          <span class="log-marker" aria-hidden="true"></span>
          <span class="log-message"><%= entry.message %></span>
          <span class="log-scope-pill"><%= entry.source || 'core' %></span>
          <span class="log-level-pill"><%= entry.level %></span>
          <span class="log-time"><%= new Date(entry.created_at).toLocaleString() %></span>
        </summary>
        <div class="log-entry-meta">
          <span><strong>Activity:</strong> <%= entry.category || 'general' %></span>
          <% if (entry.event) { %><span><strong>Event:</strong> <%= entry.event %></span><% } %>
          <% if (entry.request_id) { %><span><strong>Request ID:</strong> <code><%= entry.request_id %></code></span><% } %>
        </div>
        <% if (entry.details) { %>
          <pre class="log-details"><%= entry.details %></pre>
        <% } else { %>
          <div class="log-details empty">No additional details.</div>
        <% } %>
      </details>
      <% }) %>
    <% } %>
  </div>

  <details class="lumi-expandable-settings log-storage-settings">
    <summary><span><strong>Log storage</strong><span class="hint">Retention limits and automatic cleanup</span></span></summary>
    <div class="lumi-expandable-body">
      <p class="hint">Lumi removes entries exceeding either limit during startup and whenever these settings are saved. Plugin data and other application records are unaffected.</p>
      <form method="post" action="/admin/logs/retention" class="form-grid compact-grid">
        <div class="field">
          <label for="log-retention-days">Keep logs for up to</label>
          <input id="log-retention-days" type="number" name="max_age_days" min="1" max="3650" value="<%= retention.maxAgeDays %>" required />
        </div>
        <div class="field">
          <label for="log-retention-entries">Maximum stored entries</label>
          <input id="log-retention-entries" type="number" name="max_entries" min="1000" max="1000000" step="1000" value="<%= retention.maxEntries %>" required />
        </div>
        <div class="field form-actions"><button type="submit" class="button">Save storage settings</button></div>
      </form>
    </div>
  </details>
</section>

<div class="modal-backdrop" data-log-modal aria-hidden="true">
  <div class="modal">
    <div class="modal-header">
      <h3>Download logs</h3>
      <button type="button" class="icon-button" data-modal-close aria-label="Close">
        <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6l-12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" /></svg>
      </button>
    </div>
    <form method="get" action="/admin/logs/download" class="form-grid">
      <input type="hidden" name="source" value="<%= filters.source %>" />
      <input type="hidden" name="category" value="<%= filters.category %>" />
      <input type="hidden" name="q" value="<%= filters.search || '' %>" />
      <div class="field">
        <label>Timespan</label>
        <select name="range">
          <option value="all">All time</option>
          <option value="<%= 5 * 60 * 1000 %>">Last 5 minutes</option>
          <option value="<%= 60 * 60 * 1000 %>">Last hour</option>
          <option value="<%= 24 * 60 * 60 * 1000 %>" selected>Last 24 hours</option>
          <option value="<%= 7 * 24 * 60 * 60 * 1000 %>">Last week</option>
          <option value="<%= 30 * 24 * 60 * 60 * 1000 %>">Last month</option>
        </select>
      </div>
      <div class="field full">
        <label>Severities</label>
        <div class="checkbox-grid">
          <% ['error', 'warn', 'info', 'debug'].forEach((level) => { %>
            <label><input type="checkbox" name="level" value="<%= level %>" /> <%= level === 'warn' ? 'Warning' : level.charAt(0).toUpperCase() + level.slice(1) %></label>
          <% }) %>
        </div>
        <p class="hint">Leave unchecked for all severities. Current component, activity, and search filters are retained.</p>
      </div>
      <div class="field">
        <label>Entries</label>
        <select name="limit"><option value="50">50 most recent</option><option value="100">100 most recent</option><option value="250">250 most recent</option><option value="500">500 most recent</option><option value="all">All matching entries</option></select>
      </div>
      <div class="field">
        <label>File format</label>
        <select name="format"><option value="txt">Readable text</option><option value="jsonl">Structured JSON lines</option></select>
      </div>
      <div class="modal-actions">
        <button type="button" class="button subtle" data-modal-close>Cancel</button>
        <button type="submit" class="button">Download</button>
      </div>
    </form>
  </div>
</div>
<%- include("partials/layout-bottom") %>
