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

const ToastContext = createContext(null);

export function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);

  const addToast = useCallback((message, type = 'success') => {
    const id = Date.now() + Math.random();
    setToasts((prev) => [...prev, { id, message, type }]);
    setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 3000);
  }, []);

  const removeToast = useCallback((id) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);

  return (
    <ToastContext.Provider value={{ addToast }}>
      {children}
      <ToastContainer toasts={toasts} onRemove={removeToast} />
    </ToastContext.Provider>
  );
}

export function useToast() {
  const ctx = useContext(ToastContext);
  if (!ctx) throw new Error('useToast must be used within ToastProvider');
  return ctx;
}

const TYPE_STYLES = {
  success: { background: '#10b981', icon: '✓' },
  error:   { background: '#ef4444', icon: '✕' },
  info:    { background: '#4361EE', icon: 'i' },
};

function ToastContainer({ toasts, onRemove }) {
  if (!toasts.length) return null;
  return (
    <div style={{
      position: 'fixed', bottom: '24px', right: '24px',
      zIndex: 9999, display: 'flex', flexDirection: 'column', gap: '8px',
      pointerEvents: 'none',
    }}>
      {toasts.map((t) => {
        const s = TYPE_STYLES[t.type] || TYPE_STYLES.success;
        return (
          <div
            key={t.id}
            onClick={() => onRemove(t.id)}
            style={{
              background: s.background, color: '#fff',
              padding: '12px 16px', borderRadius: '10px',
              fontSize: '0.88rem', fontWeight: 600,
              boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
              display: 'flex', alignItems: 'center', gap: '10px',
              maxWidth: '320px', pointerEvents: 'all', cursor: 'pointer',
              animation: 'slideInRight 0.2s ease',
              fontFamily: 'var(--font-body)',
            }}
          >
            <span style={{
              width: '20px', height: '20px', borderRadius: '50%',
              background: 'rgba(255,255,255,0.25)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '0.75rem', fontWeight: 800, flexShrink: 0,
            }}>
              {s.icon}
            </span>
            {t.message}
          </div>
        );
      })}
    </div>
  );
}
