/**
 * admin-ui/js/components/ds-toast-provider.js
 * Manages a stack of ds-toast components.
 * Provides a global window.showToast() function.
 */
class DsToastProvider extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.render();
    // Expose global toast function
    window.showToast = this.showToast.bind(this);
  }

  disconnectedCallback() {
    delete window.showToast;
  }

  /**
   * Show a toast notification
   * @param {object} options - Toast options
   * @param {string} options.message - The main message
   * @param {string} [options.type='info'] - 'info', 'success', 'warning', 'error'
   * @param {number} [options.duration=5000] - Duration in ms. 0 for persistent
   * @param {boolean} [options.dismissible=true] - Show close button
   * @returns {HTMLElement} The created toast element
   */
  showToast({ message, type = 'info', duration = 5000, dismissible = true }) {
    const toast = document.createElement('ds-toast');
    toast.setAttribute('type', type);
    toast.setAttribute('duration', String(duration));
    if (dismissible) {
      toast.setAttribute('dismissible', '');
    }
    toast.innerHTML = message;

    const stack = this.shadowRoot.querySelector('.stack');
    stack.appendChild(toast);

    // Limit visible toasts
    const toasts = stack.querySelectorAll('ds-toast');
    if (toasts.length > 5) {
      toasts[0].dismiss();
    }

    return toast;
  }

  render() {
    this.shadowRoot.innerHTML = `
      <style>
        .stack {
          position: fixed;
          top: var(--space-4);
          right: var(--space-4);
          z-index: 9999;
          display: flex;
          flex-direction: column;
          gap: var(--space-3);
          max-width: 380px;
          pointer-events: none;
        }
        .stack ::slotted(ds-toast),
        .stack ds-toast {
          pointer-events: auto;
        }

        @media (max-width: 480px) {
          .stack {
            left: var(--space-4);
            right: var(--space-4);
            max-width: none;
          }
        }
      </style>
      <div class="stack"></div>
    `;
  }
}

customElements.define('ds-toast-provider', DsToastProvider);
