<script lang="ts">
  import AppHeader from '$lib/components/AppHeader.svelte';
  import { debugLog } from '$lib/debuglog.svelte';

  const levelColor: Record<string, string> = {
    info: 'text-zinc-400',
    warn: 'text-amber-400',
    error: 'text-red-400',
  };

  function fmtTime(ts: number): string {
    const d = new Date(ts);
    return (
      d.toLocaleTimeString('de-DE') + '.' + String(d.getMilliseconds()).padStart(3, '0')
    );
  }

  // Anzahl noch nicht übertragener Einträge
  const offen = $derived(debugLog.entries.filter((e) => !e.sent).length);

  const uploadText = $derived(
    debugLog.uploadState === 'sending'
      ? 'sendet …'
      : debugLog.uploadState === 'error'
        ? 'Upload fehlgeschlagen'
        : offen > 0
          ? `${offen} noch nicht übertragen`
          : 'alle übertragen',
  );
</script>

<AppHeader title="Debug-Log" back subtitle={`${debugLog.entries.length} Einträge`} />

<div class="flex items-center gap-2 border-b border-zinc-800 bg-zinc-900 px-3 py-2">
  <button
    class="rounded bg-sky-600 px-3 py-1.5 text-sm text-white active:bg-sky-700 disabled:opacity-50"
    onclick={() => debugLog.flush()}
    disabled={debugLog.uploadState === 'sending'}
  >
    An Server senden
  </button>
  <span class="flex-1 text-xs text-zinc-500">{uploadText}</span>
  <button
    class="rounded bg-zinc-800 px-3 py-1.5 text-sm active:bg-zinc-700"
    onclick={() => debugLog.clear()}
  >
    Leeren
  </button>
</div>

<div class="flex-1 overflow-y-auto p-2 font-mono text-xs">
  {#if debugLog.entries.length === 0}
    <p class="p-4 text-center text-zinc-500">Keine Einträge.</p>
  {:else}
    {#each [...debugLog.entries].reverse() as e, i (i)}
      <div class="border-b border-zinc-800/50 py-1">
        <span class="text-zinc-600">{fmtTime(e.ts)}</span>
        <span class="break-words {levelColor[e.level]}"> {e.msg}</span>
      </div>
    {/each}
  {/if}
</div>
