// Loads the bundled Learning library (orchestras / singers / poets) and looks up
// entries by folded name, so a track's orchestra or singer can link to its story.
import { fold } from "./fold.js";
import { dataURL } from "./util.js";

let _data = null;
let _orch = null;
let _sing = null;
let _poet = null;

export async function init() {
  if (_data) return;
  _data = await fetch(dataURL("learning.json")).then(r => r.json())
    .catch(() => ({ orchestras: [], singers: [], poets: [] }));
  _orch = new Map();
  _sing = new Map();
  _poet = new Map();
  for (const e of _data.orchestras || []) _orch.set(fold(e.name), e);
  for (const e of _data.singers || []) _sing.set(fold(e.name), e);
  for (const e of _data.poets || []) _poet.set(fold(e.name), e);
}

export function orchestra(name) { return _orch ? _orch.get(fold(name || "")) || null : null; }
export function singer(name) { return _sing ? _sing.get(fold(name || "")) || null : null; }
export function poet(name) { return _poet ? _poet.get(fold(name || "")) || null : null; }

// Slim list (name/kind/subtitle/fields/bio) for the hover-to-learn term scanner.
export function allEntries() {
  const out = [];
  const add = (kind, arr) => {
    for (const e of arr || []) out.push({ kind, name: e.name, subtitle: e.subtitle, fields: e.fields, bio: e.bio });
  };
  if (_data) { add("orchestra", _data.orchestras); add("singer", _data.singers); }
  return out;
}
