export type PlanId = "free" | "pro" | "elite";
export type BillingInterval = "monthly" | "annual";

export type PlanDef = {
  id: PlanId;
  name: string;
  tagline: string;
  priceMonthly: number;
  priceAnnual: number;
  highlight?: boolean;
  features: string[];
  inherits?: string;
};

export const PLANS: PlanDef[] = [
  {
    id: "free",
    name: "Free",
    tagline: "Everything you need to see clearly.",
    priceMonthly: 0,
    priceAnnual: 0,
    features: [
      "Expense tracking",
      "Dashboard & health score",
      "Goals",
      "Budgets",
      "Analytics",
      "5 AI decisions / month",
      "5 AI simulations / month",
      "Basic AI coach",
    ],
  },
  {
    id: "pro",
    name: "Pro",
    tagline: "Unlimited intelligence, no friction.",
    priceMonthly: 9,
    priceAnnual: 79,
    highlight: true,
    inherits: "Everything in Free, plus",
    features: [
      "Unlimited AI decisions",
      "Unlimited AI simulations",
      "Unlimited AI chat",
      "Advanced analytics",
      "Advanced reports",
      "Priority AI",
      "No ads",
    ],
  },
  {
    id: "elite",
    name: "Elite",
    tagline: "Your private financial desk.",
    priceMonthly: 24,
    priceAnnual: 199,
    inherits: "Everything in Pro, plus",
    features: [
      "Early features",
      "Premium AI models",
      "Family accounts",
      "Advanced forecasting",
      "Unlimited exports",
      "Dedicated AI financial coach",
      "Highest AI priority",
    ],
  },
];

export const PLAN_BY_ID: Record<PlanId, PlanDef> = Object.fromEntries(
  PLANS.map((p) => [p.id, p]),
) as Record<PlanId, PlanDef>;

/** Monthly quotas. `null` means unlimited. */
export const PLAN_LIMITS: Record<PlanId, { decisions: number | null; simulations: number | null; ads: boolean }> = {
  free: { decisions: 5, simulations: 5, ads: true },
  pro: { decisions: null, simulations: null, ads: false },
  elite: { decisions: null, simulations: null, ads: false },
};

export const PLAN_RANK: Record<PlanId, number> = { free: 0, pro: 1, elite: 2 };

/** Prefix used by server functions when a monthly quota is exhausted. */
export const LIMIT_ERROR_PREFIX = "PRUDENTIA_LIMIT";

export function parseLimitError(message: string | undefined): "decisions" | "simulations" | null {
  const m = message?.match(new RegExp(`${LIMIT_ERROR_PREFIX}:(decisions|simulations)`));
  return (m?.[1] as "decisions" | "simulations" | undefined) ?? null;
}


export function annualSavingPct(p: PlanDef) {
  if (!p.priceMonthly) return 0;
  return Math.round((1 - p.priceAnnual / (p.priceMonthly * 12)) * 100);
}
