import { accountDisplayName } from "../accounts/account-display.js";
import { translate } from "../../shared/i18n.js";

export function formatRateWindow(rateWindow, kind = "primary", now = new Date(), language = "en") {
  const parts = formatRateWindowParts(rateWindow, kind, now, language);
  return `${parts.percent}${parts.detail}`;
}

export const initialUsageStatus = { usage: null, loading: false, error: "", resetPending: false, resetError: "" };

export function reduceUsageStatus(state, action) {
  if (action.type === "reset") return initialUsageStatus;
  if (action.type === "loading" && action.silent) return state;
  if (action.type === "loading") return { ...state, loading: true, error: "" };
  if (action.type === "loaded") return { ...state, usage: action.usage, loading: false, error: "" };
  if (action.type === "failed") return { ...state, loading: false, error: action.error || "usage_unavailable" };
  if (action.type === "reset_credit_pending") return { ...state, resetPending: true, resetError: "" };
  if (action.type === "reset_credit_failed") return { ...state, resetPending: false, resetError: action.error };
  if (action.type === "reset_credit_complete") return { ...state, resetPending: false, resetError: "" };
  return state;
}

export function formatRateWindowParts(rateWindow, kind = "primary", now = new Date(), language = "en") {
  if (!rateWindow) return { percent: "", detail: translate(language, "usage.unavailable") };
  const reset = rateWindow.resetsAt ? new Date(rateWindow.resetsAt) : null;
  const resetLabel = reset && Number.isFinite(reset.getTime())
    ? kind === "primary"
      ? formatClockTime(reset, language)
      : sameLocalDay(reset, now)
        ? formatDuration(reset.getTime() - now.getTime(), language)
        : new Intl.DateTimeFormat(language === "ko" ? "ko-KR" : "en-US", { month: "short", day: "numeric" }).format(reset)
    : translate(language, "usage.unavailable");
  return { percent: `${rateWindow.remainingPercent}%`, detail: language === "ko" ? ` 남음 · ${resetLabel}` : ` left · ${resetLabel}` };
}

export function rateLimitTone(rateWindow) {
  const remaining = rateWindow?.remainingPercent;
  if (!Number.isFinite(remaining)) return "";
  if (remaining >= 50) return "usage-good";
  if (remaining >= 20) return "usage-warning";
  return "usage-low";
}

function formatDuration(milliseconds, language) {
  const totalMinutes = Math.max(0, Math.ceil(milliseconds / 60000));
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  if (language === "ko") return hours === 0 ? `${minutes}분` : minutes === 0 ? `${hours}시간` : `${hours}시간 ${minutes}분`;
  if (hours === 0) return `${minutes}m`;
  if (minutes === 0) return `${hours}h`;
  return `${hours}h ${minutes}m`;
}

function sameLocalDay(left, right) {
  return left.getFullYear() === right.getFullYear()
    && left.getMonth() === right.getMonth()
    && left.getDate() === right.getDate();
}

export function formatContextUsage(usage, language = "en") {
  if (!usage) return translate(language, "usage.unavailable");
  if (Number.isFinite(usage.remainingPercent)) return language === "ko" ? `${usage.remainingPercent}% 남음` : `${usage.remainingPercent}% left`;
  return translate(language, "usage.unavailable");
}

function formatClockTime(date, language) {
  if (language === "ko") return new Intl.DateTimeFormat("ko-KR", { hour: "numeric", minute: "2-digit", hour12: true }).format(date);
  const hours = date.getHours();
  const displayHours = hours % 12 || 12;
  const period = hours < 12 ? "AM" : "PM";
  return `${displayHours}:${String(date.getMinutes()).padStart(2, "0")} ${period}`;
}

export function formatUsageError(error, language = "en") {
  if (!error) return "";
  if (error === "pc_unreachable") return language === "ko" ? "PC 앱 오프라인" : "PC app offline";
  if (error === "account_login_required") return language === "ko" ? "로그인 필요" : "Login required";
  return translate(language, "usage.unavailable");
}

export function statusOwnerId(session, selectedAccountId) {
  return selectedAccountId;
}

export function visibleTokenUsage(session, selectedAccountId) {
  if (!session || session.accountId !== selectedAccountId) return null;
  return session.tokenUsage ?? null;
}

export function lastConversationAccountName(session, accounts = [], language = "en") {
  if (!session?.accountId || !session.codexThreadId) return translate(language, "status.none");
  return accountDisplayName(accounts.find((account) => account.id === session.accountId), accounts);
}
