<script>
  import { X } from 'lucide-svelte';

  /**
   * @typedef {Object} Props
   * @property {boolean} open - Whether modal is open
   * @property {string} [title] - Modal title
   * @property {string} [size] - Modal size (sm, md, lg, xl, full)
   * @property {boolean} [closable] - Whether modal can be closed by clicking backdrop
   * @property {'center' | 'top'} [position] - Modal position (center or top)
   * @property {Function} [onClose] - Callback when modal is closed
   * @property {import('svelte').Snippet} [children] - Modal content
   * @property {import('svelte').Snippet} [footer] - Modal footer
   */

  /** @type {Props} */
  let {
    open = $bindable(false),
    title = '',
    size = 'md',
    closable = true,
    position = 'center',
    onClose = null,
    children,
    footer,
  } = $props();

  const sizeClasses = {
    sm: 'modal-sm',
    md: '',
    lg: 'modal-lg',
    xl: 'modal-xl',
    full: 'modal-full',
    wide: 'modal-wide',
  };

  const widthStyles = {
    sm: 'max-width: 350px;',
    md: 'max-width: 450px;',
    lg: 'max-width: 700px;',
    xl: 'max-width: 1000px;',
    full: 'max-width: 100%; width: 100%; height: 100%;',
    wide: 'max-width: 90vw; width: 1000px;',
  };

  /**
   * Close the modal
   */
  function close() {
    if (closable) {
      open = false;
      if (onClose) {
        onClose();
      }
    }
  }

  /**
   * Handle backdrop click
   * @param {MouseEvent} event
   */
  function handleBackdropClick(event) {
    if (event.target === event.currentTarget && closable) {
      close();
    }
  }

  /**
   * Handle escape key
   * @param {KeyboardEvent} event
   */
  function handleKeydown(event) {
    if (event.key === 'Escape' && closable) {
      close();
    }
  }
</script>

<svelte:window onkeydown={handleKeydown} />

<dialog class="modal {sizeClasses[size] || ''}" class:modal-open={open}>
  <div class="modal-box" style="{widthStyles[size] || ''} {position === 'top' ? 'align-self: flex-start; margin-top: 2rem;' : ''}" role="dialog" aria-modal="true" aria-labelledby={title ? 'modal-title' : undefined}>
    <!-- Header -->
    <div class="flex items-center justify-between mb-4">
      {#if title}
        <h3 id="modal-title" class="font-bold text-base">{title}</h3>
      {:else}
        <div></div>
      {/if}
      
      {#if closable}
        <button
          class="btn btn-sm btn-circle btn-ghost"
          onclick={close}
          aria-label="Close modal"
        >
          <X class="w-4 h-4" />
        </button>
      {/if}
    </div>

    <!-- Content -->
    <div class="py-2">
      {@render children?.()}
    </div>

    <!-- Footer -->
    {#if footer}
      <div class="modal-action">
        {@render footer()}
      </div>
    {/if}
  </div>

  <!-- Backdrop -->
  <form method="dialog" class="modal-backdrop" onclick={handleBackdropClick}>
    <button>close</button>
  </form>
</dialog>
