// src/components/ui/Toast.jsx
// Toast notification system: provider, hook, and renderer.
//
// Usage:
//   1. Wrap your app (or page) with <ToastProvider>
//   2. In any child component: const { toast } = useToast()
//   3. Call: toast.success('Saved!', 'Your changes have been saved.')
//            toast.danger('Error', 'Something went wrong.')
//            toast.warning('Warning', 'Disk space is low.')
//            toast.info('Info', 'A new version is available.')
//
// Each toast auto-dismisses after `duration` ms (default 4000).
// ToastProvider renders the stack itself via a portal — no extra component needed.

import { createContext, useContext, useState, useCallback, useRef } from 'react'
import { createPortal } from 'react-dom'

// ---------------------------------------------------------------------------
// Context
// ---------------------------------------------------------------------------
const ToastContext = createContext(null)

// ---------------------------------------------------------------------------
// Icons (inline — no external dependency)
// ---------------------------------------------------------------------------
function ToastIcon({ variant }) {
  const props = {
    width: 16, height: 16, viewBox: '0 0 16 16',
    fill: 'none', stroke: 'currentColor',
    strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
    'aria-hidden': true,
  }

  if (variant === 'success') return (
    <svg {...props}><path d="M13 4L6 11l-3-3" /></svg>
  )
  if (variant === 'danger') return (
    <svg {...props}><path d="M12 4L4 12M4 4l8 8" /></svg>
  )
  if (variant === 'warning') return (
    <svg {...props}><path d="M8 3v5M8 11v1" /><path d="M3.5 13.5h9L8 2.5l-4.5 11z" /></svg>
  )
  // info
  return (
    <svg {...props}><circle cx="8" cy="8" r="6" /><path d="M8 7v4M8 5.5v.5" /></svg>
  )
}

// ---------------------------------------------------------------------------
// Single Toast item
// ---------------------------------------------------------------------------
function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDismiss }) {
  const [exiting, setExiting] = useState(false)

  const dismiss = useCallback(() => {
    setExiting(true)
    setTimeout(() => onDismiss(id), 300)
  }, [id, onDismiss])

  // Auto-dismiss timer
  const timerRef = useRef(null)
  const startTimer = () => {
    timerRef.current = setTimeout(dismiss, duration)
  }
  const clearTimer = () => clearTimeout(timerRef.current)

  // Start timer on mount
  useState(() => { startTimer() })

  return (
    <div
      className={['toast', `toast-${variant}`, exiting ? 'exiting' : ''].filter(Boolean).join(' ')}
      role="alert"
      aria-live="assertive"
      onMouseEnter={clearTimer}
      onMouseLeave={startTimer}
    >
      <div className="toast-icon">
        <ToastIcon variant={variant} />
      </div>

      <div className="toast-content">
        {title   && <div className="toast-title">{title}</div>}
        {message && <div className="toast-message">{message}</div>}
      </div>

      <button
        className="toast-close"
        onClick={dismiss}
        aria-label="Dismiss notification"
      >
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
          <path d="M2 2l8 8M10 2L2 10" />
        </svg>
      </button>

      {/* Progress bar — shrinks over duration */}
      <div
        className="toast-progress"
        style={{ animationDuration: `${duration}ms` }}
      />
    </div>
  )
}

// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------
let _nextId = 1

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

  const addToast = useCallback((variant, title, message, duration) => {
    const id = _nextId++
    setToasts((prev) => [...prev, { id, variant, title, message, duration }])
    return id
  }, [])

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

  const toast = {
    success: (title, message, duration) => addToast('success', title, message, duration),
    danger:  (title, message, duration) => addToast('danger',  title, message, duration),
    warning: (title, message, duration) => addToast('warning', title, message, duration),
    info:    (title, message, duration) => addToast('info',    title, message, duration),
    dismiss,
  }

  return (
    <ToastContext.Provider value={toast}>
      {children}
      {createPortal(
        <div className="toast-stack" aria-label="Notifications">
          {toasts.map((t) => (
            <ToastItem key={t.id} {...t} onDismiss={dismiss} />
          ))}
        </div>,
        document.body
      )}
    </ToastContext.Provider>
  )
}

// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
export function useToast() {
  const ctx = useContext(ToastContext)
  if (!ctx) throw new Error('useToast must be used inside <ToastProvider>')
  return { toast: ctx }
}

// Default export — the provider (hook exported as named)
export default ToastProvider
