/**
 * Toast notification system — zero external dependencies
 * Usage:
 *   import { useToast } from '../../components/ui/Toast.jsx';
 *   const toast = useToast();
 *   toast.success('Saved!');
 *   toast.error('Something went wrong');
 *   toast.info('No changes detected');
 *   await toast.confirm('Are you sure?')  → returns Promise<boolean>
 */
import React, { createContext, useContext, useState, useCallback, useRef } from 'react';

const ToastCtx = createContext(null);

let _uid = 0;

export const ToastProvider = ({ children }) => {
  const [toasts, setToasts]   = useState([]);
  const [dialog, setDialog]   = useState(null); // { message, resolve }

  /* ── add / remove toasts ── */
  const remove = useCallback((id) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  }, []);

  const add = useCallback((message, type = 'info', duration = 3500) => {
    const id = ++_uid;
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => remove(id), duration);
  }, [remove]);

  /* ── public API ── */
  const toast = {
    success: (msg, dur)  => add(msg, 'success', dur),
    error:   (msg, dur)  => add(msg, 'error',   dur ?? 5000),
    info:    (msg, dur)  => add(msg, 'info',     dur),
    warning: (msg, dur)  => add(msg, 'warning',  dur),
    /** Returns Promise<boolean> — replaces confirm() */
    confirm: (message) => new Promise(resolve => {
      setDialog({ message, resolve });
    }),
  };

  const closeDialog = (result) => {
    if (dialog) dialog.resolve(result);
    setDialog(null);
  };

  return (
    <ToastCtx.Provider value={toast}>
      {children}

      {/* ── Toast stack ── */}
      <div className="bpsfw-toast-stack" aria-live="polite">
        {toasts.map(t => (
          <div key={t.id} className={`bpsfw-toast bpsfw-toast--${t.type}`}>
            <span className="bpsfw-toast__icon">
              {t.type === 'success' && '✓'}
              {t.type === 'error'   && '✕'}
              {t.type === 'warning' && '⚠'}
              {t.type === 'info'    && 'ℹ'}
            </span>
            <span className="bpsfw-toast__msg">{t.message}</span>
            <button className="bpsfw-toast__close" onClick={() => remove(t.id)} aria-label="Dismiss">×</button>
          </div>
        ))}
      </div>

      {/* ── Confirm dialog (replaces browser confirm()) ── */}
      {dialog && (
        <div className="bpsfw-dialog-overlay" onClick={() => closeDialog(false)}>
          <div className="bpsfw-dialog" onClick={e => e.stopPropagation()}>
            <div className="bpsfw-dialog__icon">⚠️</div>
            <p className="bpsfw-dialog__msg">{dialog.message}</p>
            <div className="bpsfw-dialog__actions">
              <button className="bui-btn bui-btn--secondary" onClick={() => closeDialog(false)}>Cancel</button>
              <button className="bui-btn bui-btn--danger"    onClick={() => closeDialog(true)}>Confirm</button>
            </div>
          </div>
        </div>
      )}
    </ToastCtx.Provider>
  );
};

export const useToast = () => {
  const ctx = useContext(ToastCtx);
  if (!ctx) throw new Error('useToast must be used inside <ToastProvider>');
  return ctx;
};
