/**
 * Remembers the plan a visitor picked on the landing page so the subscription
 * page can honour it after signup.
 *
 * It has to survive email verification and a fresh login, both of which drop
 * the URL, so a query param alone is not enough — this is the only carrier that
 * lasts across that gap. Plan choice is a preference, not personal data.
 */

const STORAGE_KEY = "mbhs_plan_preference";

export type PlanType = "monthly" | "annual";
export type SubscriptionType = "individual" | "group";

export interface PlanPreference {
  planType: PlanType;
  subscriptionType: SubscriptionType;
}

const PLAN_TYPES: PlanType[] = ["monthly", "annual"];
const SUBSCRIPTION_TYPES: SubscriptionType[] = ["individual", "group"];

/** Narrow untrusted query/storage values to the two known plan shapes. */
export function parsePlanPreference(
  planType: string | undefined,
  subscriptionType: string | undefined
): PlanPreference | null {
  if (!PLAN_TYPES.includes(planType as PlanType)) return null;
  if (!SUBSCRIPTION_TYPES.includes(subscriptionType as SubscriptionType)) return null;
  return {
    planType: planType as PlanType,
    subscriptionType: subscriptionType as SubscriptionType,
  };
}

export function setPlanPreference(preference: PlanPreference): void {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(preference));
  } catch {
    // Storage can be unavailable (private mode, quota). The preference is a
    // convenience — losing it must never break signup.
  }
}

export function getPlanPreference(): PlanPreference | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as Partial<PlanPreference>;
    return parsePlanPreference(parsed.planType, parsed.subscriptionType);
  } catch {
    return null;
  }
}

export function clearPlanPreference(): void {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.removeItem(STORAGE_KEY);
  } catch {
    // Same as above — best effort.
  }
}
