<script>
  import { onMount } from 'svelte';
  import SparkCard from './lib/SparkCard.svelte';
  import QueueStats from './lib/QueueStats.svelte';

  let stats = $state({ pending: 0, blocked: 0, approved: 0, rejected: 0, shared: 0, local_only: 0, total: 0, needs_review: 0 });
  let sparks = $state([]);
  let activeTab = $state('pending');
  let loading = $state(true);
  let error = $state(null);

  const tabs = [
    { id: 'pending', label: 'Pending', countKey: 'pending' },
    { id: 'blocked', label: 'Blocked', countKey: 'blocked' },
    { id: 'approved', label: 'Approved', countKey: 'approved' },
  ];

  async function fetchStats() {
    try {
      const res = await fetch('/api/stats');
      if (!res.ok) throw new Error('Failed to fetch stats');
      stats = await res.json();
    } catch (e) {
      console.error('Failed to fetch stats:', e);
    }
  }

  async function fetchSparks(tab) {
    loading = true;
    error = null;
    try {
      const res = await fetch(`/api/sparks/${tab}`);
      if (!res.ok) throw new Error('Failed to fetch sparks');
      const data = await res.json();
      sparks = data.sparks || [];
    } catch (e) {
      error = e.message;
      sparks = [];
    } finally {
      loading = false;
    }
  }

  async function handleAction(sparkId, action, options = {}) {
    try {
      const res = await fetch(`/api/sparks/${sparkId}/${action}`, {
        method: action === 'delete' ? 'DELETE' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(options),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || 'Action failed');
      }
      // Refresh data
      await Promise.all([fetchStats(), fetchSparks(activeTab)]);
    } catch (e) {
      alert(`Error: ${e.message}`);
    }
  }

  async function handleEdit(sparkId, updates) {
    try {
      const res = await fetch(`/api/sparks/${sparkId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updates),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || 'Edit failed');
      }
      // Refresh data
      await Promise.all([fetchStats(), fetchSparks(activeTab)]);
    } catch (e) {
      alert(`Error: ${e.message}`);
    }
  }

  async function handleRevert(sparkId) {
    try {
      const res = await fetch(`/api/sparks/${sparkId}/revert`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || 'Revert failed');
      }
      // Refresh data
      await Promise.all([fetchStats(), fetchSparks(activeTab)]);
    } catch (e) {
      alert(`Error: ${e.message}`);
    }
  }

  function switchTab(tabId) {
    activeTab = tabId;
    fetchSparks(tabId);
  }

  onMount(() => {
    fetchStats();
    fetchSparks(activeTab);

    // Poll for updates every 5 seconds
    const interval = setInterval(() => {
      fetchStats();
      fetchSparks(activeTab);
    }, 5000);

    return () => clearInterval(interval);
  });
</script>

<div class="app">
  <header class="header">
    <div class="header-title">
      <div class="status-indicator"></div>
      <h1>SparkNet Review</h1>
    </div>
    <div class="header-meta">
      <span class="label">Security-First Approval Queue</span>
    </div>
  </header>

  <main class="container">
    <QueueStats {stats} />

    <div class="panel mt-4">
      <nav class="tabs">
        {#each tabs as tab}
          <button
            class="tab"
            class:active={activeTab === tab.id}
            onclick={() => switchTab(tab.id)}
          >
            {tab.label}
            {#if stats[tab.countKey] > 0}
              <span class="tab-count">{stats[tab.countKey]}</span>
            {/if}
          </button>
        {/each}
      </nav>

      <div class="panel-body">
        {#if loading}
          <div class="loading">
            <div class="loading-spinner"></div>
          </div>
        {:else if error}
          <div class="alert error">
            <strong>Error:</strong> {error}
          </div>
        {:else if sparks.length === 0}
          <div class="empty-state">
            <div class="empty-state-icon">
              {#if activeTab === 'pending'}
                &#x2713;
              {:else if activeTab === 'blocked'}
                &#x26A0;
              {:else}
                &#x2605;
              {/if}
            </div>
            <h3>No {activeTab} sparks</h3>
            <p class="text-muted">
              {#if activeTab === 'pending'}
                All sparks have been reviewed
              {:else if activeTab === 'blocked'}
                No security issues detected
              {:else}
                No sparks approved yet
              {/if}
            </p>
          </div>
        {:else}
          <div class="spark-list">
            {#each sparks as spark (spark.id)}
              <SparkCard
                {spark}
                showActions={activeTab !== 'approved'}
                onApprove={(id, opts) => handleAction(id, 'approve', opts)}
                onReject={(id) => handleAction(id, 'reject')}
                onLocalOnly={(id) => handleAction(id, 'local-only')}
                onDelete={(id) => handleAction(id, 'delete')}
                onEdit={handleEdit}
                onRevert={handleRevert}
              />
            {/each}
          </div>
        {/if}
      </div>
    </div>
  </main>
</div>

<style>
  .app {
    min-height: 100vh;
    background: var(--bg-primary);
  }

  .header-meta {
    display: flex;
    align-items: center;
    gap: 1rem;
  }

  .tab-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 1.25rem;
    height: 1.25rem;
    padding: 0 0.375rem;
    font-size: 0.7rem;
    font-weight: 600;
    background: var(--bg-elevated);
    margin-left: 0.5rem;
  }

  .tab.active .tab-count {
    background: var(--bg-primary);
    color: var(--green-dim);
  }

  .spark-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }
</style>
