<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Syslog Viewer - FWServe</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: system-ui, -apple-system, sans-serif;
      background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
      min-height: 100vh; color: #e0e0e0; padding: 20px;
    }
    .container { max-width: 1200px; margin: 0 auto; }
    header { margin-bottom: 30px; }
    h1 { color: #00d4ff; margin-bottom: 5px; }
    .subtitle { color: #888; }
    .back-link { color: #00d4ff; text-decoration: none; }
    .back-link:hover { text-decoration: underline; }

    .panel {
      background: rgba(255,255,255,0.05);
      border: 1px solid rgba(255,255,255,0.1);
      border-radius: 12px; padding: 25px; margin-bottom: 20px;
    }
    .panel h2 { color: #00d4ff; margin-bottom: 15px; font-size: 1.2rem; }

    .controls {
      display: flex; gap: 15px; flex-wrap: wrap; align-items: flex-end;
    }
    .control-group { flex: 1; min-width: 150px; }
    .control-group label {
      display: block; margin-bottom: 5px; color: #aaa; font-size: 14px;
    }
    .control-group input {
      width: 100%; padding: 10px; border-radius: 6px;
      border: 1px solid rgba(255,255,255,0.2); background: rgba(0,0,0,0.3);
      color: #fff; font-size: 14px;
    }
    .control-group input::placeholder { color: #666; }

    .apply-btn {
      background: #00d4ff; color: #1a1a2e; padding: 10px 20px;
      border: none; border-radius: 6px; font-weight: 600;
      cursor: pointer; font-size: 14px; height: 42px;
    }
    .apply-btn:hover { background: #00b8e6; }

    .messages-container {
      background: rgba(0,0,0,0.3);
      border-radius: 8px;
      padding: 15px;
      max-height: 600px;
      overflow-y: auto;
      font-family: monospace;
      font-size: 13px;
      line-height: 1.6;
    }
    .message-line {
      padding: 4px 0;
      border-bottom: 1px solid rgba(255,255,255,0.05);
    }
    .message-line:last-child { border-bottom: none; }
    .msg-timestamp { color: #888; }
    .msg-host { color: #00d4ff; font-weight: 600; }
    .msg-severity { padding: 2px 6px; border-radius: 3px; font-size: 11px; }
    .sev-emerg, .sev-alert, .sev-crit { background: #dc3545; color: white; }
    .sev-err { background: #fd7e14; color: white; }
    .sev-warning { background: #ffc107; color: #1a1a2e; }
    .sev-notice { background: #17a2b8; color: white; }
    .sev-info { background: #28a745; color: white; }
    .sev-debug { background: #6c757d; color: white; }
    .msg-text { color: #ccc; }

    .status-bar {
      display: flex; justify-content: space-between; align-items: center;
      margin-top: 15px; font-size: 12px; color: #888;
    }
    .status-dot {
      display: inline-block; width: 8px; height: 8px;
      border-radius: 50%; margin-right: 6px;
    }
    .status-connected { background: #28a745; }
    .status-disconnected { background: #dc3545; }
  </style>
</head>
<body>
  <div class="container">
    <header>
      <a href="/" class="back-link">&larr; Back to Home</a>
      <h1>Syslog Viewer</h1>
      <p class="subtitle">Real-time syslog message viewer with filtering</p>
    </header>

    <div class="panel">
      <h2>Filters</h2>
      <div class="controls">
        <div class="control-group">
          <label for="host">Host</label>
          <input type="text" id="host" placeholder="Filter by hostname" />
        </div>
        <div class="control-group">
          <label for="severity">Severity</label>
          <input type="text" id="severity" placeholder="e.g. error, warning" />
        </div>
        <div class="control-group">
          <label for="query">Message Contains</label>
          <input type="text" id="query" placeholder="Search in messages" />
        </div>
        <button class="apply-btn" id="apply">Apply Filters</button>
      </div>
    </div>

    <div class="panel">
      <h2>Messages</h2>
      <div class="messages-container" id="messages">
        <p style="color: #888; font-style: italic;">Loading messages...</p>
      </div>
      <div class="status-bar">
        <span id="connectionStatus">
          <span class="status-dot status-disconnected"></span>
          Connecting...
        </span>
        <span id="messageCount">0 messages</span>
      </div>
    </div>
  </div>

  <script>
    const messagesEl = document.getElementById("messages");
    const hostInput = document.getElementById("host");
    const severityInput = document.getElementById("severity");
    const queryInput = document.getElementById("query");
    const applyButton = document.getElementById("apply");
    const connectionStatus = document.getElementById("connectionStatus");
    const messageCount = document.getElementById("messageCount");
    let eventSource = null;
    let count = 0;

    function getSeverityClass(sev) {
      const s = (sev || '').toLowerCase();
      if (s.includes('emerg')) return 'sev-emerg';
      if (s.includes('alert')) return 'sev-alert';
      if (s.includes('crit')) return 'sev-crit';
      if (s.includes('err')) return 'sev-err';
      if (s.includes('warn')) return 'sev-warning';
      if (s.includes('notice')) return 'sev-notice';
      if (s.includes('info')) return 'sev-info';
      if (s.includes('debug')) return 'sev-debug';
      return '';
    }

    function formatEntry(entry) {
      const sev = entry.severity_label || entry.severity || '';
      const sevClass = getSeverityClass(sev);
      return `<div class="message-line">
        <span class="msg-timestamp">${entry.timestamp || ''}</span>
        <span class="msg-host">${entry.host || ''}</span>
        <span class="msg-severity ${sevClass}">${sev}</span>
        <span class="msg-text">${entry.message || ''}</span>
      </div>`;
    }

    function updateStatus(connected) {
      const dot = connectionStatus.querySelector('.status-dot');
      dot.className = 'status-dot ' + (connected ? 'status-connected' : 'status-disconnected');
      connectionStatus.innerHTML = `<span class="status-dot ${connected ? 'status-connected' : 'status-disconnected'}"></span>` +
        (connected ? 'Connected (streaming)' : 'Disconnected');
    }

    function updateCount() {
      messageCount.textContent = count + ' message' + (count !== 1 ? 's' : '');
    }

    async function loadHistory() {
      const params = new URLSearchParams({
        host: hostInput.value,
        severity: severityInput.value,
        q: queryInput.value
      });
      try {
        const response = await fetch(`/syslog/history?${params.toString()}`);
        const data = await response.json();
        count = data.entries.length;
        if (count === 0) {
          messagesEl.innerHTML = '<p style="color: #888; font-style: italic;">No messages yet</p>';
        } else {
          messagesEl.innerHTML = data.entries.map(formatEntry).join('');
        }
        updateCount();
        messagesEl.scrollTop = messagesEl.scrollHeight;
      } catch (e) {
        messagesEl.innerHTML = '<p style="color: #dc3545;">Error loading messages</p>';
      }
    }

    function connectStream() {
      const params = new URLSearchParams({
        host: hostInput.value,
        severity: severityInput.value,
        q: queryInput.value
      });
      if (eventSource) {
        eventSource.close();
      }
      eventSource = new EventSource(`/syslog/stream?${params.toString()}`);

      eventSource.onopen = () => updateStatus(true);
      eventSource.onerror = () => updateStatus(false);

      eventSource.onmessage = (event) => {
        if (!event.data) return;
        try {
          const entry = JSON.parse(event.data);
          const html = formatEntry(entry);
          if (count === 0) {
            messagesEl.innerHTML = html;
          } else {
            messagesEl.innerHTML += html;
          }
          count++;
          updateCount();
          messagesEl.scrollTop = messagesEl.scrollHeight;
        } catch (e) {}
      };
    }

    applyButton.addEventListener("click", async () => {
      count = 0;
      await loadHistory();
      connectStream();
    });

    loadHistory().then(connectStream);
  </script>
</body>
</html>
