<script lang="ts">
  import { ContentEditor } from '@warkypublic/svelix';

  interface Props {
    value: string;
    filename: string;
    disabled?: boolean;
    onchange: (text: string) => void;
  }

  let { value, filename, disabled = false, onchange }: Props = $props();

  let currentBlob = $state<Blob | undefined>(undefined);

  const initialBlob = $derived(new Blob([value ?? ''], { type: 'text/plain' }));

  $effect(() => {
    currentBlob = undefined;
  });

  async function handleBlobChange(blob?: Blob) {
    currentBlob = blob;
    if (!blob) {
      onchange('');
      return;
    }
    onchange(await blob.text());
  }
</script>

<div class="rounded-xl border border-white/10 bg-slate-950/60 overflow-hidden">
  <div class="border-b border-white/10 px-4 py-2 text-xs uppercase tracking-[0.18em] text-slate-500">
    {filename}
  </div>
  <div class:opacity-60={disabled} class:pointer-events-none={disabled}>
    <ContentEditor
      value={currentBlob ?? initialBlob}
      {filename}
      colorScheme="dark"
      hideHeader={true}
      onChange={(blob) => { void handleBlobChange(blob); }}
    />
  </div>
</div>
