<script lang="ts">
  interface LogEntry {
    timestamp: string;
    priority: string;
    message: string;
  }

  let logs = $state<LogEntry[]>([]);
  let loading = $state(true);
  let error = $state('');
  let filter = $state('');
  let hours = $state(1);

  async function loadLogs() {
    loading = true;
    error = '';
    try {
      const token = localStorage.getItem('token');
      const res = await fetch(`/api/logs?hours=${hours}&filter=${encodeURIComponent(filter)}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      if (res.ok) {
        const data = await res.json();
        logs = data.data || [];
      } else {
        error = 'Failed to load logs';
      }
    } catch (e) {
      error = 'Connection error';
      console.error('Failed to load logs:', e);
    } finally {
      loading = false;
    }
  }

  function getPriorityClass(priority: string): string {
    const p = priority.toLowerCase();
    if (p === 'err' || p === 'error') return 'text-error';
    if (p === 'warning' || p === 'warn') return 'text-warning';
    return '';
  }

  $effect(() => { loadLogs(); });
</script>

<div class="space-y-4">
  <div class="flex justify-between items-center flex-wrap gap-4">
    <h2 class="text-2xl font-bold">Mail Logs</h2>
    <div class="flex gap-2 items-center">
      <select class="select select-bordered" bind:value={hours} onchange={loadLogs}>
        <option value={1}>Last hour</option>
        <option value={6}>Last 6 hours</option>
        <option value={24}>Last 24 hours</option>
        <option value={48}>Last 48 hours</option>
      </select>
      <input 
        type="text" 
        class="input input-bordered" 
        bind:value={filter} 
        placeholder="Filter logs..." 
        onkeydown={(e) => e.key === 'Enter' && loadLogs()} 
      />
      <button class="btn btn-primary" onclick={loadLogs}>Refresh</button>
    </div>
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else if error}
    <div class="alert alert-error">
      <span>{error}</span>
    </div>
  {:else if logs.length === 0}
    <div class="card bg-base-100 shadow">
      <div class="card-body items-center text-center py-12">
        <p class="text-base-content/60">No log entries found.</p>
      </div>
    </div>
  {:else}
    <div class="bg-neutral text-neutral-content rounded-lg p-4 max-h-[600px] overflow-y-auto font-mono text-sm">
      {#each logs as entry}
        <div class="py-1 border-b border-neutral/20 last:border-0">
          <span class="text-neutral-content/50 mr-2">{entry.timestamp}</span>
          <span class="{getPriorityClass(entry.priority)} font-bold">[{entry.priority}]</span>
          <span class="ml-2">{entry.message}</span>
        </div>
      {/each}
    </div>
  {/if}
</div>
