<script>
  import { getGame, deleteGame, updateGame, bundleUrl, artworkUrl } from "../lib/api.js";
  import { push } from "../lib/router.js";

  let { id } = $props();

  let game = $state(null);
  let loading = $state(true);
  let editing = $state(false);
  let saving = $state(false);
  let error = $state("");

  let editTitle = $state("");
  let editYear = $state(0);
  let editGenre = $state("");
  let editDeveloper = $state("");
  let editPublisher = $state("");
  let editDescription = $state("");

  async function load() {
    loading = true;
    try {
      game = await getGame(id);
    } catch (e) {
      error = "Game not found";
    }
    loading = false;
  }

  function startEdit() {
    editTitle = game.title;
    editYear = game.year || 0;
    editGenre = game.genre || "";
    editDeveloper = game.developer || "";
    editPublisher = game.publisher || "";
    editDescription = game.description || "";
    editing = true;
  }

  async function saveEdit() {
    saving = true;
    try {
      game = await updateGame(id, {
        title: editTitle,
        year: editYear || undefined,
        genre: editGenre || undefined,
        developer: editDeveloper || undefined,
        publisher: editPublisher || undefined,
        description: editDescription || undefined,
      });
      editing = false;
    } catch (e) {
      error = e.message;
    }
    saving = false;
  }

  async function handleDelete() {
    if (!confirm(`Delete "${game.title}"? This cannot be undone.`)) return;
    try {
      await deleteGame(id);
      push("/");
    } catch (e) {
      error = e.message;
    }
  }

  function handlePlay() {
    push(`/play/${id}`);
  }

  $effect(() => { load(); });
</script>

{#if loading}
  <div class="loading">Loading...</div>
{:else if error && !game}
  <div class="error">{error}</div>
  <a href="#/" class="back-link">← Back to Library</a>
{:else if game}
  <div class="detail">
    <a href="#/" class="back-link">← Back to Library</a>

    <div class="detail-layout">
      <!-- Cover -->
      <div class="cover-section">
        {#if game.has_cover}
          <img src={`/games/${game.id}/cover.jpg`} alt={game.title} class="cover-img" />
        {:else}
          <div class="cover-placeholder">💾</div>
        {/if}
      </div>

      <!-- Info -->
      <div class="info-section">
        {#if editing}
          <input type="text" bind:value={editTitle} placeholder="Title" class="edit-title" />
          <div class="edit-row">
            <input type="number" bind:value={editYear} placeholder="Year" style="width:100px" />
            <input type="text" bind:value={editGenre} placeholder="Genre" style="flex:1" />
          </div>
          <div class="edit-row">
            <input type="text" bind:value={editDeveloper} placeholder="Developer" style="flex:1" />
            <input type="text" bind:value={editPublisher} placeholder="Publisher" style="flex:1" />
          </div>
          <textarea bind:value={editDescription} placeholder="Description" rows="4"></textarea>
          <div class="edit-actions">
            <button class="btn btn-primary" onclick={saveEdit} disabled={saving}>
              {saving ? "Saving..." : "Save"}
            </button>
            <button class="btn" onclick={() => editing = false}>Cancel</button>
          </div>
        {:else}
          <h1>{game.title}</h1>
          {#if game.year || game.genre}
            <div class="meta">
              {#if game.year}<span class="meta-item">{game.year}</span>{/if}
              {#if game.genre}<span class="meta-item">{game.genre}</span>{/if}
            </div>
          {/if}
          {#if game.developer}
            <p class="dev">by {game.developer}{game.publisher ? ` · ${game.publisher}` : ""}</p>
          {/if}
          {#if game.description}
            <p class="description">{game.description}</p>
          {/if}

          <div class="actions">
            {#if game.ready}
              <button class="btn btn-primary" onclick={handlePlay}>▶ Play</button>
            {/if}
            <button class="btn" onclick={startEdit}>✏ Edit</button>
            <button class="btn btn-danger" onclick={handleDelete}>✕ Delete</button>
          </div>
        {/if}
      </div>
    </div>
  </div>
{/if}

<style>
  .detail { padding: 32px 0; }
  .loading { text-align: center; padding: 60px; color: var(--text-dim); }
  .error { background: #331111; border: 1px solid #cc3333; color: #ff6666; padding: 12px; border-radius: var(--radius-sm); margin-bottom: 16px; }
  .back-link { display: inline-block; margin-bottom: 24px; color: var(--text-dim); }
  .back-link:hover { color: var(--phosphor); }
  .detail-layout { display: grid; grid-template-columns: 300px 1fr; gap: 32px; align-items: start; }
  @media (max-width: 640px) { .detail-layout { grid-template-columns: 1fr; } }
  .cover-section { border-radius: var(--radius); overflow: hidden; }
  .cover-img { width: 100%; border-radius: var(--radius); }
  .cover-placeholder { aspect-ratio: 3/4; background: var(--surface); display: flex; align-items: center; justify-content: center; font-size: 4rem; border-radius: var(--radius); }
  .info-section h1 { color: var(--phosphor); font-family: var(--font-mono); margin-bottom: 8px; }
  .meta { display: flex; gap: 8px; margin-bottom: 8px; }
  .meta-item { background: var(--surface-hover); color: var(--phosphor-dim); padding: 4px 12px; border-radius: 12px; font-size: 0.85rem; }
  .dev { color: var(--text-dim); margin-bottom: 16px; }
  .description { color: var(--text); line-height: 1.7; margin-bottom: 24px; }
  .actions { display: flex; gap: 8px; flex-wrap: wrap; }
  .edit-title { font-size: 1.5rem; margin-bottom: 12px; width: 100%; }
  .edit-row { display: flex; gap: 8px; margin-bottom: 8px; }
  .edit-actions { display: flex; gap: 8px; margin-top: 12px; }
  textarea { width: 100%; min-height: 100px; }
</style>