<script lang="ts">
  import { onMount, onDestroy } from 'svelte';
  import { layout } from '$lib/stores/layout.svelte.js';
  import { setCanvas, startRenderLoop, stopRenderLoop } from '$lib/canvas/renderer.js';
  import { initInteractions, destroyInteractions, setContextMenuCallback } from '$lib/canvas/interactions.js';
  import { setImageUpdateCallback } from '$lib/pdf.js';

  let wrapperEl = $state<HTMLDivElement>(null!);
  let canvasEl = $state<HTMLCanvasElement>(null!);
  let pdfContainerEl = $state<HTMLDivElement>(null!);
  let contextMenu = $state<{ x: number; y: number; symId: number } | null>(null);
  let pdfNatW = $state(0);
  let pdfNatH = $state(0);
  let hasPdfImage = $state(false);

  onMount(() => {
    setCanvas(canvasEl);
    initInteractions(canvasEl, wrapperEl);
    startRenderLoop();

    setContextMenuCallback((x, y, symId) => {
      contextMenu = { x, y, symId };
    });

    setImageUpdateCallback((imgCanvas, natW, natH) => {
      pdfNatW = natW;
      pdfNatH = natH;

      if (pdfContainerEl) {
        pdfContainerEl.innerHTML = '';
        if (imgCanvas) {
          pdfContainerEl.appendChild(imgCanvas);
          hasPdfImage = true;
        } else {
          hasPdfImage = false;
        }
      }
    });

    // PDF restore is triggered by Toolbar after project/MCM are initialized

    function onClick() {
      contextMenu = null;
    }
    document.addEventListener('click', onClick);

    return () => {
      document.removeEventListener('click', onClick);
    };
  });

  onDestroy(() => {
    stopRenderLoop();
    destroyInteractions();
  });

  function handleDelete() {
    if (!contextMenu) return;
    if (layout.selectedIds.has(contextMenu.symId) && layout.selectedIds.size > 1) {
      layout.removeSelected();
    } else {
      layout.removeSymbol(contextMenu.symId);
    }
    contextMenu = null;
  }

  function handleDuplicate() {
    if (!contextMenu) return;
    if (layout.selectedIds.has(contextMenu.symId) && layout.selectedIds.size > 1) {
      layout.duplicateSelected();
    } else {
      layout.duplicateSymbol(contextMenu.symId);
    }
    contextMenu = null;
  }

  function handleMirror() {
    if (!contextMenu) return;
    if (layout.selectedIds.has(contextMenu.symId) && layout.selectedIds.size > 1) {
      layout.mirrorSelected();
    } else {
      layout.mirrorSymbol(contextMenu.symId);
    }
    contextMenu = null;
  }

  function handleHide() {
    if (!contextMenu) return;
    if (layout.selectedIds.has(contextMenu.symId) && layout.selectedIds.size > 1) {
      layout.hideSelected();
    } else {
      layout.toggleSymbolHidden(contextMenu.symId);
    }
    contextMenu = null;
  }

  function handleShowAll() {
    layout.showAllHidden();
    contextMenu = null;
  }

  function handleSetLabel() {
    if (!contextMenu) return;
    const sym = layout.symbols.find(s => s.id === contextMenu!.symId);
    if (!sym) return;
    const value = prompt('Set symbol ID (used as id and inkscape:label in export):', sym.label || '');
    if (value !== null) {
      sym.label = value;
      layout.markDirty();
      layout.saveMcmState();
    }
    contextMenu = null;
  }

  let pdfDisplayW = $derived(pdfNatW * layout.pdfScale);
  let pdfDisplayH = $derived(pdfNatH * layout.pdfScale);
</script>

<div class="canvas-wrapper" bind:this={wrapperEl}>
  <div
    class="canvas-transform"
    style="transform: translate({layout.panX}px, {layout.panY}px) scale({layout.zoomLevel}); transform-origin: 0 0;"
  >
    <!-- Dark background layer -->
    <div class="canvas-bg" style="width: {layout.canvasW}px; height: {layout.canvasH}px;"></div>

    <!-- PDF hi-res image: rendered once, CSS-scaled, stays crisp up to ~5x zoom -->
    <div
      class="pdf-background"
      class:editing={layout.editingBackground}
      class:hidden={!hasPdfImage}
      bind:this={pdfContainerEl}
      style="
        left: {layout.pdfOffsetX}px;
        top: {layout.pdfOffsetY}px;
        width: {pdfDisplayW}px;
        height: {pdfDisplayH}px;
      "
    ></div>

    <!-- Canvas: grid + symbols (transparent so PDF shows through) -->
    <canvas
      bind:this={canvasEl}
      width={layout.canvasW}
      height={layout.canvasH}
      style="width: {layout.canvasW}px; height: {layout.canvasH}px;{layout.editingBackground ? ' cursor: move;' : ''}"
    ></canvas>
  </div>
</div>

{#if contextMenu}
  <div
    class="context-menu"
    style="left: {contextMenu.x}px; top: {contextMenu.y}px;"
    role="menu"
  >
    <button class="context-menu-item" onclick={handleSetLabel} role="menuitem">Set ID</button>
    <button class="context-menu-item" onclick={handleMirror} role="menuitem">Mirror</button>
    <button class="context-menu-item" onclick={handleDuplicate} role="menuitem">Duplicate</button>
    <button class="context-menu-item" onclick={handleHide} role="menuitem">Hide</button>
    <button class="context-menu-item" onclick={handleDelete} role="menuitem">Delete</button>
    {#if layout.symbols.some(s => s.hidden) || layout.hiddenGroups.size > 0}
      <div class="context-menu-divider"></div>
      <button class="context-menu-item" onclick={handleShowAll} role="menuitem">Show All Hidden</button>
    {/if}
  </div>
{/if}

<style>
  .canvas-wrapper {
    flex: 1;
    overflow: hidden;
    background: #111;
    position: relative;
  }

  .canvas-transform {
    position: absolute;
  }

  .canvas-bg {
    position: absolute;
    top: 0;
    left: 0;
    background: #1e1e1e;
    border: 1px solid #333;
    z-index: 0;
  }

  .pdf-background {
    position: absolute;
    pointer-events: none;
    opacity: 0.35;
    overflow: hidden;
    z-index: 1;
  }

  .pdf-background.editing {
    opacity: 0.6;
  }

  .pdf-background.hidden {
    display: none;
  }

  .pdf-background :global(canvas) {
    width: 100% !important;
    height: 100% !important;
    display: block;
  }

  canvas {
    display: block;
    position: relative;
    z-index: 2;
  }

  .context-menu {
    position: fixed;
    background: #16213e;
    border: 1px solid #0f3460;
    border-radius: 6px;
    padding: 4px 0;
    z-index: 10000;
    min-width: 140px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
  }

  .context-menu-item {
    display: block;
    width: 100%;
    padding: 8px 16px;
    font-size: 12px;
    color: #e0e0e0;
    cursor: pointer;
    background: none;
    border: none;
    text-align: left;
    transition: background 0.15s;
  }

  .context-menu-item:hover {
    background: #e94560;
  }

  .context-menu-divider {
    height: 1px;
    background: #0f3460;
    margin: 4px 0;
  }
</style>
