<script lang="ts">
  import { layout } from '$lib/stores/layout.svelte.js';
  import { exportSVG, exportJSON, loadLayoutJSON, loadLayoutSVG } from '$lib/export.js';
  import { loadPdfFile, loadPdfFromPath, pdfZoomIn, pdfZoomOut, removePdf, toggleEditBackground, restorePdf } from '$lib/pdf.js';
  import { discoverProjects } from '$lib/projects.js';
  import { onMount } from 'svelte';
  import Palette from './Palette.svelte';

  let importFileEl = $state<HTMLInputElement>(null!);
  let pdfFileEl = $state<HTMLInputElement>(null!);
  let toolbarCollapsed = $state(false);

  let pdfOpen = $state(false);
  let settingsOpen = $state(false);

  onMount(async () => {
    const projects = await discoverProjects();
    const savedProject = localStorage.getItem('scada_lastProject');
    const savedMcm = localStorage.getItem('scada_lastMcm');

    if (projects.length > 0) {
      layout.projects = projects;
      const proj = (savedProject && projects.find(p => p.name === savedProject)) || projects[0];
      layout.currentProject = proj.name;
      const mcm = (savedMcm && proj.mcms.find(m => m.name === savedMcm)) || proj.mcms[0];
      if (mcm) layout.currentMcm = mcm.name;
      layout.loadMcmState();
    } else {
      layout.currentProject = savedProject || 'default';
      layout.currentMcm = savedMcm || 'MCM01';
      layout.loadMcmState();
    }
    localStorage.setItem('scada_lastProject', layout.currentProject);
    localStorage.setItem('scada_lastMcm', layout.currentMcm);
    await restorePdf();
  });

  function onProjectChange(e: Event) {
    layout.saveMcmState();
    const val = (e.target as HTMLSelectElement).value;
    layout.currentProject = val;
    const proj = layout.projects.find(p => p.name === val);
    if (proj && proj.mcms.length > 0) {
      layout.currentMcm = proj.mcms[0].name;
    }
    localStorage.setItem('scada_lastProject', layout.currentProject);
    localStorage.setItem('scada_lastMcm', layout.currentMcm);
    layout.loadMcmState();
    autoLoadPdf();
  }

  function onMcmChange(e: Event) {
    layout.saveMcmState();
    layout.currentMcm = (e.target as HTMLSelectElement).value;
    localStorage.setItem('scada_lastMcm', layout.currentMcm);
    layout.loadMcmState();
    autoLoadPdf();
  }

  async function autoLoadPdf() {
    const proj = layout.projects.find(p => p.name === layout.currentProject);
    if (!proj) { removePdf(); return; }
    const mcm = proj.mcms.find(m => m.name === layout.currentMcm);
    if (!mcm?.pdfPath) { removePdf(); return; }
    await loadPdfFromPath(mcm.pdfPath);
  }

  function onCanvasSizeChange() { layout.markDirty(); layout.saveMcmState(); }
  function onGridSizeChange() { layout.markDirty(); layout.saveMcmState(); }
  function onShowGridChange() { layout.markDirty(); }
  function onMinSpacingChange() { layout.saveMcmState(); }

  function clearCanvas() {
    if (!confirm('Clear all placed symbols?')) return;
    layout.clearAll();
  }

  async function onImportFile(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (!file) return;
    try {
      if (file.name.endsWith('.svg')) await loadLayoutSVG(file);
      else await loadLayoutJSON(file);
    } catch (err) {
      alert('Invalid layout file: ' + (err instanceof Error ? err.message : String(err)));
    }
    (e.target as HTMLInputElement).value = '';
  }

  async function onPdfFile(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (!file) return;
    await loadPdfFile(file);
    (e.target as HTMLInputElement).value = '';
  }

  let currentMcms = $derived(
    layout.projects.find(p => p.name === layout.currentProject)?.mcms ?? []
  );
</script>

