<script>
  import { goto } from '$app/navigation';
  import { onMount } from 'svelte';
  import Card from '$lib/Card.svelte';

  let cards = $state([]);
  let loading = $state(false);

  onMount(() => {
    if (!localStorage.getItem('token')) goto('/auth');
  });

  async function openPack() {
    loading = true;
    try {
      const res = await fetch('http://localhost:8000/pack/10', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      if (res.status === 401) { goto('/auth'); return; }
      cards = await res.json();
    } catch (e) {
      console.error(e);
    } finally {
      loading = false;
    }
  }
</script>

<main>
  <button onclick={openPack} disabled={loading}>
    {loading ? "Opening..." : "Open Pack"}
  </button>

  <div class="pack">
    {#each cards as card}
      <Card {card} />
    {/each}
  </div>
</main>

<style>
  main {
    min-height: 100vh;
    background: #887859;
    padding: 2rem;
  }

  button {
    display: block;
    margin: 0 auto 2rem;
    padding: 10px 28px;
    font-family: 'Cinzel', serif;
    font-size: 14px;
    background: #2e1c05;
    color: #f0d080;
    border: 1px solid #6b4c1e;
    border-radius: 6px;
    cursor: pointer;
  }

  button:hover:not(:disabled) {
    background: #3d2507;
  }

  .pack {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    justify-content: center;
  }
</style>