import { useI18n } from "../../i18n/I18nContext";
import { getPlanRights, planCtaLabel } from "../../lib/planRights";
import { PLANS, type PlanId } from "../../lib/usageMeter";
import { Button } from "../ui/Button";
import { Badge } from "../ui/Badge";

type Props = {
  currentId: PlanId;
  formatPrice: (twd: number) => string;
  onChoose: (id: PlanId) => void;
  busy?: boolean;
  /** 強調哪一案（預設 starter） */
  highlighted?: PlanId;
};

/**
 * 標準三欄方案比價（SaaS pricing）。
 */
export function PlanPricingGrid({
  currentId,
  formatPrice,
  onChoose,
  busy = false,
  highlighted = "starter",
}: Props) {
  const { t } = useI18n();

  return (
    <div className="hb-pricing">
      {(Object.keys(PLANS) as PlanId[]).map((id) => {
        const p = PLANS[id];
        const rights = getPlanRights(id, t, formatPrice);
        const current = currentId === id;
        const popular = id === highlighted;
        const manage = current && currentId !== "free";
        const cta = manage ? t("plans.manage") : planCtaLabel(currentId, id, t);

        return (
          <article
            key={id}
            className={`hb-pricing__card${current ? " is-current" : ""}${popular ? " is-popular" : ""}`}
          >
            <header className="hb-pricing__head">
              <div className="hb-pricing__title-row">
                <h3 className="hb-pricing__name">{p.name}</h3>
                {current ? <Badge tone="brand">{t("plans.inUse")}</Badge> : null}
                {!current && popular ? <Badge tone="neutral">{t("plans.recommended")}</Badge> : null}
              </div>
              <p className="hb-pricing__blurb">{rights.headline}</p>
              <p className="hb-pricing__price">
                <strong>{formatPrice(p.price_twd)}</strong>
                <span className="hb-pricing__period">{t("plans.perMonth")}</span>
              </p>
              <p className="hb-pricing__credits">
                {t("plans.creditsPerMonth", { n: p.monthly_credits })}
              </p>
              <p className="hb-pricing__softcaps">{rights.approxCallsLine}</p>
              <p className="hb-pricing__softcaps hb-pricing__softcaps--pts">{rights.softCapsLine}</p>
            </header>

            <ul className="hb-pricing__bullets">
              {rights.bullets.map((b) => (
                <li key={b}>{b}</li>
              ))}
            </ul>

            <div className="hb-pricing__cta">
              <Button
                type="button"
                variant={current ? "ghost" : popular ? "primary" : "secondary"}
                disabled={busy || (current && currentId === "free")}
                onClick={() => onChoose(id)}
              >
                {cta}
              </Button>
            </div>
          </article>
        );
      })}
    </div>
  );
}
