<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { Music2, RotateCcw } from 'lucide-svelte';
  import { useQueryClient } from '@tanstack/svelte-query';
  import { createMyQuarantineQuery, unflagTrack } from '$lib/api/quarantine';
  import { qk } from '$lib/api/queries';
  import type { LidarrQuarantineMineRow, LidarrQuarantineReason } from '$lib/api/types';
  import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
  import { coverUrl } from '$lib/media/covers';

  const client = useQueryClient();
  const queryStore = createMyQuarantineQuery();
  const query = $derived($queryStore);
  const rows = $derived((query.data ?? []) as LidarrQuarantineMineRow[]);

  const REASON_LABELS: Record<LidarrQuarantineReason, string> = {
    bad_rip:    'Bad rip',
    wrong_file: 'Wrong file',
    wrong_tags: 'Wrong tags',
    duplicate:  'Duplicate',
    other:      'Other'
  };

  function relativeTime(iso: string): string {
    const ms = Date.now() - new Date(iso).getTime();
    const days = Math.floor(ms / (24 * 3_600_000));
    if (days >= 1) return `${days}d ago`;
    const hours = Math.floor(ms / 3_600_000);
    if (hours >= 1) return `${hours}h ago`;
    const minutes = Math.floor(ms / 60_000);
    if (minutes >= 1) return `${minutes}m ago`;
    return 'just now';
  }

  async function onUnhide(trackID: string) {
    try {
      await unflagTrack(trackID);
      await client.invalidateQueries({ queryKey: qk.myQuarantine() });
    } catch {
      // Silent in v1; the SPA will refetch on next mount.
    }
  }
</script>

<svelte:head><title>{pageTitle('Library · Hidden')}</title></svelte:head>

<div class="space-y-6">
  <header class="space-y-1">
    <h2 class="font-display text-2xl font-medium text-text-primary">Hidden</h2>
    <p class="text-text-secondary">Tracks you've flagged as broken.</p>
  </header>

  {#if query.isError}
    <ApiErrorBanner error={query.error} onRetry={query.refetch} />
  {:else if !query.isPending && rows.length === 0}
    <p class="text-text-secondary">Nothing hidden yet.</p>
  {:else if rows.length > 0}
    <ul class="space-y-2">
      {#each rows as row (row.track_id)}
        <li class="flex items-start gap-3 rounded-md border border-border bg-surface p-3">
          <!-- Album art / fallback -->
          <div class="flex h-14 w-14 shrink-0 items-center justify-center rounded-md bg-surface-hover">
            {#if row.album_cover_art_path}
              <img
                src={coverUrl(row.album_id)}
                alt=""
                class="h-full w-full rounded-md object-cover"
                loading="lazy"
              />
            {:else}
              <Music2 size={24} strokeWidth={1} class="text-text-muted" />
            {/if}
          </div>
          <!-- Body -->
          <div class="flex flex-1 flex-col gap-1">
            <div class="flex items-center gap-2">
              <span class="kind-pill">Track</span>
              <span class="kind-pill">{REASON_LABELS[row.reason]}</span>
            </div>
            <div class="text-sm text-text-primary">{row.track_title}</div>
            <div class="text-xs text-text-secondary">
              by {row.artist_name} · {row.album_title} · flagged {relativeTime(row.created_at)}
            </div>
            {#if row.notes}
              <div class="text-xs italic text-text-secondary">{row.notes}</div>
            {/if}
          </div>
          <!-- Action -->
          <button
            type="button"
            aria-label={`Un-hide ${row.track_title}`}
            onclick={() => onUnhide(row.track_id)}
            class="inline-flex shrink-0 items-center gap-1 rounded-md border border-border px-2.5 py-1.5 text-sm text-text-secondary hover:text-text-primary"
          >
            <RotateCcw size={14} strokeWidth={1} />
            Un-hide
          </button>
        </li>
      {/each}
    </ul>
  {/if}
</div>

<style>
  .kind-pill {
    display: inline-flex;
    align-items: center;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    line-height: 14px;
    background: color-mix(in srgb, var(--fs-accent) 15%, transparent);
    color: var(--fs-accent);
  }
</style>
