"use client";

import { useSession } from "next-auth/react";
import { useEffect } from "react";
import Link from "next/link";
import { useCreditsStore } from "@/lib/stores/credits-store";

export function WalletBadge() {
  const { data: session, status } = useSession();
  // Shared store dedups across all credit-aware UI on the page; previously
  // both this component and LoyaltyBadge polled independently every 15s.
  const credits = useCreditsStore((s) => s.credits);
  const startPolling = useCreditsStore((s) => s.startPolling);
  const stopPolling = useCreditsStore((s) => s.stopPolling);

  useEffect(() => {
    if (status === "unauthenticated") {
      // C.9: cancel the polling timer and clear the cached balance the
      // moment the user signs out, so the next user signed-in in the
      // same tab doesn't see a stale number.
      stopPolling();
      return;
    }
    if (!session?.user) return;
    startPolling();
  }, [status, session, startPolling, stopPolling]);

  if (!session?.user || credits === null) return null;

  return (
    <Link
      href="/credits/buy"
      className="flex items-center gap-1.5 bg-gold/10 hover:bg-gold/20 border border-gold/30 rounded-lg px-3 py-1.5 transition-all duration-200 group"
      title="Top Up Credits"
    >
      {/* Gold coin icon */}
      <svg
        className="w-4 h-4 text-gold group-hover:scale-110 transition-transform"
        viewBox="0 0 24 24"
        fill="currentColor"
      >
        <circle cx="12" cy="12" r="10" fill="currentColor" opacity="0.2" />
        <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" fill="none" />
        <text x="12" y="16" textAnchor="middle" fontSize="11" fontWeight="bold" fill="currentColor">C</text>
      </svg>
      <span className="text-gold font-semibold text-sm">{credits.toLocaleString()}</span>
    </Link>
  );
}
