// Shared lazy loader – fetches /data/calculators.json exactly once.
// Because this is a plain fetch (not a JS dynamic import), Vite will NOT
// emit a modulepreload for it, keeping the homepage bundle small.

export interface CalculatorDef {
  slug: string;
  name: string;
  category: string;
  type: string;
  teaser?: string;
  labels: { in1: string; in2: string; in3?: string };
  factor?: number;
  offset?: number;
  hidden?: boolean;
}

let cache: CalculatorDef[] | null = null;
let pending: Promise<CalculatorDef[]> | null = null;

const runtimeHost =
  import.meta.env.PUBLIC_SITE_URL ??
  (import.meta.env.DEV ? 'http://localhost:5173' : 'https://howdoyouconvert.com');

const getCalculatorsUrl = (): string =>
  import.meta.env.SSR
    ? new URL('/data/calculators.json', runtimeHost).toString()
    : '/data/calculators.json';

export async function loadCalculators(): Promise<CalculatorDef[]> {
  if (cache) return cache;
  if (pending) return pending;

  const url = getCalculatorsUrl();
  pending = fetch(url)
    .then(r => r.json())
    .then((data: CalculatorDef[]) => {
      cache = data;
      pending = null;
      return data;
    });

  return pending;
}

export function searchCalculators(calcs: CalculatorDef[], query: string): CalculatorDef[] {
  const q = query.toLowerCase();
  return calcs.filter(c =>
    (c.name.toLowerCase().includes(q) ||
    c.slug.includes(q) ||
    c.labels.in1.toLowerCase().includes(q) ||
    c.labels.in2.toLowerCase().includes(q)) && !c.hidden
  );
}
