"use client";

import { useState } from "react";

export function VerificationBanner({ emailVerified, justVerified }: { emailVerified: boolean; justVerified: "1" | "0" | undefined }) {
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (emailVerified) {
    // Only shown right after clicking the link — not a persistent banner
    // once verified, that would just be noise on every future visit.
    if (justVerified === "1") {
      return <p className="text-label text-success w-full">E-Mail-Adresse bestätigt.</p>;
    }
    return null;
  }

  async function handleResend() {
    setSending(true);
    setError(null);
    try {
      const res = await fetch("/api/account/resend-verification", { method: "POST" });
      const data = await res.json();
      if (!data.ok) {
        setError(data.reason || "Mail konnte nicht gesendet werden.");
        setSending(false);
        return;
      }
      setSent(true);
      setSending(false);
    } catch {
      setError("Mail konnte gerade nicht gesendet werden.");
      setSending(false);
    }
  }

  return (
    <div className="bg-bg-muted rounded-md p-4 flex flex-col gap-1 w-full">
      <p className="text-body-sm text-text-primary">
        {justVerified === "0"
          ? "Der Bestätigungslink ist ungültig oder abgelaufen."
          : "Bitte bestätige deine E-Mail-Adresse."}{" "}
        {!sent && (
          <button type="button" onClick={handleResend} disabled={sending} className="underline font-bold hover:text-brand transition-colors">
            {sending ? "…" : "Erneut senden"}
          </button>
        )}
        {sent && <span className="text-success">Mail wurde erneut gesendet.</span>}
      </p>
      {error && <p className="text-label text-red-600">{error}</p>}
    </div>
  );
}
