// toast.js - 自包含模块，自动注入 HTML + 提供 toastModule.show() 接口
(function () {
  // 注入 HTML 模板（Alpine 控制 + Tailwind 样式）
  function injectTemplate() {
    if (document.getElementById('toast-container')) return;

    const div = document.createElement('div');
    div.id = 'toast-container';
    div.innerHTML = `
      <div class="fixed top-5 left-1/2 transform -translate-x-1/2 z-50"
           x-data="toastAlpine()"
           x-init="init()"
           x-show="show"
           x-transition:enter="transition ease-out duration-300"
           x-transition:enter-start="-translate-y-full opacity-0"
           x-transition:enter-end="translate-y-0 opacity-100"
           x-transition:leave="transition ease-in duration-300"
           x-transition:leave-start="translate-y-0 opacity-100"
           x-transition:leave-end="-translate-y-full opacity-0"
           style="display: none">
        <div class="flex items-center p-4 text-sm text-white rounded-lg shadow-md"
             :class="type === 'success' ? 'bg-green-500' : 'bg-red-500'">
          <i class="mr-2"
             :class="type === 'success' ? 'fa-solid fa-circle-check' : 'fa-solid fa-circle-exclamation'"></i>
          <span x-text="message"></span>
        </div>
      </div>
      
    `;
    document.body.appendChild(div);
  }

  // 注入 Alpine 方法
  window.toastAlpine = function () {
    return {
      show: false,
      message: '',
      type: 'error',
      init() {
        window.addEventListener('toast', (e) => {
          const { message, type, duration, onClose } = e.detail;
          this.message = message;
          this.type = type || 'error';
          this.show = true;

          setTimeout(() => {
            this.show = false;

            setTimeout(() => {
              if (typeof onClose === 'function') onClose();
            }, 300); // 动画时间
          }, duration || 2000);
        });
      }
    };
  };

  // 提供统一接口
  window.toastModule = {
    show({ message, type = 'error', duration = 2000, onClose = null }) {
      window.dispatchEvent(new CustomEvent('toast', {
        detail: { message, type, duration, onClose }
      }));
    },
    success({message, duration, onClose}) {
      this.show({message, type: 'success', duration, onClose})
    },
    error({message, duration, onClose}) {
      this.show({message, type: 'error', duration, onClose})
    },
    errorLayer({msg, time, onClose}) {
      layui.layer.msg(
        '<i class="fa-solid fa-circle-exclamation"></i>' + msg, {
        offset: '15px',
        anim: 'slideDown',
        time: time,
        skin: 'giggity error',
        end: onClose
      })
    },
    successLayer({msg, time, onClose}) {
      layui.layer.msg(
        '<i class="fa-solid fa-circle-check"></i>' + msg, {
        offset: '15px',
        anim: 'slideDown',
        time: time,
        skin: 'giggity success',
        end: onClose
      })
    }
  };

  // 注入模板
  injectTemplate();
})();
