import { site } from '../config/site';
import { FALLBACK_PLANS, type Plan } from '../data/plans';
import type { Lang } from '../i18n';

let cache: Promise<{ plans: Plan[]; source: 'api' | 'fallback' }> | null = null;

const num = (v: unknown, d = 0) => (v === null || v === undefined || v === '' ? d : Number(v));
const lim = (v: unknown) => (v === null || v === undefined || v === '' ? null : Number(v));

/** API module keys → the website's module keys (MODULE_LABELS in data/plans.ts) */
const MODULE_KEYS: Record<string, string> = { driver_mobile: 'driver_access', excel_pdf_export: 'export', company_announcements: 'announcements' };
const modulesOf = (m: unknown): Plan['modules'] => (m && typeof m === 'object'
  ? Object.fromEntries(Object.entries(m as Record<string, boolean>).map(([k, v]) => [MODULE_KEYS[k] || k, Boolean(v)]))
  : {}) as Plan['modules'];

function normalize(p: any): Plan {
  return {
    id: p.id,
    name: String(p.name ?? 'Plan'),
    slug: String(p.slug ?? String(p.name ?? 'plan').toLowerCase().replace(/\s+/g, '-')),
    description: String(p.description ?? ''),
    badge: p.badge ?? null,
    price_monthly: num(p.price_monthly),
    price_quarterly: num(p.price_quarterly, num(p.price_monthly) * 3),
    price_half_yearly: num(p.price_half_yearly, num(p.price_monthly) * 6),
    price_yearly: num(p.price_yearly, num(p.price_monthly) * 12),
    max_trucks: lim(p.max_trucks),
    max_drivers: lim(p.max_drivers),
    max_users: lim(p.max_users),
    max_trailers: lim(p.max_trailers),
    storage_mb: lim(p.storage_mb),
    modules: modulesOf(p.modules),
    support_level: p.support_level ?? 'standard',
    is_popular: Boolean(p.is_popular ?? (p.badge && /popular/i.test(p.badge))),
  };
}

/**
 * Fetches standard plans from the API at BUILD time.
 * Never throws: falls back to static defaults so the build succeeds without the API.
 */
export function getPlans() {
  if (!cache) {
    cache = (async () => {
      const ctrl = new AbortController();
      const timer = setTimeout(() => ctrl.abort(), 4000);
      try {
        const res = await fetch(`${site.buildApiUrl}/public/plans`, { headers: { Accept: 'application/json' }, signal: ctrl.signal });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json();
        const list = Array.isArray(json?.data) ? json.data : [];
        if (!list.length) throw new Error('empty plan list');
        return { plans: list.map(normalize), source: 'api' as const };
      } catch (e) {
        console.warn(`[plans] API unavailable (${(e as Error).message}); using fallback plans.`);
        return { plans: FALLBACK_PLANS, source: 'fallback' as const };
      } finally {
        clearTimeout(timer);
      }
    })();
  }
  return cache;
}

const UNLIMITED: Record<Lang, string> = { en: 'Unlimited', es: 'Ilimitado' };
export const fmtLimit = (v: number | null, lang: Lang = 'en') => (v === null ? UNLIMITED[lang] : v.toLocaleString('en-US'));
export const fmtStorage = (mb: number | null, lang: Lang = 'en') =>
  mb === null ? UNLIMITED[lang] : mb >= 1024 ? `${+(mb / 1024).toFixed(1)} GB` : `${mb} MB`;
export const fmtMoney = (v: number) =>
  v.toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: v % 1 ? 2 : 0, maximumFractionDigits: 2 });
/** Monthly-equivalent price when billed yearly */
export const yearlyPerMonth = (p: Plan) => Math.round((p.price_yearly / 12) * 100) / 100;

/** Billing cycles shown on the pricing toggle: key, label, months, "billed …" wording */
export const CYCLES = [
  { key: 'monthly', label: 'Monthly', months: 1, billed: 'billed monthly' },
  { key: 'quarterly', label: 'Quarterly', months: 3, billed: 'billed every 3 months' },
  { key: 'half_yearly', label: 'Half-yearly', months: 6, billed: 'billed every 6 months' },
  { key: 'yearly', label: 'Yearly', months: 12, billed: 'billed yearly' },
] as const;
export type CycleKey = (typeof CYCLES)[number]['key'];

const CYCLES_ES: Record<CycleKey, { label: string; billed: string }> = {
  monthly: { label: 'Mensual', billed: 'cobro mensual' },
  quarterly: { label: 'Trimestral', billed: 'cobro cada 3 meses' },
  half_yearly: { label: 'Semestral', billed: 'cobro cada 6 meses' },
  yearly: { label: 'Anual', billed: 'cobro anual' },
};
/** the billing cycles in the page language */
export const cyclesFor = (lang: Lang) => CYCLES.map((c) => (lang === 'es' ? { ...c, ...CYCLES_ES[c.key] } : c));

/**
 * Plan description + badge in the page language. Plans come from the API in English; the standard plans
 * (by slug) have a Spanish text here. A plan without one (e.g. a new plan made in Super Admin) shows its English text.
 */
const PLAN_ES: Record<string, string> = {
  solo: 'Para propietarios-operadores con un solo camión.',
  starter: 'Para propietarios-operadores y flotas muy pequeñas.',
  professional: 'Para flotas en crecimiento con choferes en la carretera.',
  business: 'Para transportistas establecidos que lo necesitan todo.',
};
const BADGE_ES: Record<string, string> = { 'most popular': 'Más popular', popular: 'Popular', 'best value': 'Mejor precio', recommended: 'Recomendado', new: 'Nuevo' };
export function planText(p: Plan, lang: Lang) {
  if (lang !== 'es') return { description: p.description, badge: p.badge };
  return {
    description: PLAN_ES[p.slug] ?? p.description,
    badge: p.badge ? BADGE_ES[p.badge.trim().toLowerCase()] ?? p.badge : null,
  };
}

export const cyclePrice = (p: Plan, key: CycleKey) =>
  ({ monthly: p.price_monthly, quarterly: p.price_quarterly, half_yearly: p.price_half_yearly, yearly: p.price_yearly })[key];
/** price per month for a cycle (cents kept) */
export const cyclePerMonth = (p: Plan, key: CycleKey) => {
  const c = CYCLES.find((x) => x.key === key)!;
  return Math.round((cyclePrice(p, key) / c.months) * 100) / 100;
};
/** % saved vs paying monthly for the same months */
export const cycleSaving = (p: Plan, key: CycleKey) => {
  const c = CYCLES.find((x) => x.key === key)!;
  const full = p.price_monthly * c.months;
  return full > 0 ? Math.max(0, Math.round((1 - cyclePrice(p, key) / full) * 100)) : 0;
};
