import { useState } from 'react'
import api from '../utils/api'

function isEmailVerifiedRow(p) {
  if (!p) return false
  const v = p.email_verified
  return v === true || v === 't' || v === 1 || v === 'true'
}

/**
 * Hinweis + „Erneut senden“, wenn eingeloggt aber E-Mail noch nicht verifiziert (wie Mitai).
 */
export default function EmailVerificationBanner({ profile }) {
  const [resending, setResending] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState('')

  if (!profile?.email || isEmailVerifiedRow(profile)) return null

  const handleResend = async () => {
    if (!profile.email) return
    setResending(true)
    setError('')
    setSuccess(false)
    try {
      await api.resendVerification(profile.email)
      setSuccess(true)
      setTimeout(() => setSuccess(false), 6000)
    } catch (err) {
      setError(err.message || 'Versand fehlgeschlagen')
      setTimeout(() => setError(''), 7000)
    } finally {
      setResending(false)
    }
  }

  return (
    <div
      className="card"
      style={{
        marginBottom: '1.25rem',
        borderLeft: '4px solid #D97706',
        background: 'var(--surface2)',
      }}
      role="status"
    >
      <div
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          alignItems: 'center',
          gap: '12px',
        }}
      >
        <span style={{ fontSize: '1.5rem', lineHeight: 1 }} aria-hidden>
          📧
        </span>
        <div style={{ flex: '1 1 200px' }}>
          <div style={{ fontWeight: 700, fontSize: '0.95rem', color: '#D97706', marginBottom: 4 }}>
            E-Mail noch nicht bestätigt
          </div>
          <p style={{ fontSize: '0.875rem', color: 'var(--text2)', lineHeight: 1.45, margin: 0 }}>
            Bitte prüfe dein Postfach und öffne den Bestätigungslink (auch Spam-Ordner).
            {success && (
              <span style={{ color: 'var(--accent-dark)', fontWeight: 600, marginLeft: 8 }}>Neue Mail wurde angefordert.</span>
            )}
            {error && <span style={{ color: 'var(--danger)', fontWeight: 600, marginLeft: 8 }}>{error}</span>}
          </p>
        </div>
        <button
          type="button"
          className="btn btn-secondary"
          onClick={handleResend}
          disabled={resending || success}
          style={{ flexShrink: 0 }}
        >
          {resending ? 'Sende…' : success ? '✓ Unterwegs' : 'Erneut senden'}
        </button>
      </div>
    </div>
  )
}
