/* Lecteur d'analyse biblique — composants & helpers */

const LBRAND = {
  vert: '#003333',
  vertDeep: '#001e1e',
  or: '#fbb03b',
  parchment: '#f4ede2',
  ivory: '#fbf7f1',
  ink: '#05201e',
  gray: '#9c948a',
  bleu: '#4a6b8a',
  rouge: '#a8453d',
  violet: '#7a4a8a',
};

// Annotation "kinds" — controlled vocabulary with a colour per kind
const KINDS = [
  { id: 'racine',   label: 'Racine',          color: LBRAND.or     },
  { id: 'verbe',    label: 'Verbe',           color: LBRAND.or     },
  { id: 'nom',      label: 'Nom / sujet',     color: LBRAND.vert   },
  { id: 'particule',label: 'Particule',       color: LBRAND.bleu   },
  { id: 'syntaxe',  label: 'Syntaxe',         color: LBRAND.bleu   },
  { id: 'parallel', label: 'Parallélisme',    color: LBRAND.rouge  },
  { id: 'lexique',  label: 'Note lexicale',   color: LBRAND.violet },
];
const kindByKey = Object.fromEntries(KINDS.map(k => [k.id, k]));

// Default lesson — Genèse 1.1–3
const DEFAULT_LESSON = {
  reference: 'Genèse 1 · 1–3',
  series: 'Séance 03 · Bereshit',
  translation: 'Segond 21',
  activeVerseId: 1,
  verses: [
    {
      id: 1, n: 1,
      bibleRef: 'Gen.1.1',
      heb: 'בְּרֵאשִׁ֖ית בָּרָ֣א אֱלֹהִ֑ים אֵ֥ת הַשָּׁמַ֖יִם וְאֵ֥ת הָאָֽרֶץ׃',
      fr:  'Au commencement, Dieu créa les cieux et la terre.',
      annotations: [
        { tokenIdx: 2, tr: 'bārāʾ', kindId: 'verbe',
          note: 'Qal · pf 3ms. Créer ex nihilo. 48 occ. — sujet toujours divin.' },
        { tokenIdx: 4, tr: 'ʾĕlōhîm', kindId: 'nom',
          note: 'Pluriel de majesté ; accord verbal au singulier.' },
      ],
    },
    {
      id: 2, n: 2,
      bibleRef: 'Gen.1.2',
      heb: 'וְהָאָ֗רֶץ הָיְתָ֥ה תֹ֙הוּ֙ וָבֹ֔הוּ וְחֹ֖שֶׁךְ עַל־פְּנֵ֣י תְה֑וֹם וְר֣וּחַ אֱלֹהִ֔ים מְרַחֶ֖פֶת עַל־פְּנֵ֥י הַמָּֽיִם׃',
      fr:  "La terre était informe et vide ; les ténèbres couvraient l'abîme, et l'Esprit de Dieu planait sur les eaux.",
      annotations: [
        { tokenIdx: 4, tr: 'tōhû', kindId: 'parallel',
          note: 'Binôme tōhû wāḇōhû — merisme d\'informité absolue.' },
        { tokenIdx: 20, tr: 'mᵉraḥep̄et', kindId: 'verbe',
          note: 'Piel ptc f.s. — « planer » avec idée protectrice (cf. Dt 32.11).' },
      ],
    },
    {
      id: 3, n: 3,
      bibleRef: 'Gen.1.3',
      heb: 'וַיֹּ֥אמֶר אֱלֹהִ֖ים יְהִ֣י א֑וֹר וַֽיְהִי־אֽוֹר׃',
      fr:  "Dieu dit : « Que la lumière soit ! » Et la lumière fut.",
      annotations: [
        { tokenIdx: 4, tr: 'yᵉhî', kindId: 'syntaxe',
          note: 'Jussif court de הָיָה — performatif divin (création par la parole).' },
      ],
    },
  ],
};

// Tokenise Hebrew preserving separators (whitespace + maqaf).
// Returns array of { text, isWord } in source order.
function tokenize(text) {
  if (!text) return [];
  const out = [];
  // split keeping separators
  const parts = text.split(/(\s+|־)/);
  for (const p of parts) {
    if (p === '') continue;
    if (/^\s+$/.test(p) || p === '־') out.push({ text: p, isWord: false });
    else out.push({ text: p, isWord: true });
  }
  return out;
}

// Words only, with their global token index preserved
function getWordTokens(text) {
  return tokenize(text)
    .map((t, i) => ({ ...t, idx: i }))
    .filter(t => t.isWord);
}

// Helpers
const uid = () => Math.random().toString(36).slice(2, 9);
const clamp = (n, a, b) => Math.max(a, Math.min(b, n));

// Local persistence
const STORAGE_KEY = 'yehi-or.lecteur.v1';
function loadLesson() {
  try {
    const s = localStorage.getItem(STORAGE_KEY);
    if (!s) return DEFAULT_LESSON;
    const parsed = JSON.parse(s);
    return parsed && parsed.verses ? parsed : DEFAULT_LESSON;
  } catch { return DEFAULT_LESSON; }
}
function saveLesson(lesson) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(lesson)); }
  catch (e) { console.warn('save failed', e); }
}

// Normalise un identifiant Strong (« H1 », « 1 », « h001 » → « H1 »)
function normalizeStrongKey(s) {
  if (!s) return null;
  const m = String(s).trim().match(/^([HhGg]?)0*(\d+)$/);
  if (!m) return null;
  const prefix = m[1].toUpperCase() || 'H';
  return prefix + m[2];
}

