import { createContext, useContext, useState, useCallback, useEffect } from 'react';

const ConfirmContext = createContext(null);

const DEFAULTS = {
  title: 'Are you sure?',
  message: '',
  confirmLabel: 'Confirm',
  cancelLabel: 'Cancel',
  tone: 'default', // 'default' | 'danger' | 'success'
  icon: null,
};

const TONE_ICON = { default: '❓', danger: '🗑️', success: '✓' };

export function ConfirmProvider({ children }) {
  const [dialog, setDialog] = useState(null);

  // Returns a promise that resolves true (confirm) or false (cancel/dismiss).
  const confirm = useCallback(
    (opts = {}) =>
      new Promise((resolve) => {
        setDialog({ ...DEFAULTS, ...opts, resolve });
      }),
    []
  );

  const settle = useCallback((result) => {
    setDialog((d) => {
      if (d) d.resolve(result);
      return null;
    });
  }, []);

  useEffect(() => {
    if (!dialog) return undefined;
    const onKey = (e) => {
      if (e.key === 'Escape') settle(false);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [dialog, settle]);

  return (
    <ConfirmContext.Provider value={confirm}>
      {children}
      {dialog && (
        <div className="modal-overlay" onMouseDown={() => settle(false)}>
          <div className="modal" role="dialog" aria-modal="true" onMouseDown={(e) => e.stopPropagation()}>
            <div className="modal-body">
              <div className={`modal-icon ${dialog.tone}`}>{dialog.icon || TONE_ICON[dialog.tone] || TONE_ICON.default}</div>
              <h3>{dialog.title}</h3>
              {dialog.message && <p>{dialog.message}</p>}
            </div>
            <div className="modal-actions">
              <button className="btn btn-ghost" onClick={() => settle(false)} autoFocus>
                {dialog.cancelLabel}
              </button>
              <button
                className={`btn ${dialog.tone === 'danger' ? 'btn-danger' : ''}`}
                onClick={() => settle(true)}
              >
                {dialog.confirmLabel}
              </button>
            </div>
          </div>
        </div>
      )}
    </ConfirmContext.Provider>
  );
}

export function useConfirm() {
  const ctx = useContext(ConfirmContext);
  if (!ctx) throw new Error('useConfirm must be used within ConfirmProvider');
  return ctx;
}
