<script lang="ts">
  import { onMount, onDestroy } from 'svelte';
  import { uiStore } from '../../stores/ui';
  import { gameStore } from '../../stores/game';
  import { contentManager } from '../../services/content-manager';
  import { gameEngine } from '../../services/game-engine';
  import GameError from './GameError.svelte';
  
  let reloadTimer: any;
  let previousContent = '';
  let isInitialized = false;
  let lastRestartTime = 0;
  let reloadInProgress = false;

  $: if ($contentManager.content !== previousContent && $gameStore.isAutoRunning && isInitialized) {
    previousContent = $contentManager.content;
    clearTimeout(reloadTimer);

    const now = Date.now();
    // Ensure minimum time between reloads and no overlapping reloads
    if (now - lastRestartTime >= 2000 && !reloadInProgress) {
      reloadTimer = setTimeout(async () => {
        const currentTime = Date.now();
        if (currentTime - lastRestartTime < 2000 || $gameStore.isStarting || reloadInProgress) {
          return;
        }
        lastRestartTime = currentTime;
        reloadInProgress = true;

        try {
          await gameEngine.startFromDocument($contentManager.content);
        } finally {
          // Ensure we always reset the flag
          reloadInProgress = false;
        }
      }, 1500);
    }
  }

  onMount(async () => {
    previousContent = $contentManager.content;

    setTimeout(async () => {
      if (!$gameStore.instance && $gameStore.isAutoRunning && $contentManager.content) {
        await gameEngine.startFromDocument($contentManager.content);
      }
      isInitialized = true;
    }, 400);
  });
  
  onDestroy(() => {
    clearTimeout(reloadTimer);
    gameEngine.stop();
  });
</script>

<div class="game-section">
  {#if $uiStore.error}
    <GameError error={$uiStore.error} />
  {/if}
  
  <div id="world-container" style="display: none;"></div>
  
  <div class="canvas-container">
    <canvas id="game-canvas"></canvas>
  </div>
</div>

<style>
  .game-section {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .canvas-container {
    flex: 1;
    position: relative;
    background: radial-gradient(ellipse at center, rgba(124, 152, 133, 0.02) 0%, transparent 70%);
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  #game-canvas {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: contain;
    pointer-events: auto;
    user-select: none;
  }
</style>