<script lang="ts">
  import { state as _state } from "$lib/state.svelte";
  import { Button } from "$lib/components/ui/button";
  import { EditorView } from "codemirror";
  import { onMount } from "svelte";
  import { BrushCleaning, Clipboard, FastForward } from "@lucide/svelte";
  import {
    copyContent,
    formatJson,
    setContent,
    setUpdateHandler,
    toggleVim,
    isVimEnabled,
  } from "$lib/codemirror.svelte";
  import { init } from "$lib/codemirror.svelte";

  let { input = null, onStateChange } = $props();

  let view: EditorView;

  onMount(async () => {
    view = init("editor", false, true);

    setUpdateHandler(view, onStateChange);
  });

  $effect(() => {
    if (input != null && input !== view.state.doc.toString()) {
      setContent(view, input);
    }
  });
</script>

<div class="w-full flex rounded-md border max-h-60">
  <!-- EDITOR SIDEBAR -->

  <div class="sticky flex flex-col gap-2 p-2 border-r">
    <Button
      onclick={() => toggleVim(view)}
      variant={isVimEnabled() ? "default" : "outline"}
      size="icon-sm"
    >
      <FastForward />
    </Button>

    <Button onclick={() => copyContent(view)} variant="outline" size="icon-sm"
      ><Clipboard /></Button
    >

    <Button onclick={() => formatJson(view)} variant="outline" size="icon-sm"
      ><BrushCleaning /></Button
    >
  </div>

  <!-- EDITOR -->

  <div
    id="editor"
    class="mx-auto w-full rounded-md overflow-scroll max-h-fit"
  ></div>
</div>
