<script lang="ts">
  import type { Interface, Widget } from './types';
  import TextView from './widgets/TextView.svelte';

  let { iface }: { iface: Interface | null } = $props();

  const dpr = window.devicePixelRatio ?? 1;

  function componentForType(type: string): any {
    switch (type) {
      case 'textview': return TextView;
      default: return null;
    }
  }
</script>

<div
  class="canvas-container"
  style="--dpr: {dpr};"
>
  {#if iface === null}
    <div class="placeholder">
      <p>Select an interface from the left panel, or import one.</p>
    </div>
  {:else}
    <div class="canvas-area">
      {#each iface.widgets as widget (widget.id)}
        {#if componentForType(widget.type) !== null}
          {@const Comp = componentForType(widget.type)}
          <Comp {widget} />
        {:else}
          <!-- Unknown widget type: grey placeholder box -->
          <div
            class="unknown-widget"
            style="
              left: {widget.x}px;
              top: {widget.y}px;
              width: {widget.w}px;
              height: {widget.h}px;
            "
            title="Unknown widget type: {widget.type}"
          >
            <span class="unknown-label">{widget.type}</span>
          </div>
        {/if}
      {/each}
    </div>
  {/if}
</div>

<style>
  .canvas-container {
    flex: 1;
    position: relative;
    overflow: auto;
    background: #0f1117;
    min-width: 0;
  }

  .placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #475569;
    font-size: 0.95rem;
    text-align: center;
    padding: 2rem;
  }

  .canvas-area {
    position: relative;
    /* Large enough to accommodate absolutely-positioned widgets */
    min-width: 100%;
    min-height: 100%;
    width: max-content;
    height: max-content;
    padding: 1rem;
    box-sizing: border-box;
  }

  .unknown-widget {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #1e2535;
    border: 1px dashed #3d4f6e;
    border-radius: 4px;
    box-sizing: border-box;
  }

  .unknown-label {
    color: #475569;
    font-size: 0.75rem;
    font-family: ui-monospace, monospace;
  }
</style>
