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

  let { id } = $props();

  let game = $state(null);
  let loading = $state(true);
  let error = $state("");
  let booting = $state(false);
  let running = $state(false);
  let started = false;

  let dosContainer;
  let dosCI = null;

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

  async function startEmulator() {
    if (!dosContainer || !game?.ready || running || started) return;
    started = true;
    booting = true;

    // Load js-dos CSS
    const link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = "https://v8.js-dos.com/latest/js-dos.css";
    document.head.appendChild(link);

    // Load js-dos script from CDN if not already loaded
    if (!window.Dos) {
      try {
        await new Promise((resolve, reject) => {
          const s = document.createElement("script");
          s.src = "https://v8.js-dos.com/latest/js-dos.js";
          s.onload = resolve;
          s.onerror = reject;
          document.head.appendChild(s);
        });
      } catch {
        error = "Failed to load emulator. Check your internet connection.";
        booting = false;
        return;
      }
    }

    // Start the DOS emulator
    try {
      const url = bundleUrl(game);
      if (!url || !window.Dos) {
        throw new Error("Failed to resolve game bundle");
      }
      dosCI = await window.Dos(dosContainer, { url });
      running = true;
    } catch (e) {
      error = "Failed to start emulator: " + e.message;
    }
    booting = false;
  }

  function stopEmulator() {
    // Kill the emulator process
    if (dosCI) {
      try { dosCI.exit(); } catch (_) {}
      dosCI = null;
    }
    if (dosContainer) {
      dosContainer.innerHTML = "";
    }
    running = false;
    // Navigate back to game detail
    push(`/game/${game.id}`);
  }

  // Load game data on mount
  $effect(() => { load(); });

  // Auto-start emulator once game data and DOM are ready
  $effect(() => {
    if (game?.ready && dosContainer && !started) {
      startEmulator();
    }
  });

  // Cleanup on unmount (navigating away, browser back, etc.)
  $effect(() => {
    return () => {
      if (dosCI) {
        try { dosCI.exit(); } catch (_) {}
        dosCI = null;
      }
      if (dosContainer) {
        dosContainer.innerHTML = "";
      }
      running = false;
    };
  });
</script>

{#if loading}
  <div class="loading">Loading...</div>
{:else if error}
  <div class="play-page">
    <a href="#/" class="back-link">← Back to Library</a>
    <div class="error-msg">{error}</div>
  </div>
{:else if game}
  <div class="play-page">
    <!-- Top bar -->
    <div class="play-header">
      <button class="link-button" onclick={stopEmulator}>← {game.title}</button>
      {#if running}
        <button class="btn stop-btn" onclick={stopEmulator}>⏹ Stop</button>
      {/if}
    </div>

    <!-- Booting state -->
    {#if booting && !running}
      <div class="booting">
        <div class="booting-icon">⚙️</div>
        <h2>{game.title}</h2>
        <p>Starting emulator...</p>
        <p class="save-hint">💾 Game saves are stored automatically in your browser</p>
      </div>
    {/if}

    <!-- Emulator canvas -->
    {#if running}
      <div class="emulator-wrapper">
        <div bind:this={dosContainer} class="dos-container"></div>
      </div>
    {/if}

    <!-- Empty state (shouldn't normally show) -->
    {#if !booting && !running}
      <div class="booting">
        <div class="booting-icon">🕹️</div>
        <h2>{game.title}</h2>
        {#if game.ready}
          <button class="btn btn-primary" onclick={startEmulator}>▶ Start Game</button>
        {:else}
          <p>This game is not ready yet.</p>
        {/if}
        <p class="save-hint">💾 Game saves are stored automatically in your browser</p>
      </div>
    {/if}
  </div>
{/if}

<style>
  .play-page { padding: 16px 0; }
  .loading {
    text-align: center;
    padding: 60px;
    color: var(--text-dim);
  }
  .error-msg {
    background: #331111;
    border: 1px solid #cc3333;
    color: #ff6666;
    padding: 12px 16px;
    border-radius: var(--radius-sm);
    margin-top: 16px;
  }
  .back-link {
    display: inline-block;
    color: var(--text-dim);
    font-size: 0.9rem;
  }
  .back-link:hover { color: var(--phosphor); }
  .link-button {
    background: none;
    border: none;
    color: var(--text-dim);
    font-size: 0.9rem;
    cursor: pointer;
    padding: 0;
    font-family: var(--font-sans);
  }
  .link-button:hover { color: var(--phosphor); }
  .play-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }
  .stop-btn {
    border-color: #cc3333;
    color: #ff4444;
  }
  .stop-btn:hover {
    background: #331111;
    box-shadow: 0 0 12px #331111;
  }

  /* Booting / transitional state */
  .booting {
    text-align: center;
    padding: 60px 20px;
    border: 1px dashed var(--border);
    border-radius: var(--radius);
  }
  .booting-icon { font-size: 3rem; margin-bottom: 16px; }
  .booting h2 {
    color: var(--phosphor);
    font-family: var(--font-mono);
    margin-bottom: 8px;
  }
  .booting p { color: var(--text-dim); }
  .save-hint {
    display: inline-block;
    margin-top: 16px;
    padding: 6px 16px;
    border-radius: 12px;
    background: var(--phosphor-burn);
    color: var(--phosphor-dim);
    font-size: 0.85rem;
  }

  /* Emulator */
  .emulator-wrapper {
    background: #000;
    border-radius: var(--radius);
    overflow: hidden;
    border: 1px solid var(--border);
  }
  .dos-container {
    width: 100%;
    aspect-ratio: 4/3;
    max-height: 80vh;
  }
  .dos-container :global(canvas) {
    width: 100% !important;
    height: 100% !important;
  }
</style>
