import { DEFAULT_CREDIT_COST, PLANS, type PlanId } from "./usageMeter";

export type PlanRightsCopy = {
  headline: string;
  /** 比價卡上 4～5 條短權益 */
  bullets: string[];
  /** 結帳頁：你會得到 */
  rights: string[];
  /** 結帳頁：額度 */
  quota: string[];
  notes: string[];
  /** 比價卡／頂欄短行：分項點數 + 約當次數 */
  softCapsLine: string;
  /** 約當次數短行（行銷可讀） */
  approxCallsLine: string;
};

type TFn = (key: string, params?: Record<string, string | number>) => string;

/** soft_caps 是點數；約當次數 = floor(點 / 單次扣點) */
export function planCapParams(id: PlanId, priceLabel?: string) {
  const p = PLANS[id];
  const copy = p.soft_caps.ai_copy;
  const research = p.soft_caps.ai_research;
  const search = p.soft_caps.web_search;
  const image = p.soft_caps.ai_image;
  return {
    n: p.monthly_credits,
    price: priceLabel ?? p.price_label,
    copy,
    research,
    search,
    image,
    copyCalls: Math.floor(copy / DEFAULT_CREDIT_COST.ai_copy),
    researchCalls: Math.floor(research / DEFAULT_CREDIT_COST.ai_research),
    searchCalls: Math.floor(search / DEFAULT_CREDIT_COST.web_search),
    imageCalls: Math.floor(image / DEFAULT_CREDIT_COST.ai_image),
  };
}

/** 購買／比價用文案（用量首頁不堆字）— 由 i18n keys 組成 */
export function getPlanRights(
  id: PlanId,
  t: TFn,
  /** 語系化價格；未傳則用 PLANS.price_label（固定 NT$…／月） */
  formatPrice?: (amountTwd: number) => string,
): PlanRightsCopy {
  const p = PLANS[id];
  const price = formatPrice ? formatPrice(p.price_twd) : p.price_label;
  const caps = planCapParams(id, price);
  return {
    headline: t(`plan.${id}.headline`),
    bullets: [
      t(`plan.${id}.bullet1`, { n: p.monthly_credits }),
      t(`plan.${id}.bullet2`),
      t(`plan.${id}.bullet3`),
      t(`plan.${id}.bullet4`),
    ],
    rights: [
      t(`plan.${id}.right1`),
      t(`plan.${id}.right2`),
      t(`plan.${id}.right3`),
    ],
    quota: [
      t(`plan.${id}.quota1`, { n: p.monthly_credits, price }),
      t("plan.quota2", caps),
    ],
    notes: [t(`plan.${id}.note1`), t(`plan.${id}.note2`)],
    softCapsLine: t("plan.softCapsLine", caps),
    approxCallsLine: t("plan.approxCallsLine", caps),
  };
}

export function planCtaLabel(current: PlanId, target: PlanId, t: TFn): string {
  if (current === target) return t("plan.cta.current");
  const order: PlanId[] = ["free", "starter", "pro"];
  const a = order.indexOf(current);
  const b = order.indexOf(target);
  if (b > a) return t("plan.cta.upgrade");
  if (b < a) return t("plan.cta.downgrade");
  return t("plan.cta.switch");
}