// Cherche une entrée dans le dictionnaire Strong's hébreu FRANÇAIS
// (source : bible-strong.app, basé sur Louis Segond 1910).
// Retourne { m, h, p, t, lsg, def, o } ou null.
//   m = mot translittéré (ex. "bara'")
//   h = mot hébreu pointé (ex. "בָּרָא")
//   p = phonétique (ex. "baw-raw'")
//   t = type grammatical (ex. "Verbe")
//   lsg = traductions LSG avec compteur d'occurrences
//   def = définition hiérarchique en français
//   o = origine / étymologie
function getStrongEntry(s) {
  const key = normalizeStrongKey(s);
  if (!key) return null;
  if (key.startsWith('G')) return (window.STRONGS_GREEK_FR && window.STRONGS_GREEK_FR[key]) || null;
  return (window.STRONGS_HEBREW_FR && window.STRONGS_HEBREW_FR[key]) || null;
}

// Normalise une référence biblique pour matcher BIBLE_STRONGS.
// Accepte « Gen.1.1 », « gen 1 1 », « Gen 1:1 », etc.
const BIBLE_REF_ALIASES = {
  // Synonymes français → OSIS
  'genese':'Gen','genèse':'Gen','exode':'Exod','levitique':'Lev','lévitique':'Lev','nombres':'Num','deuteronome':'Deut','deutéronome':'Deut',
  'josue':'Josh','josué':'Josh','juges':'Judg','ruth':'Ruth',
  '1samuel':'1Sam','2samuel':'2Sam','1rois':'1Kgs','2rois':'2Kgs',
  '1chroniques':'1Chr','2chroniques':'2Chr','esdras':'Ezra','nehemie':'Neh','néhémie':'Neh',
  'esther':'Esth','job':'Job','psaumes':'Ps','psaume':'Ps','proverbes':'Prov',
  'ecclesiaste':'Eccl','ecclésiaste':'Eccl','cantique':'Song','cantiquedescantiques':'Song',
  'esaie':'Isa','ésaïe':'Isa','isaie':'Isa','isaïe':'Isa',
  'jeremie':'Jer','jérémie':'Jer','lamentations':'Lam',
  'ezechiel':'Ezek','ézéchiel':'Ezek','daniel':'Dan','osee':'Hos','osée':'Hos',
  'joel':'Joel','joël':'Joel','amos':'Amos','abdias':'Obad','jonas':'Jonah',
  'michee':'Mic','michée':'Mic','nahum':'Nah','habacuc':'Hab','sophonie':'Zeph',
  'aggee':'Hag','aggée':'Hag','zacharie':'Zech','malachie':'Mal',
};
function normalizeBibleRef(ref) {
  if (!ref) return null;
  // Sépare livre / chapitre / verset par n'importe quel séparateur
  const m = String(ref).trim().match(/^([\d]?\s*[a-zA-ZéèêëàâäîïôöùûüçÉÈÊËÀÂÄÎÏÔÖÙÛÜÇ]+)\s*[\.:\s]\s*(\d+)\s*[\.:\s]\s*(\d+)$/);
  if (!m) return null;
  let book = m[1].toLowerCase().replace(/\s+/g, '');
  // Si on est déjà sur un nom OSIS valide (Gen, Exod...), on garde
  // Sinon, on cherche un alias français
  if (BIBLE_REF_ALIASES[book]) book = BIBLE_REF_ALIASES[book];
  else {
    // Capitalise au format OSIS (1samuel → 1Sam, gen → Gen)
    book = book.replace(/^(\d)([a-z])/, (_, d, c) => d + c.toUpperCase());
    book = book.charAt(0).toUpperCase() + book.slice(1);
  }
  return `${book}.${m[2]}.${m[3]}`;
}

// Récupère le numéro Strong's d'un mot donné dans un verset référencé.
// `bibleRef` ex. "Gen.1.1", `wordIndex` = position du mot (0-based) dans la liste
// des mots hébreux du verset (séparés par espace + maqaf).
function getStrongForWord(bibleRef, wordIndex) {
  if (!bibleRef || !window.BIBLE_STRONGS) return null;
  const arr = window.BIBLE_STRONGS[bibleRef];
  if (!arr || wordIndex < 0 || wordIndex >= arr.length) return null;
  return arr[wordIndex] || null;
}

// === Traductions françaises personnelles des entrées Strong's ===
// Sauvegardées globalement (réutilisables d'une leçon à l'autre).
const STRONGS_FR_KEY = 'yehi-or.strongs.fr.v1';
function loadStrongsFr() {
  try {
    const s = localStorage.getItem(STRONGS_FR_KEY);
    return s ? JSON.parse(s) : {};
  } catch { return {}; }
}
function saveStrongsFr(map) {
  try { localStorage.setItem(STRONGS_FR_KEY, JSON.stringify(map)); }
  catch (e) { console.warn('save FR strongs failed', e); }
}

Object.assign(window, {
  LBRAND, KINDS, kindByKey, DEFAULT_LESSON,
  tokenize, getWordTokens, uid, clamp,
  loadLesson, saveLesson, STORAGE_KEY,
  normalizeStrongKey, getStrongEntry,
  normalizeBibleRef, getStrongForWord,
  loadStrongsFr, saveStrongsFr,
});
