(function(){
  'use strict';

  function ensurePopupContainer(){
    if (document.getElementById('spPopupBackdrop')) return;
    const backdrop = document.createElement('div');
    backdrop.className = 'sp-popup-backdrop';
    backdrop.id = 'spPopupBackdrop';
    document.body.appendChild(backdrop);

    const toastWrap = document.createElement('div');
    toastWrap.className = 'sp-toast-wrap';
    toastWrap.id = 'spToastWrap';
    document.body.appendChild(toastWrap);
  }

  function iconFor(type){
    switch ((type || 'info').toLowerCase()){
      case 'success': return '✓';
      case 'error':   return '✕';
      case 'warning': return '!';
      case 'confirm': return '?';
      default:        return 'i';
    }
  }

  function escapeHTML(s){
    return String(s == null ? '' : s)
      .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
      .replace(/"/g,'&quot;').replace(/'/g,'&#39;');
  }

  let currentResolve = null;

  function closePopup(){
    const bd = document.getElementById('spPopupBackdrop');
    if (!bd) return;
    bd.classList.remove('show');
    setTimeout(() => { bd.innerHTML = ''; }, 250);
  }

  function buildPopup(opts){
    ensurePopupContainer();
    const bd = document.getElementById('spPopupBackdrop');

    const type      = (opts.type || opts.icon || 'info').toLowerCase();
    const title     = opts.title    || (type === 'error' ? 'Terjadi Kesalahan' : type === 'success' ? 'Berhasil' : type === 'warning' ? 'Perhatian' : type === 'confirm' ? 'Konfirmasi' : 'Info');
    const message   = opts.message  || opts.html || '';
    const html      = !!opts.html;
    const isConfirm = type === 'confirm' || opts.confirm === true;
    const okText    = opts.okText    || (isConfirm ? 'Ya, Lanjutkan' : 'OK');
    const cancelText= opts.cancelText|| 'Batal';
    const showCancel= isConfirm;
    const danger    = !!opts.danger;
    const closable  = opts.closable !== false;

    bd.innerHTML = `
      <div class="sp-popup" role="dialog" aria-modal="true">
        ${closable ? '<button type="button" class="sp-popup-close" data-act="close">×</button>' : ''}
        <div class="sp-popup-head">
          <div class="sp-popup-icon ${type}">${iconFor(type)}</div>
          <h3 class="sp-popup-title">${escapeHTML(title)}</h3>
        </div>
        <div class="sp-popup-body">${html ? message : escapeHTML(message).replace(/\n/g,'<br>')}</div>
        <div class="sp-popup-actions">
          ${showCancel ? `<button type="button" class="sp-popup-btn sp-popup-btn-secondary" data-act="cancel">${escapeHTML(cancelText)}</button>` : ''}
          <button type="button" class="sp-popup-btn ${danger ? 'sp-popup-btn-danger' : 'sp-popup-btn-primary'}" data-act="ok">${escapeHTML(okText)}</button>
        </div>
      </div>
    `;

    bd.classList.add('show');

    return new Promise((resolve) => {
      currentResolve = resolve;
      bd.querySelectorAll('[data-act]').forEach(btn => {
        btn.addEventListener('click', () => {
          const act = btn.getAttribute('data-act');
          closePopup();
          if (act === 'ok') {
            if (typeof opts.onYes === 'function') opts.onYes();
            resolve(true);
          } else {
            if (typeof opts.onNo === 'function') opts.onNo();
            resolve(false);
          }
        });
      });
      bd.addEventListener('click', (e) => {
        if (e.target === bd && closable) {
          closePopup();
          if (typeof opts.onNo === 'function') opts.onNo();
          resolve(false);
        }
      }, { once: true });
    });
  }

  // ---------- Public API ----------
  const SpinPopup = {
    alert(opts){
      if (typeof opts === 'string') opts = { message: opts };
      return buildPopup(Object.assign({ type: 'info' }, opts));
    },
    success(message, title){
      return buildPopup({ type: 'success', message, title: title || 'Berhasil' });
    },
    error(message, title){
      return buildPopup({ type: 'error', message, title: title || 'Terjadi Kesalahan' });
    },
    warning(message, title){
      return buildPopup({ type: 'warning', message, title: title || 'Perhatian' });
    },
    info(message, title){
      return buildPopup({ type: 'info', message, title: title || 'Info' });
    },
    confirm(opts){
      if (typeof opts === 'string') opts = { message: opts };
      return buildPopup(Object.assign({ type: 'confirm' }, opts, { confirm: true }));
    },
    close: closePopup,

    toast(opts){
      ensurePopupContainer();
      const wrap = document.getElementById('spToastWrap');
      const type = (opts.type || 'info').toLowerCase();
      const dur = opts.duration || 3200;
      const el = document.createElement('div');
      el.className = 'sp-toast ' + type;
      el.innerHTML = `
        <div class="sp-toast-icon">${iconFor(type)}</div>
        <div class="sp-toast-body">
          ${opts.title ? `<div class="sp-toast-title">${escapeHTML(opts.title)}</div>` : ''}
          <div class="sp-toast-msg">${escapeHTML(opts.message || '')}</div>
        </div>
        <button type="button" class="sp-toast-close" aria-label="Tutup">×</button>
      `;
      wrap.appendChild(el);
      requestAnimationFrame(() => el.classList.add('show'));
      const remove = () => {
        el.classList.remove('show');
        setTimeout(() => el.remove(), 250);
      };
      el.querySelector('.sp-toast-close').addEventListener('click', remove);
      setTimeout(remove, dur);
    },

    needLogin(redirectTo){
      return buildPopup({
        type: 'warning',
        title: 'Harus Login Dulu',
        message: 'Untuk memainkan game ini, kamu harus login terlebih dahulu. Klik LOGIN di pojok kanan atas.',
        okText: 'Login Sekarang',
        cancelText: 'Nanti Saja',
        confirm: true,
        onYes(){
          // Trigger login modal on parent if exists
          const loginBtn = document.querySelector('#openLogin, .login-btn, [data-open-login]');
          if (loginBtn) loginBtn.click();
          else if (redirectTo) window.location.href = redirectTo;
        }
      });
    }
  };

  // expose globally
  window.SpinPopup = SpinPopup;

  // ESC to close
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      const bd = document.getElementById('spPopupBackdrop');
      if (bd && bd.classList.contains('show')) {
        const closable = bd.querySelector('.sp-popup-close');
        if (closable) closable.click();
      }
    }
  });
})();
