<script>
  import { INPUT_TYPE_ICON } from "@src/lib/vars";
  import { FileText, X } from "@lucide/svelte";

  let { searches = [], onDelete = async () => {} } = $props();

  const STATUS_BADGE = {
    running:   "badge-warning",
    done:      "badge-success",
    cancelled: "badge-error",
  };


  function fmtDate(iso) {
    return new Date(iso).toLocaleString(undefined, {
      month: "short", day: "numeric",
      hour: "2-digit", minute: "2-digit",
    });
  }
</script>

{#if searches.length === 0}
  <p class="text-base-content/40 text-sm text-center py-8">No searches yet. Run one above.</p>
{:else}
  <div class="flex flex-col gap-2">
    {#each searches as s (s.id)}
      <a
        href={`/search/${s.id}`}
        class="card bg-base-200 hover:bg-base-300 transition-colors shadow-sm cursor-pointer"
      >
        <div class="card-body flex-row items-center gap-4 py-3 px-4">
          <div class="text-base-content/40 w-6 flex items-center justify-center shrink-0">
            {#each [INPUT_TYPE_ICON[s.input_type] ?? FileText] as Icon}
              <Icon size={16} />
            {/each}
          </div>
          <div class="flex flex-col min-w-0 flex-1">
            <span class="font-mono font-semibold truncate">{s.target}</span>
            <div class="flex items-center gap-1.5 flex-wrap text-xs text-base-content/50">
              <span>{s.input_type}</span>
              {#if s.profile}
                <span class="badge badge-outline badge-xs font-semibold">{s.profile}</span>
              {/if}
              <span>· {fmtDate(s.started_at)}</span>
            </div>
          </div>

          {#if s.status !== "running"}
            {@const total = (s.planned_tools ?? []).reduce((sum, t) => sum + (t.result_count ?? 0), 0)}
            {#if total > 0}
              <span class="text-xs font-mono text-base-content/50 shrink-0">{total} result{total !== 1 ? "s" : ""}</span>
            {/if}
          {/if}

          <span class="badge {STATUS_BADGE[s.status] ?? 'badge-ghost'} badge-sm shrink-0">
            {#if s.status === "running"}
              <span class="loading loading-ring loading-xs mr-1"></span>
            {/if}
            {s.status}
          </span>

          <button
            class="btn btn-ghost btn-xs text-base-content/30 hover:text-error shrink-0"
            onclick={(e) => { e.preventDefault(); onDelete(s.id); }}
            title="Delete"
          ><X size={14} /></button>
        </div>
      </a>
    {/each}
  </div>
{/if}
