/**
 * Subscription plans: Starter $50 · Growth $100 · Enterprise $250 per workspace per month (USD).
 * One source of truth for prices, limits, feature lists shown on pricing pages, and what each plan unlocks
 * (navigation, API path prefixes, voice AI). Legacy plan key "agency" maps to Enterprise.
 */
export type PlanKey = "starter" | "growth" | "enterprise";
export type Feature =
  | "crm" | "inbox" | "forms" | "basic_analytics" | "ai_assistant" | "journeys_basic"
  | "journeys" | "broadcasts" | "social_inbox" | "ads" | "conversions_api" | "attribution" | "scheduled_reports" | "voice_ai" | "ai_agents" | "content_calendar"
  | "agency" | "white_label" | "custom_roles" | "api" | "webhooks" | "ai_autopilot" | "ip_allowlist" | "audit_export" | "priority_support";

export const PLAN_ORDER: PlanKey[] = ["starter", "growth", "enterprise"];

export const PLANS_CATALOG: Record<PlanKey, {
  name: string; priceUsd: number; tagline: string; seats: number; contacts: number; aiCredits: number; workspaces: number;
  features: Feature[]; highlights: string[]; popular?: boolean;
}> = {
  starter: {
    name: "Starter", priceUsd: 50, tagline: "For a small team getting organised", seats: 3, contacts: 2_500, aiCredits: 200, workspaces: 1,
    features: ["crm", "inbox", "forms", "basic_analytics", "ai_assistant", "journeys_basic"],
    highlights: ["3 team seats · 2,500 contacts", "CRM, pipeline, tasks & lead routing", "Unified inbox: WhatsApp, Messenger, SMS, email", "Forms & landing pages", "Up to 3 automation journeys", "Dashboards & basic analytics", "AI help assistant · 200 AI credits", "Two-factor security for every user"],
  },
  growth: {
    name: "Growth", priceUsd: 100, tagline: "For teams running campaigns at scale", seats: 10, contacts: 15_000, aiCredits: 1_500, workspaces: 1, popular: true,
    features: ["crm", "inbox", "forms", "basic_analytics", "ai_assistant", "journeys_basic", "journeys", "broadcasts", "social_inbox", "ads", "conversions_api", "attribution", "scheduled_reports", "voice_ai", "ai_agents", "content_calendar"],
    highlights: ["Everything in Starter, plus:", "10 seats · 15,000 contacts", "Unlimited journeys & broadcasts", "Social inbox: comments, reviews, engagement rules", "Ads sync (Meta, Google, TikTok, LinkedIn) + Conversions API", "Multi-touch attribution & scheduled client reports", "Voice AI assistant & AI qualification agent", "1,500 AI credits"],
  },
  enterprise: {
    name: "Enterprise", priceUsd: 250, tagline: "For agencies and multi-brand businesses", seats: 50, contacts: 100_000, aiCredits: 6_000, workspaces: 25,
    features: ["crm", "inbox", "forms", "basic_analytics", "ai_assistant", "journeys_basic", "journeys", "broadcasts", "social_inbox", "ads", "conversions_api", "attribution", "scheduled_reports", "voice_ai", "ai_agents", "content_calendar", "agency", "white_label", "custom_roles", "api", "webhooks", "ai_autopilot", "ip_allowlist", "audit_export", "priority_support"],
    highlights: ["Everything in Growth, plus:", "50 seats · 100,000 contacts", "Agency sub-accounts & white-label", "Custom roles & IP allowlists", "Platform API & webhooks", "AI autopilot with approvals", "Audit log export", "6,000 AI credits · priority support"],
  },
};

export const normalizePlan = (k?: string | null): PlanKey => (k === "agency" ? "enterprise" : k === "starter" || k === "growth" || k === "enterprise" ? k : "growth");
export const hasFeature = (plan: string | null | undefined, f: Feature) => PLANS_CATALOG[normalizePlan(plan)].features.includes(f);
export const minPlanFor = (f: Feature): PlanKey => PLAN_ORDER.find((p) => PLANS_CATALOG[p].features.includes(f)) ?? "enterprise";

/** Navigation hrefs → feature they need (shown with a PRO badge and routed to billing when locked). */
export const NAV_FEATURE: Record<string, Feature> = {
  "/broadcasts": "broadcasts", "/ads": "ads", "/content": "content_calendar", "/reports": "scheduled_reports", "/ai/approvals": "ai_autopilot",
  "/inbox/rules": "social_inbox", "/inbox/moderation": "social_inbox", "/inbox/analytics": "social_inbox", "/settings/social": "social_inbox",
  "/settings/agency": "agency", "/settings/api": "api", "/settings/roles": "custom_roles",
};
/** API path prefixes → feature (enforced server-side in /api/v1). */
export const API_FEATURE: [prefix: string, feature: Feature][] = [
  ["/broadcasts", "broadcasts"], ["/ads", "ads"], ["/campaigns", "ads"], ["/conversions", "conversions_api"], ["/content", "content_calendar"],
  ["/engagement-rules", "social_inbox"], ["/social", "social_inbox"], ["/moderation", "social_inbox"], ["/reports/engagement", "social_inbox"],
  ["/agency", "agency"], ["/api-keys", "api"], ["/webhooks", "webhooks"], ["/roles", "custom_roles"], ["/ai/actions", "ai_autopilot"], ["/ai/agent", "ai_agents"],
];

export function lockedNav(plan: string | null | undefined) {
  const locked = Object.entries(NAV_FEATURE).filter(([, f]) => !hasFeature(plan, f)).map(([href]) => href);
  if (!hasFeature(plan, "voice_ai")) locked.push("voice");
  return locked;
}

export function apiFeatureFor(path: string): Feature | null {
  const hit = API_FEATURE.find(([prefix]) => path === prefix || path.startsWith(prefix + "/"));
  return hit ? hit[1] : null;
}

export const TRIAL_DAYS = 14;
/** Access is allowed while trialing (until trial end), active, or within a 7-day grace period after a failed payment. */
export function subscriptionAccess(ws: { subscriptionStatus: string; trialEndsAt: Date | null; currentPeriodEnd: Date | null }) {
  const now = Date.now();
  if (ws.subscriptionStatus === "active") return { ok: true as const };
  if (ws.subscriptionStatus === "trialing") return ws.trialEndsAt && ws.trialEndsAt.getTime() > now ? { ok: true as const, trialDaysLeft: Math.ceil((ws.trialEndsAt.getTime() - now) / 86400000) } : { ok: false as const, reason: "trial_ended" as const };
  if (ws.subscriptionStatus === "past_due") return ws.currentPeriodEnd && ws.currentPeriodEnd.getTime() + 7 * 86400000 > now ? { ok: true as const, pastDue: true } : { ok: false as const, reason: "past_due" as const };
  return { ok: false as const, reason: "canceled" as const };
}
