"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

interface Props {
  initialBalance: number;
}

// D.1: when Stripe redirects back to /credits?success=true the user previously
// saw their *old* balance with no confirmation, leading to "where are my
// credits?" support tickets. Show a banner immediately and poll the balance
// for up to 30 s so the new total appears as soon as the webhook fires.
export default function StripeSuccessBanner({ initialBalance }: Props) {
  const router = useRouter();
  const [balance, setBalance] = useState<number>(initialBalance);
  const [polling, setPolling] = useState(true);

  useEffect(() => {
    let attempts = 0;
    const poll = async () => {
      attempts += 1;
      try {
        const res = await fetch("/api/credits/balance", { cache: "no-store" });
        if (res.ok) {
          const data = await res.json();
          const next = typeof data.credits === "number" ? data.credits : null;
          if (next !== null && next !== balance) {
            setBalance(next);
            setPolling(false);
            // Refresh the surrounding server component so other dashboards
            // pick up the new balance too.
            router.refresh();
            return;
          }
        }
      } catch {}
      if (attempts >= 10) {
        setPolling(false);
        return;
      }
      window.setTimeout(poll, 3000);
    };
    poll();
    // We intentionally exclude `balance` from deps; we want the loop fixed.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="bg-green-500/10 border border-green-500/30 text-green-300 rounded-lg p-4 mb-6 flex items-start gap-3" role="status" aria-live="polite">
      <svg className="w-5 h-5 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <div className="flex-1">
        <p className="font-semibold">Payment received.</p>
        <p className="text-sm text-green-300/80">
          {polling
            ? "Your credits will appear in a few seconds…"
            : "Your balance is up to date."}
        </p>
      </div>
      <span className="text-2xl font-bold tabular-nums">{balance}</span>
    </div>
  );
}
