'use client'

import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'

export type ToastKind = 'success' | 'error'

/**
 * Rövid visszajelzés a képernyő aljáról. A `body`-ba renderelődik, hogy
 * semmilyen szülő rétegkontextusa ne szoríthassa a tartalom alá.
 *
 * A szövegváltozást a képernyőolvasók is megkapják (role="status").
 */
export default function Toast({
  kind,
  message,
  onClose,
  duration = 6000,
}: {
  kind: ToastKind
  message: string
  onClose: () => void
  duration?: number
}) {
  const [mounted, setMounted] = useState(false)
  const [leaving, setLeaving] = useState(false)

  useEffect(() => setMounted(true), [])

  useEffect(() => {
    const hide = setTimeout(() => setLeaving(true), duration)
    const gone = setTimeout(onClose, duration + 400)
    return () => {
      clearTimeout(hide)
      clearTimeout(gone)
    }
  }, [duration, onClose])

  if (!mounted) return null

  return createPortal(
    <div className={`toast toast-${kind}${leaving ? ' is-leaving' : ''}`} role="status" aria-live="polite">
      <span className="toast-icon" aria-hidden="true">
        {kind === 'success' ? (
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.5">
            <path d="M4 12.5l5 5L20 6.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        ) : (
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.5">
            <path d="M12 7v6M12 17h.01" strokeLinecap="round" />
            <circle cx="12" cy="12" r="9" strokeWidth="2" />
          </svg>
        )}
      </span>
      <p className="toast-text">{message}</p>
      <button
        type="button"
        className="toast-close"
        onClick={() => {
          setLeaving(true)
          setTimeout(onClose, 400)
        }}
        aria-label="Bezárás"
      >
        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5">
          <path d="M6 6l12 12M18 6L6 18" strokeLinecap="round" />
        </svg>
      </button>
      <span className="toast-bar" style={{ animationDuration: `${duration}ms` }} aria-hidden="true" />
    </div>,
    document.body
  )
}
