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

  interface Props {
    open: boolean;
    title: string;
    content: string;
    filename: string;
    onSave: (text: string) => Promise<void>;
    onClose: () => void;
  }

  let { open, title, content, filename, onSave, onClose }: Props = $props();

  let saveError = $state('');
  let saving = $state(false);
  let fullscreen = $state(false);
  let currentBlob = $state<Blob | undefined>(undefined);

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

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

  async function save() {
    const blob = currentBlob ?? initialBlob;
    if (!blob) return;
    saveError = '';
    saving = true;
    try {
      const text = await blob.text();
      await onSave(text);
      onClose();
    } catch (e) {
      saveError = e instanceof Error ? e.message : 'Save failed';
    } finally {
      saving = false;
    }
  }

  function onKeydown(e: KeyboardEvent) {
    if (e.key === 'Escape') { if (fullscreen) { fullscreen = false; } else { onClose(); } }
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
      e.preventDefault();
      void save();
    }
  }
</script>

<svelte:window onkeydown={onKeydown} />

{#if open}
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-8" class:p-0={fullscreen}>
    <div
      class="flex flex-col w-full max-w-5xl bg-slate-900 transition-all"
      class:max-w-5xl={!fullscreen}
      style={fullscreen ? 'height: 100vh; border-radius: 0; border: none;' : 'height: 85vh; border-radius: 1rem; overflow: hidden; border: 1px solid rgba(255,255,255,0.1);'}
    >
      <div class="flex-none flex items-center justify-between px-5 py-3 border-b border-white/10 bg-slate-800">
        <h2 class="text-sm font-semibold text-white">{title}</h2>
        <div class="flex items-center gap-4">
          {#if saveError}
            <p class="text-xs text-rose-300">{saveError}</p>
          {/if}
          <button
            onclick={() => { fullscreen = !fullscreen; }}
            class="text-xs text-slate-400 hover:text-white"
            title={fullscreen ? 'Exit fullscreen' : 'Fullscreen'}
          >{fullscreen ? '⊡' : '⛶'}</button>
          <button
            onclick={onClose}
            class="text-xs text-slate-400 hover:text-white"
          >Cancel</button>
          <button
            onclick={save}
            disabled={saving}
            class="rounded-lg bg-cyan-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-cyan-500 disabled:opacity-50"
          >{saving ? 'Saving…' : 'Save'}</button>
        </div>
      </div>
      <div class="flex-1 overflow-hidden bg-slate-900">
        <ContentEditor
          value={initialBlob}
          {filename}
          colorScheme="dark"
          hideHeader={true}
          onChange={(v) => { currentBlob = v; }}
          onSave={save}
        />
      </div>
    </div>
  </div>
{/if}
