<script lang="ts">
  import { goto } from "$app/navigation";
  import { auth } from "$lib/stores/auth";
  import { toast } from "$lib/stores/toast";

  interface Props {
    isOpen?: boolean;
    onClose?: () => void;
    initialItemIds?: string[];
  }

  let { isOpen = false, onClose, initialItemIds = [] }: Props = $props();

  let name = $state("");
  let creating = $state(false);

  async function handleCreate() {
    const trimmed = name.trim();
    if (!trimmed) return;

    creating = true;
    try {
      const repo = auth.getRepository();
      const result = await repo.createPlaylist(trimmed, initialItemIds.length > 0 ? initialItemIds : undefined);
      toast.success(`Playlist "${trimmed}" created`);
      name = "";
      onClose?.();
      goto(`/library/${result.id}`);
    } catch (e) {
      console.error("[CreatePlaylist] Failed:", e);
      toast.error("Failed to create playlist");
    } finally {
      creating = false;
    }
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === "Enter" && name.trim()) handleCreate();
    if (e.key === "Escape") onClose?.();
  }
</script>

{#if isOpen}
  <!-- svelte-ignore a11y_no_static_element_interactions -->
  <div
    class="fixed inset-0 bg-black/60 flex items-center justify-center z-50"
    onclick={onClose}
    onkeydown={(e) => { if (e.key === "Escape") onClose?.(); }}
    role="dialog"
    aria-modal="true"
    tabindex="-1"
  >
    <div
      class="bg-[var(--color-surface)] rounded-xl p-6 max-w-sm w-full mx-4 space-y-4"
      onclick={(e) => e.stopPropagation()}
      onkeydown={(e) => e.stopPropagation()}
      role="presentation"
    >
      <h3 class="text-lg font-semibold text-white">Create Playlist</h3>

      <input
        type="text"
        bind:value={name}
        onkeydown={handleKeydown}
        placeholder="Playlist name"
        class="w-full px-4 py-2 bg-[var(--color-background)] border border-gray-600 rounded-lg text-white placeholder-gray-500 outline-none focus:border-[var(--color-jellyfin)] transition-colors"
      />

      {#if initialItemIds.length > 0}
        <p class="text-sm text-gray-400">
          {initialItemIds.length} track{initialItemIds.length !== 1 ? "s" : ""} will be added.
        </p>
      {/if}

      <div class="flex gap-3 justify-end">
        <button
          onclick={onClose}
          class="px-4 py-2 bg-[var(--color-surface-hover)] hover:bg-gray-600 rounded-lg transition-colors"
        >
          Cancel
        </button>
        <button
          onclick={handleCreate}
          disabled={!name.trim() || creating}
          class="px-4 py-2 bg-[var(--color-jellyfin)] hover:bg-[var(--color-jellyfin-dark)] disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
        >
          {creating ? "Creating..." : "Create"}
        </button>
      </div>
    </div>
  </div>
{/if}