<div class="toolbar" class:collapsed={toolbarCollapsed}>
  <button class="collapse-btn" onclick={() => toolbarCollapsed = !toolbarCollapsed}>
    {toolbarCollapsed ? '\u276F' : '\u276E'}
  </button>

  {#if !toolbarCollapsed}
    <div class="toolbar-content">
      <!-- Project & MCM selectors — always visible, compact -->
      <div class="project-bar">
        {#if layout.projects.length > 0}
          <select class="proj-select" value={layout.currentProject} onchange={onProjectChange} title="Project">
            {#each layout.projects as proj (proj.name)}
              <option value={proj.name}>{proj.name}</option>
            {/each}
          </select>
        {/if}
        <select class="mcm-select" value={layout.currentMcm} onchange={onMcmChange} title="MCM">
          {#each currentMcms as mcm (mcm.name)}
            <option value={mcm.name}>{mcm.name}</option>
          {/each}
        </select>
      </div>

      <!-- Action bar — always visible -->
      <div class="action-bar">
        <button onclick={exportSVG} title="Export SVG">SVG</button>
        <button onclick={exportJSON} title="Export JSON">JSON</button>
        <button onclick={() => importFileEl.click()} title="Import layout file">Import</button>
        <button class="btn-danger" onclick={clearCanvas} title="Clear canvas">Clear</button>
        <input bind:this={importFileEl} type="file" accept=".json,.svg" style="display:none" onchange={onImportFile}>
      </div>

      <div class="divider"></div>

      <!-- Background PDF -->
      <button class="section-toggle" onclick={() => pdfOpen = !pdfOpen}>
        <span class="chevron" class:open={pdfOpen}></span>
        Background
        {#if layout.pdfLoaded}
          <span class="badge">{Math.round(layout.pdfScale * 100)}%</span>
        {/if}
      </button>
      {#if pdfOpen}
        <div class="section-body">
          <div class="btn-row">
            <button onclick={() => pdfFileEl.click()}>Load PDF</button>
            <input bind:this={pdfFileEl} type="file" accept=".pdf" style="display:none" onchange={onPdfFile}>
            <button onclick={removePdf}>Remove</button>
          </div>
          {#if layout.pdfLoaded}
            <div class="btn-row">
              <button onclick={pdfZoomOut}>-</button>
              <span class="zoom-label">{Math.round(layout.pdfScale * 100)}%</span>
              <button onclick={pdfZoomIn}>+</button>
              <button
                class:active={layout.editingBackground}
                onclick={toggleEditBackground}
              >
                {layout.editingBackground ? 'Done' : 'Move'}
              </button>
            </div>
          {/if}
        </div>
      {/if}

      <!-- Canvas Settings -->
      <button class="section-toggle" onclick={() => settingsOpen = !settingsOpen}>
        <span class="chevron" class:open={settingsOpen}></span>
        Canvas
      </button>
      {#if settingsOpen}
        <div class="section-body">
          <div class="inline-row">
            <label>W</label>
            <input type="number" bind:value={layout.canvasW} min="800" max="7680" step="10" onchange={onCanvasSizeChange}>
            <label>H</label>
            <input type="number" bind:value={layout.canvasH} min="600" max="4320" step="10" onchange={onCanvasSizeChange}>
          </div>
          <div class="inline-row">
            <label>Grid</label>
            <input type="number" bind:value={layout.gridSize} min="5" max="100" step="5" onchange={onGridSizeChange}>
            <label>Gap</label>
            <input type="number" bind:value={layout.minSpacing} min="0" max="100" step="5" onchange={onMinSpacingChange}>
          </div>
          <div class="toggle-row">
            <label class="toggle-label">
              <input type="checkbox" bind:checked={layout.showGrid} onchange={onShowGridChange}>
              <span>Grid</span>
            </label>
            <label class="toggle-label">
              <input type="checkbox" bind:checked={layout.snapEnabled}>
              <span>Snap</span>
            </label>
          </div>
        </div>
      {/if}

      <div class="divider"></div>

      <!-- Symbols -->
      <Palette />
    </div>
  {/if}
</div>

<style>
  .toolbar {
    width: 220px;
    min-width: 220px;
    background: #111827;
    border-right: 1px solid #1f2937;
    display: flex;
    flex-direction: column;
    position: relative;
    transition: width 0.2s ease, min-width 0.2s ease;
    overflow: hidden;
  }

  .toolbar.collapsed {
    width: 28px;
    min-width: 28px;
  }

  .collapse-btn {
    position: absolute;
    top: 6px;
    right: 2px;
    width: 22px;
    height: 22px;
    background: transparent;
    border: none;
    color: #6b7280;
    cursor: pointer;
    z-index: 10;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    transition: all 0.15s;
  }

  .collapse-btn:hover {
    background: #1f2937;
    color: #e5e7eb;
  }

  .toolbar-content {
    padding: 4px 6px;
    overflow: hidden;
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  /* Project bar */
  .project-bar {
    display: flex;
    gap: 3px;
    margin-bottom: 4px;
    flex-shrink: 0;
  }

  .proj-select, .mcm-select {
    flex: 1;
    padding: 4px 6px;
    background: #1f2937;
    border: 1px solid #374151;
    color: #e5e7eb;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    outline: none;
    appearance: none;
    min-width: 0;
  }

  .proj-select:focus, .mcm-select:focus {
    border-color: #3b82f6;
  }

  /* Action bar */
  .action-bar {
    display: flex;
    gap: 2px;
    margin-bottom: 4px;
    flex-shrink: 0;
  }

  .action-bar button {
    flex: 1;
    padding: 4px 2px;
    background: #1f2937;
    border: 1px solid #374151;
    color: #9ca3af;
    border-radius: 4px;
    cursor: pointer;
    font-size: 9px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    transition: all 0.15s;
  }

  .action-bar button:hover {
    background: #374151;
    color: #e5e7eb;
  }

  .action-bar .btn-danger:hover {
    background: #991b1b;
    border-color: #991b1b;
    color: #fca5a5;
  }

  .divider {
    height: 1px;
    background: #1f2937;
    margin: 2px 0;
    flex-shrink: 0;
  }

  /* Section toggle */
  .section-toggle {
    display: flex;
    align-items: center;
    gap: 6px;
    width: 100%;
    padding: 5px 4px;
    background: none;
    border: none;
    color: #9ca3af;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    cursor: pointer;
    transition: color 0.15s;
    text-align: left;
    flex-shrink: 0;
  }

  .section-toggle:hover {
    color: #e5e7eb;
  }

  .chevron {
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 3.5px solid transparent;
    border-bottom: 3.5px solid transparent;
    border-left: 4.5px solid currentColor;
    transition: transform 0.15s ease;
    flex-shrink: 0;
  }

  .chevron.open {
    transform: rotate(90deg);
  }

  .badge {
    margin-left: auto;
    font-size: 9px;
    color: #6b7280;
    font-weight: 400;
    text-transform: none;
    letter-spacing: 0;
    background: #1f2937;
    padding: 1px 5px;
    border-radius: 8px;
  }

  .section-body {
    padding: 2px 0 6px 10px;
    flex-shrink: 0;
  }

  /* Button rows */
  .btn-row {
    display: flex;
    gap: 3px;
    margin-bottom: 3px;
    align-items: center;
  }

  .btn-row button, .section-body > button {
    flex: 1;
    padding: 4px 6px;
    background: #1f2937;
    border: 1px solid #374151;
    color: #9ca3af;
    border-radius: 4px;
    cursor: pointer;
    font-size: 10px;
    transition: all 0.15s;
  }

  .btn-row button:hover {
    background: #374151;
    color: #e5e7eb;
  }

  .btn-row button.active {
    background: #3b82f6;
    border-color: #3b82f6;
    color: #fff;
  }

  .zoom-label {
    font-size: 10px;
    color: #9ca3af;
    min-width: 32px;
    text-align: center;
  }

  /* Inline settings rows */
  .inline-row {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 3px;
  }

  .inline-row label {
    font-size: 9px;
    color: #6b7280;
    font-weight: 600;
    text-transform: uppercase;
    flex-shrink: 0;
    min-width: 14px;
  }

  .inline-row input[type="number"] {
    flex: 1;
    padding: 3px 4px;
    background: #1f2937;
    border: 1px solid #374151;
    color: #e5e7eb;
    border-radius: 4px;
    font-size: 11px;
    outline: none;
    min-width: 0;
  }

  .inline-row input:focus {
    border-color: #3b82f6;
  }

  .toggle-row {
    display: flex;
    gap: 12px;
  }

  .toggle-label {
    display: flex;
    align-items: center;
    gap: 4px;
    cursor: pointer;
    font-size: 10px;
    color: #9ca3af;
  }

  .toggle-label input[type="checkbox"] {
    accent-color: #3b82f6;
    width: 12px;
    height: 12px;
  }

  .toggle-label span {
    user-select: none;
  }
</style>
