/* global window */
/* ============================================================
   DATA — fetches real data from the FastAPI backend.
   API_BASE is empty when served from FastAPI itself (same origin),
   or set to 'http://localhost:8000' for standalone file dev.
   ============================================================ */

const API_BASE = window.API_BASE !== undefined ? window.API_BASE : "http://localhost:8000";

window.DATA_READY = (async function loadData() {
  const getJson = async (url) => {
    const r = await fetch(url);
    if (!r.ok) throw new Error(`${r.status} ${r.statusText} — ${url}`);
    return r.json();
  };

  try {
    const [spells, powers, schools, powerTypes, powerCategories, classes, origins, races, skills] = await Promise.all([
      getJson(`${API_BASE}/spells?limit=1000`),
      getJson(`${API_BASE}/powers?limit=1000`),
      getJson(`${API_BASE}/meta/schools`),
      getJson(`${API_BASE}/meta/power-types`),
      getJson(`${API_BASE}/meta/power-categories`),
      getJson(`${API_BASE}/classes`),
      getJson(`${API_BASE}/origins`),
      getJson(`${API_BASE}/races`),
      getJson(`${API_BASE}/skills`),
    ]);

    window.SPELLS = spells;
    window.POWERS = powers;
    window.CLASSES = classes;
    window.ORIGINS = origins;
    window.RACES = races;
    window.SKILLS = skills;

    // fetchClassSpells(name, level) — mesma assinatura da API real.
    // Chama GET /classes/{name}/spells?level={n} e retorna a Promise.
    // A UI (class-creator.jsx) só usa await — troca transparente.
    window.fetchClassSpells = async function(className, characterLevel) {
      return getJson(`${API_BASE}/classes/${encodeURIComponent(className)}/spells?level=${characterLevel}`);
    };

    window.fetchClassPowers = async function(className, characterLevel) {
      return getJson(`${API_BASE}/classes/${encodeURIComponent(className)}/powers?level=${characterLevel}`);
    };

    window.fetchRaces = async function() {
      return getJson(`${API_BASE}/races`);
    };

    window.fetchOrigins = async function() {
      return getJson(`${API_BASE}/origins`);
    };

    window.fetchDeities = async function() {
      return getJson(`${API_BASE}/deities`);
    };

    window.fetchDeity = async function(id) {
      return getJson(`${API_BASE}/deities/${id}`);
    };

    window.CHAPTERS = [
      {
        id: "magias",
        label: "Magias",
        subtitle: "Grimório",
        color: "var(--tab-magias)",
        data: spells,
        searchFields: ["name", "description"],
        filterGroups: [
          {
            id: "circle",
            label: "Círculo",
            kind: "circle",
            values: [1, 2, 3, 4, 5],
            match: (it, v) => it.circle === v,
            format: (v) => `${v}º`,
          },
          {
            id: "school",
            label: "Escola",
            kind: "school",
            values: schools,
            match: (it, v) => it.school === v,
            format: (v) => v,
          },
          {
            id: "type",
            label: "Tipo",
            values: ["Arcana", "Divina"],
            match: (it, v) => it.type === v,
            format: (v) => v,
          },
        ],
      },
      {
        id: "poderes",
        label: "Poderes",
        subtitle: "Manual",
        color: "var(--tab-poderes)",
        data: powers,
        searchFields: ["name", "description", "prerequisites"],
        filterGroups: [
          {
            id: "power_type",
            label: "Tipo",
            kind: "power-type",
            values: powerTypes,
            match: (it, v) => it.power_type === v,
            format: (v) => v,
          },
          {
            id: "power_category",
            label: "Categoria",
            values: powerCategories,
            match: (it, v) => it.power_category === v,
            format: (v) => v,
          },
        ],
      },
      {
        id: "racas",
        label: "Raças",
        subtitle: "Personagem",
        color: "var(--tab-racas)",
        data: [],
        filterGroups: [],
      },
      {
        id: "origens",
        label: "Origens",
        subtitle: "Personagem",
        color: "var(--tab-origens)",
        data: [],
        filterGroups: [],
      },
      {
        id: "classes",
        label: "Classes",
        subtitle: "Personagem",
        color: "var(--tab-classes)",
        data: [],
        filterGroups: [],
      },
      {
        id: "divindade",
        label: "Divindade",
        subtitle: "Panteão",
        color: "var(--tab-divindade)",
        data: [],
        filterGroups: [],
      },
      {
        id: "pericias",
        label: "Perícias",
        subtitle: "Personagem",
        color: "var(--tab-pericias)",
        data: [],
        filterGroups: [],
      },
      {
        id: "ficha",
        label: "Ficha",
        subtitle: "Personagem",
        color: "var(--tab-ficha)",
        data: [],
        filterGroups: [],
      },
    ];
  } catch (err) {
    console.error("[Escriba] Falha ao carregar dados da API:", err);
    window.CHAPTERS = [];
    window.SPELLS = [];
    window.POWERS = [];
    window.ORIGINS = [];
    window.RACES = [];
    window.SKILLS = [];
    throw err;
  }
})();
