// Toast notifications — bottom-right. Replaces window.alert / window.confirm.
//   toast(msg, type)         → 'success' | 'error' | 'warning' | 'info' (default)
//   toastConfirm(msg, opts)  → Promise<boolean> (renders Confirm/Cancel buttons)

const TOASTS = (() => {
  let seq = 0;
  const items = [];
  const listeners = new Set();
  function notify() { listeners.forEach((cb) => { try { cb(); } catch {} }); }

  function show(msg, type, timeout) {
    const t = { id: ++seq, msg: String(msg == null ? '' : msg), type: type || 'info', kind: 'note' };
    items.push(t);
    notify();
    const ms = timeout == null ? (type === 'error' ? 6000 : 3800) : timeout;
    if (ms) setTimeout(() => dismiss(t.id), ms);
    return t.id;
  }
  function dismiss(id) {
    const i = items.findIndex((x) => x.id === id);
    if (i >= 0) { items.splice(i, 1); notify(); }
  }
  function confirm(msg, opts) {
    opts = opts || {};
    return new Promise((resolve) => {
      const t = {
        id: ++seq, msg: String(msg == null ? '' : msg), kind: 'confirm',
        type: opts.danger ? 'warning' : 'info',
        confirmLabel: opts.confirmLabel || 'ยืนยัน',
        cancelLabel: opts.cancelLabel || 'ยกเลิก',
        danger: !!opts.danger,
        resolve,
      };
      items.push(t);
      notify();
    });
  }
  function answer(id, val) {
    const i = items.findIndex((x) => x.id === id);
    if (i >= 0) {
      const t = items[i];
      items.splice(i, 1);
      notify();
      if (t.resolve) t.resolve(val);
    }
  }
  function subscribe(cb) { listeners.add(cb); return () => listeners.delete(cb); }
  return { show, dismiss, confirm, answer, subscribe, get items() { return items; } };
})();

function toast(msg, type) { return TOASTS.show(msg, type); }
function toastConfirm(msg, opts) { return TOASTS.confirm(msg, opts); }

const TOAST_ICON = { success: '✅', error: '❌', warning: '⚠️', info: 'ℹ️' };
const TOAST_COLOR = { success: 'var(--accent)', error: 'var(--danger)', warning: 'var(--warn)', info: 'var(--info)' };

function ToastItem({ t }) {
  const color = TOAST_COLOR[t.type] || 'var(--info)';
  return (
    <div className="toast-item" style={{
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderLeft: `3px solid ${color}`,
      borderRadius: 10,
      padding: '12px 14px',
      boxShadow: '0 8px 28px rgba(0,0,0,.35)',
      display: 'flex', flexDirection: 'column', gap: 10,
      minWidth: 260,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        <span style={{ fontSize: 15, lineHeight: 1.2 }}>{TOAST_ICON[t.type] || 'ℹ️'}</span>
        <div style={{ flex: 1, fontSize: 13, lineHeight: 1.45, color: 'var(--text)', whiteSpace: 'pre-wrap' }}>{t.msg}</div>
        {t.kind === 'note' && (
          <button onClick={() => TOASTS.dismiss(t.id)} style={{
            background: 'none', border: 0, color: 'var(--text-muted)', cursor: 'pointer',
            fontSize: 16, lineHeight: 1, padding: 0, marginLeft: 4,
          }}>×</button>
        )}
      </div>
      {t.kind === 'confirm' && (
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button className="btn" style={{ padding: '4px 12px', fontSize: 12 }} onClick={() => TOASTS.answer(t.id, false)}>{t.cancelLabel}</button>
          <button className={t.danger ? 'btn danger' : 'btn primary'} style={{ padding: '4px 12px', fontSize: 12 }} onClick={() => TOASTS.answer(t.id, true)}>{t.confirmLabel}</button>
        </div>
      )}
    </div>
  );
}

function ToastHost() {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => TOASTS.subscribe(force), []);
  return (
    <div style={{
      position: 'fixed', right: 18, bottom: 18, zIndex: 9999,
      display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 380,
      pointerEvents: 'none',
    }}>
      {TOASTS.items.map((t) => (
        <div key={t.id} className="toast-enter" style={{ pointerEvents: 'auto' }}>
          <ToastItem t={t}/>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { TOASTS, toast, toastConfirm, ToastHost });
