<script setup lang="ts">
import { onMounted } from "vue";
import { useTrashStore } from "@/stores/trash";
import { relativeTime } from "@/composables/useRelativeTime";

const store = useTrashStore();

async function purge(batchId: string) {
  if (!confirm("Permanently delete this? This cannot be undone.")) return;
  await store.purge(batchId);
}

async function empty() {
  if (!store.batches.length) return;
  if (!confirm("Permanently delete everything in the trash? This cannot be undone.")) return;
  await store.emptyTrash();
}

onMounted(() => store.fetchTrash());
</script>

<template>
  <main class="trash-page">
    <header class="trash-header">
      <h1>Trash</h1>
      <button
        v-if="store.batches.length"
        class="btn-ghost btn-compact"
        @click="empty"
      >Empty trash</button>
    </header>

    <p class="trash-note">
      Deleted items are kept here and can be restored. They're permanently removed
      after the retention window set in Settings.
    </p>

    <div v-if="store.loading" class="trash-loading">Loading…</div>

    <p v-else-if="!store.batches.length" class="trash-empty">Trash is empty.</p>

    <ul v-else class="batch-list">
      <li v-for="b in store.batches" :key="b.batch_id" class="batch">
        <div class="batch-main">
          <div class="batch-summary">
            {{ b.summary }}
            <span v-if="b.count > 1" class="batch-count">+ {{ b.count - 1 }} item{{ b.count - 1 === 1 ? '' : 's' }}</span>
          </div>
          <div class="batch-meta">
            deleted {{ b.deleted_at ? relativeTime(b.deleted_at) : '' }}
            <span class="batch-types">· {{ b.items.map(i => i.type).join(', ') }}</span>
          </div>
        </div>
        <div class="batch-actions">
          <button class="btn-ghost btn-compact btn-restore" @click="store.restore(b.batch_id)">Restore</button>
          <button class="btn-ghost btn-compact btn-purge" @click="purge(b.batch_id)">Delete permanently</button>
        </div>
      </li>
    </ul>
  </main>
</template>

<style scoped>
.trash-page { max-width: 900px; margin: 0 auto; padding: 1.5rem; }
.trash-header { display: flex; align-items: center; justify-content: space-between; }
.trash-header h1 { font-family: Fraunces, serif; font-style: italic; margin: 0; }
.batch-summary { font-weight: 500; }
.batch-count { opacity: 0.6; font-weight: 400; font-size: 0.9em; margin-left: 0.35rem; }
.batch-meta { font-size: 0.82em; opacity: 0.6; margin-top: 0.25rem; }
.batch-actions { display: flex; gap: 0.5rem; flex-shrink: 0; }
.batch-actions button { border-radius: 6px; padding: 0.35rem 0.7rem; cursor: pointer; border: 1px solid var(--fs-border-color); background: none; color: inherit; }
.btn-restore:hover { border-color: var(--fs-action-primary); color: var(--fs-action-primary); }
.btn-purge:hover { border-color: var(--fs-action-destructive); color: var(--fs-action-destructive); }
</style>
