<script lang="ts">
  import Moveable from "svelte-moveable";

  export let elem_id = "";
  export let elem_classes: string[] = [];
  export let visible = true;

  let data: HTMLDivElement;
  let componentElements = [];

  $: {
    if (data) {
      componentElements = Array.from(
        data.querySelectorAll('[id^="component-"]')
      );
    }
  }

  const draggable = true;
  const throttleDrag = 1;
  const edgeDraggable = true;
  const startDragRotate = 0;
  const throttleDragRotate = 0;
  const scalable = true;
  const keepRatio = false;
  const throttleScale = 0;
  const renderDirections = ["nw", "n", "ne", "w", "e", "sw", "s", "se"];
  const rotatable = true;
  const throttleRotate = 0;
  const rotationPosition = "top";

  let editing = false;
</script>

<div
  id={elem_id}
  class="gr-group {elem_classes.join(' ')}"
  class:hide={!visible}
>
  <button class="edit-button" on:click={() => (editing = !editing)}
    >{editing ? "Done" : "Edit"}</button
  >
  <div bind:this={data} class="hide">
    <slot />
  </div>

  {#each componentElements as elmt, id}
    <div class={"target target" + id}>
      {@html elmt.outerHTML}
    </div>
  {/each}

  {#if componentElements.length > 0 && editing}
    <Moveable
      target={".target"}
      individualGroupable={true}
      {draggable}
      {throttleDrag}
      {edgeDraggable}
      {startDragRotate}
      {throttleDragRotate}
      {scalable}
      {keepRatio}
      {throttleScale}
      {renderDirections}
      {rotatable}
      {throttleRotate}
      {rotationPosition}
      on:drag={({ detail: e }) => {
        e.target.style.transform = e.transform;
      }}
      on:scale={({ detail: e }) => {
        e.target.style.transform = e.drag.transform;
      }}
      on:rotate={({ detail: e }) => {
        e.target.style.transform = e.drag.transform;
      }}
    />
  {/if}
</div>

<style>
  .edit-button {
    position: absolute;
    top: 0;
    right: 0;
    left: 100%;
  }

  :global(.moveable-line) {
    opacity: 0.1;
  }

  :global(.moveable-control) {
    opacity: 0.2;
  }

  :global(.moveable-origin) {
    opacity: 0;
  }
  :global(.gradio-container) {
    overflow: visible;
  }
  .hide {
    display: none;
  }

  .target {
    margin: 30px;
  }
</style>
