<script lang="ts">
  import type { SplitNode } from "./tree";
  import Pane from "./Pane.svelte";

  let { node }: { node: SplitNode } = $props();

  let containerEl: HTMLDivElement;
  let dragging = $state(false);

  function onPointerDown(e: PointerEvent) {
    (e.target as HTMLElement).setPointerCapture(e.pointerId);
    dragging = true;
    e.preventDefault();
  }

  function onPointerMove(e: PointerEvent) {
    if (!dragging || !containerEl) return;
    const rect = containerEl.getBoundingClientRect();
    const isH = node.orientation === "h";
    const pos = isH ? e.clientX - rect.left : e.clientY - rect.top;
    const size = isH ? rect.width : rect.height;
    if (size <= 0) return;
    const r = Math.max(0.05, Math.min(0.95, pos / size));
    node.ratio = r;
  }

  function onPointerUp(e: PointerEvent) {
    if (!dragging) return;
    (e.target as HTMLElement).releasePointerCapture(e.pointerId);
    dragging = false;
  }
</script>

<div
  class="split"
  class:horizontal={node.orientation === "h"}
  class:vertical={node.orientation === "v"}
  bind:this={containerEl}
>
  <div class="side" style="flex: {node.ratio}">
    <Pane node={node.a} />
  </div>
  <div
    class="gutter"
    class:active={dragging}
    role="separator"
    aria-orientation={node.orientation === "h" ? "vertical" : "horizontal"}
    aria-valuenow={Math.round(node.ratio * 100)}
    tabindex="-1"
    onpointerdown={onPointerDown}
    onpointermove={onPointerMove}
    onpointerup={onPointerUp}
    onpointercancel={onPointerUp}
  ></div>
  <div class="side" style="flex: {1 - node.ratio}">
    <Pane node={node.b} />
  </div>
</div>

<style>
  .split {
    display: flex;
    width: 100%;
    height: 100%;
    min-width: 0;
    min-height: 0;
  }
  .split.horizontal {
    flex-direction: row;
  }
  .split.vertical {
    flex-direction: column;
  }

  .side {
    display: flex;
    min-width: 0;
    min-height: 0;
    overflow: hidden;
  }

  .gutter {
    flex: 0 0 4px;
    background: #1a1a1a;
    cursor: col-resize;
    user-select: none;
    touch-action: none;
    transition: background 0.12s;
  }
  .split.vertical > .gutter {
    cursor: row-resize;
  }
  .gutter:hover,
  .gutter.active {
    background: #3a5a8c;
  }
</style>
