/* RC-OPS-005 — Toast system for export failures (+ success + retry).
   Global API:   window.__rcToast.push({kind, title, detail, action, actionLabel, timeout})
                 window.__rcToast.dismiss(id)
   Mount once: <RCToastHost /> at app root. */

const _listeners = new Set();
let _seq = 1;
const _toasts = [];

const emit = () => _listeners.forEach(fn => fn([..._toasts]));

window.__rcToast = {
  push(opts) {
    const id = _seq++;
    const t = { id, kind: 'info', timeout: 5000, ...opts };
    _toasts.push(t);
    emit();
    if (t.timeout > 0) {
      setTimeout(() => window.__rcToast.dismiss(id), t.timeout);
    }
    return id;
  },
  dismiss(id) {
    const i = _toasts.findIndex(t => t.id === id);
    if (i !== -1) { _toasts.splice(i, 1); emit(); }
  },
  /* Convenience — RC-OPS-005 export failure + retry */
  exportFailed({ scope = 'section', detail, onRetry } = {}) {
    const id = window.__rcToast.push({
      kind: 'error',
      title: `Export failed`,
      detail: detail || `We couldn't generate the ${scope} export. Try again, or contact support if this keeps happening.`,
      actionLabel: 'Retry',
      action: () => {
        window.__rcToast.dismiss(id);
        onRetry && onRetry();
      },
      timeout: 0,
    });
    return id;
  },
  exportStarted({ scope = 'section' } = {}) {
    return window.__rcToast.push({
      kind: 'info',
      title: `Preparing ${scope} export…`,
      detail: 'Building your file — this should take just a moment.',
      timeout: 1800,
    });
  },
  exportSucceeded({ scope = 'section', filename } = {}) {
    return window.__rcToast.push({
      kind: 'success',
      title: 'Export ready',
      detail: filename ? `Saved ${filename}` : `Your ${scope} export is ready.`,
      timeout: 4000,
    });
  },
};

/* React host — renders the stack bottom-right. */
const RCToastHost = () => {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    const fn = setItems;
    _listeners.add(fn);
    return () => _listeners.delete(fn);
  }, []);
  const palette = {
    error:   { bg: '#fef2f2', border: '#fecaca', ink: '#991b1b', icon: 'alert',   iconBg: '#fee2e2' },
    success: { bg: '#f0fdf4', border: '#bbf7d0', ink: '#166534', icon: 'check',   iconBg: '#dcfce7' },
    info:    { bg: '#eff6ff', border: '#bfdbfe', ink: '#1e40af', icon: 'refresh', iconBg: '#dbeafe' },
  };
  return (
    <div style={{
      position: 'fixed', right: 16, bottom: 16, zIndex: 9999,
      display: 'flex', flexDirection: 'column-reverse', gap: 8,
      maxWidth: 380, pointerEvents: 'none',
    }}>
      {items.map(t => {
        const p = palette[t.kind] || palette.info;
        return (
          <div key={t.id} style={{
            pointerEvents: 'auto',
            display: 'flex', alignItems: 'flex-start', gap: 10,
            padding: '11px 13px',
            background: p.bg, border: `1px solid ${p.border}`, borderRadius: 10,
            boxShadow: '0 10px 25px -8px rgba(15,23,42,0.22)',
            animation: 'rcToastIn 180ms ease',
            fontFamily: 'Inter',
            maxWidth: 380,
          }}>
            <div style={{
              width: 24, height: 24, borderRadius: 999, flexShrink: 0,
              background: p.iconBg, display: 'inline-flex',
              alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={p.icon} size={12} color={p.ink} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: p.ink, marginBottom: t.detail ? 2 : 0 }}>{t.title}</div>
              {t.detail && <div style={{ fontSize: 11.5, color: p.ink, opacity: 0.82, lineHeight: 1.4 }}>{t.detail}</div>}
              {t.action && t.actionLabel && (
                <button onClick={t.action} style={{
                  marginTop: 7, padding: '4px 10px', fontSize: 11, fontWeight: 600,
                  border: `1px solid ${p.border}`, borderRadius: 6,
                  background: '#fff', color: p.ink, cursor: 'pointer', fontFamily: 'inherit',
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                }}>
                  <Icon name="refresh" size={10} /> {t.actionLabel}
                </button>
              )}
            </div>
            <button onClick={() => window.__rcToast.dismiss(t.id)} title="Dismiss"
              style={{
                border: 0, background: 'transparent', color: p.ink, opacity: 0.6,
                cursor: 'pointer', padding: 2, lineHeight: 0,
              }}>
              <Icon name="x" size={11} />
            </button>
          </div>
        );
      })}
    </div>
  );
};

/* Inject keyframes once */
if (typeof document !== 'undefined' && !document.getElementById('rc-toast-kf')) {
  const s = document.createElement('style');
  s.id = 'rc-toast-kf';
  s.textContent = `@keyframes rcToastIn { from {opacity:0; transform:translateY(8px);} to {opacity:1; transform:translateY(0);} }`;
  document.head.appendChild(s);
}

Object.assign(window, { RCToastHost });
