<script lang="ts">
  import type { Snippet } from "svelte";
  import Icon from "@iconify/svelte";
  import "$lib/iconify-offline";

  interface Props {
    label: string;
    open?: boolean;
    lazy?: boolean;
    id?: string;
    class?: string;
    onToggleEvent?: (e: Event) => void;
    children: Snippet;
  }

  let {
    label,
    open = false,
    lazy = false,
    id = undefined,
    class: cls = "",
    onToggleEvent,
    children,
  }: Props = $props();

  let everOpened = $state(false);
  const mounted = $derived(!lazy || open || everOpened);

  function onToggle(e: Event) {
    if ((e.target as HTMLDetailsElement).open) everOpened = true;
    onToggleEvent?.(e);
  }
</script>

<details {id} {open} ontoggle={onToggle} class="pt-4 border-t border-stein-200 group {cls}">
  <summary class="flex cursor-pointer list-none items-center gap-2 text-sm font-medium select-none">
    <Icon icon="mdi:chevron-right" class="size-4 shrink-0 transition-transform group-open:rotate-90" />
    {label}
  </summary>
  <div class="mt-4">
    {#if mounted}
      {@render children()}
    {/if}
  </div>
</details>
