import { formatContextUsage, formatRateWindowParts, formatUsageError, lastConversationAccountName, rateLimitTone } from "./status-state.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { AccountIdentity } from "../accounts/AccountIdentity.jsx";

function RateWindow({ label, rateWindow, kind, loading, error, language, t }) {
  const tone = loading ? "" : rateLimitTone(rateWindow);
  const value = loading
    ? { percent: "", detail: t("status.loading") }
    : error
      ? { percent: "", detail: formatUsageError(error, language) }
      : formatRateWindowParts(rateWindow, kind, new Date(), language);
  return <span className={`rate-window ${tone}`}><strong>{label}</strong> {value.percent && <span className="usage-percent">{value.percent}</span>}<span className="usage-reset">{value.detail}</span></span>;
}

export function ConversationAccountBar({ session, accounts = [], accountMosaic = false }) {
  const { language, t } = useI18n();
  return <div className="chat-account-row"><strong>{t("status.lastAccount")}</strong> <span><AccountIdentity identity={lastConversationAccountName(session, accounts, language)} mosaic={accountMosaic} /></span></div>;
}

export function StatusPanel({ status, tokenUsage, connectionError = "" }) {
  const { language, t } = useI18n();
  return <section className="usage-status" aria-label={t("status.usage")}>
    <RateWindow label={language === "ko" ? "5시간" : "5h"} rateWindow={status.usage?.primary} kind="primary" loading={status.loading} error={status.error} language={language} t={t} />
    <RateWindow label={t("status.weekly")} rateWindow={status.usage?.secondary} kind="weekly" loading={status.loading} error={status.error} language={language} t={t} />
    <span><strong>{t("status.context")}</strong> <span className="usage-value">{formatContextUsage(tokenUsage, language)}</span></span>
    {connectionError && <span className="status-connection-error" role="status">{connectionError}</span>}
  </section>;
}
