import { useEffect, useState } from 'react';
import type { SystemId } from '@/lib/rules';

/** name (lowercased) -> short description, per system. Cached across mounts. */
const cache = new Map<SystemId, Map<string, string>>();

export function useConditionGlossary(system: SystemId): Map<string, string> {
  const [map, setMap] = useState<Map<string, string>>(() => cache.get(system) ?? new Map());

  useEffect(() => {
    if (cache.has(system)) {
      setMap(cache.get(system)!);
      return;
    }
    let cancelled = false;
    void (async () => {
      const m = new Map<string, string>();
      try {
        if (system === '5e') {
          const mod = await import('@/data/srd/conditions.json');
          for (const c of mod.default as { name: string; description?: string }[]) {
            m.set(c.name.toLowerCase(), c.description ?? '');
          }
        } else {
          const res = await fetch(`${import.meta.env.BASE_URL}data/pf2e/conditions.json`);
          if (res.ok) {
            for (const c of (await res.json()) as { name: string; text?: string }[]) {
              m.set(c.name.toLowerCase(), (c.text ?? '').trim().slice(0, 400));
            }
          }
        }
      } catch {
        /* tooltips are best-effort */
      }
      cache.set(system, m);
      if (!cancelled) setMap(m);
    })();
    return () => { cancelled = true; };
  }, [system]);

  return map;
}
