"use client";

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { getJackpotSummary } from "@/api/jackpot";
import { formatMinorAsCurrency } from "@/lib/money";

type JackpotResultsStripProps = {
  currencyCode?: string;
};

/** 开奖模块顶部：Jackpot 当前池（公开接口） */
export function JackpotResultsStrip({
  currencyCode = "NPR",
}: JackpotResultsStripProps) {
  const { t } = useTranslation("player");
  const [minor, setMinor] = useState<number | null>(null);
  const [gap, setGap] = useState<number | null>(null);
  const [enabled, setEnabled] = useState(false);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const j = await getJackpotSummary(currencyCode);
        if (!cancelled) {
          setEnabled(j.enabled);
          setMinor(j.current_amount_minor);
          setGap(j.draws_since_last_burst);
        }
      } catch {
        if (!cancelled) {
          setEnabled(false);
          setMinor(null);
          setGap(null);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [currencyCode]);

  if (!enabled || minor === null) {
    return null;
  }

  return (
    <div className="rounded-xl border border-amber-200 bg-gradient-to-r from-amber-100 via-white to-[#f8fbff] px-3 py-3 shadow-[0_8px_20px_rgba(180,83,9,0.08)]">
      <p className="text-[11px] font-black uppercase tracking-normal text-amber-700">
        {t("results.jackpotLabel")}
      </p>
      <p className="font-mono text-lg font-black tabular-nums text-[#0b3f96]">
        {formatMinorAsCurrency(minor, currencyCode.toUpperCase())}
      </p>
      {gap !== null ? (
        <p className="mt-1 text-xs font-semibold text-amber-800">
          {t("results.jackpotGap", { count: gap })}
        </p>
      ) : null}
    </div>
  );
}
