/* ============================================================
   FicheCard — la fiche 9:16 (format Story / Instagram, 1080×1920)
   Gabarit de référence pour les vidéos produites en batch.
   Conçue à 360×640 px, exportée ×3 → 1080×1920 PNG.
   Lettrine héros (gravure) + prénom Spectral + signature chiffrée
   + une ligne de lecture distillée. Palette terre & bois.
   Props : { word, kindLabel, elemParts, gematrie, nombre, matiere,
             sub, line, onClose }
   ============================================================ */
const { useState: useStateF, useRef: useRefF } = React;

function FicheCard({ word, kindLabel, elemParts, gematrie, nombre, matiere, sub, line, onClose, inline }) {
  const ref = useRefF(null);
  const [busy, setBusy] = useStateF(false);
  const { src, letter } = window.lettrineFor(word);
  const ELM = window.ELEM_META || {};

  async function download() {
    if (!window.htmlToImage || !ref.current) return;
    setBusy(true);
    try {
      const url = await window.htmlToImage.toPng(ref.current, { pixelRatio: 3, cacheBust: true });
      const a = document.createElement("a");
      a.href = url;
      a.download = "oracle-fiche-" + (word || "prenom").toLowerCase().replace(/\s+/g, "-") + ".png";
      a.click();
    } catch (e) {/* silencieux */} finally {setBusy(false);}
  }

  // La carte elle-même (commune au mode inline et au mode modal).
  const card = (
    <div className="fiche-9x16" ref={ref}>
      <div className="fiche-frame">
        <div className="fiche-head">
          <span className="fiche-seal"><span className="fiche-seal-mark"></span>NomPrénom</span>
          {kindLabel ? <span className="fiche-kind">{kindLabel}</span> : null}
        </div>

        <div className="fiche-hero">
          <div className="fiche-lettrine">
            {src ?
            <img className="fiche-lettrine-img" src={src} alt={"Lettrine " + letter} draggable="false" /> :
            <span className="fiche-lettrine-fallback">{letter}</span>}
          </div>
          <div className="fiche-name">{word}</div>
          {sub ? <div className="fiche-sub">{sub}</div> : null}
        </div>

        <div className="fiche-sig">
          <div className="fiche-sig-elems">
            {(elemParts || []).map((e) =>
            <span className={"elem-tag elem-" + e.toLowerCase() + (e === (elemParts || [])[0] ? " elem-lead" : "")} key={e}>
                <span className={"elem-dot elem-" + e.toLowerCase()}></span>{ELM[e] ? ELM[e].nom : e}
              </span>
            )}
          </div>
          <div className="fiche-sig-nums">
            {gematrie != null && <span className="fiche-sig-num">gématrie <b>{gematrie}</b></span>}
            {nombre != null && <span className="fiche-sig-num">nombre <b>{nombre}</b></span>}
            {matiere && <span className="fiche-sig-num">matière <b>{matiere}</b></span>}
          </div>
        </div>

        {line ? <div className="fiche-line">{line}</div> : null}
        <div className="fiche-url">nomprenom.fr</div>
      </div>
    </div>
  );

  const actions = (
    <div className="fiche-actions">
      <button className="fiche-dl-btn" onClick={download} disabled={busy}>{busy ? "Préparation…" : "Télécharger la carte"}</button>
    </div>
  );

  // Mode INLINE : intégré dans la page (aperçu d'en-tête), AUCUNE modale, aucun backdrop.
  if (inline) {
    return (
      <div className="fiche-inline">
        {card}
        {actions}
      </div>
    );
  }

  // Mode MODAL : ouvert sur clic (« Créer la fiche à partager »).
  return ReactDOM.createPortal(
    <React.Fragment>
      <div className="backdrop" onClick={onClose}></div>
      <div className="fiche-modal" role="dialog" aria-modal="true">
        <button className="legal-x fiche-x" onClick={onClose} aria-label="Fermer">×</button>
        {card}
        {actions}
      </div>
    </React.Fragment>,
    document.body);

}
window.FicheCard = FicheCard;
