import React, { useEffect, useState } from 'react'

export default function LoadingOverlay({ show, label = 'Processando...' }) {
  const [elapsedSeconds, setElapsedSeconds] = useState(0)

  useEffect(() => {
    if (!show) {
      setElapsedSeconds(0)
      return undefined
    }

    const startedAt = Date.now()
    const timer = window.setInterval(() => {
      setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1000))
    }, 1000)

    return () => {
      window.clearInterval(timer)
    }
  }, [show])

  function formatElapsed(totalSeconds) {
    const minutes = Math.floor(totalSeconds / 60)
    const seconds = totalSeconds % 60
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
  }

  if (!show) return null

  return (
    <div className="loading-overlay" role="status" aria-live="polite" aria-label={label}>
      <div className="loading-overlay-card">
        <div className="loading-spinner" aria-hidden="true" />
        <div className="loading-overlay-label">{label}</div>
        <div className="loading-overlay-elapsed">Tempo: {formatElapsed(elapsedSeconds)}</div>
      </div>
    </div>
  )
}
