// PANEL DE REFERENCIA — consulta las fichas SIN salir del capítulo que escribes.
// Se abre desde el botón "◆ FICHAS" del editor de capítulo (o con Ctrl+B).
//
// Lo que resuelve: estás en el capítulo 14, no te acuerdas de quién era el tío
// del secundario. Abres, buscas, lees, cierras. Nunca saliste del texto.
//
// Sufijo RP en todo (los .jsx del proto comparten scope global).

const { useState: useStateRP, useEffect: useEffectRP, useMemo: useMemoRP, useRef: useRefRP } = React;

// Ficha en modo lectura. Los SECRETOS van tapados detrás de un click para que
// no te spoilees a ti mismo de reojo mientras escribes.
function RefEntityDetailRP({ entity, entities, arcs, onBack, onToggleChapter, inThisChapter }) {
  const B = window.BibleStore;
  const [showSecrets, setShowSecrets] = useStateRP(false);
  const kindInfo = B.KIND_LABELS[entity.kind] || B.KIND_LABELS.personaje;
  const fields = B.FIELD_GROUPS[entity.kind] || B.FIELD_GROUPS.personaje;

  const chapterNames = useMemoRP(() => {
    const all = window.wbFlatChapters(arcs);
    const ids = new Set((entity.chapters || []).map(c => String(c.chapterId)));
    return all.filter(c => ids.has(String(c.id)));
  }, [entity.chapters, arcs]);

  return (
    <div className="rp-detail">
      <button type="button" className="rp-back" onClick={onBack}>← TODAS LAS FICHAS</button>

      <div className="rp-detail-head">
        <window.EntityAvatar entity={entity} size={64} />
        <div className="rp-detail-head-text">
          <div className="rp-detail-kind" style={{ color: entity.color }}>{kindInfo.singular}</div>
          <div className="rp-detail-name">{entity.name || "(sin nombre)"}</div>
          {entity.alias && <div className="rp-detail-alias">“{entity.alias}”</div>}
        </div>
      </div>

      {entity.oneLiner && <div className="rp-oneliner">{entity.oneLiner}</div>}

      <div className="rp-chips">
        {entity.role && <span className="rp-chip">{entity.role.toUpperCase()}</span>}
        {entity.status && <span className="rp-chip">{entity.status.toUpperCase()}</span>}
        {entity.faction && <span className="rp-chip">{entity.faction}</span>}
        {entity.age && <span className="rp-chip">{entity.age}</span>}
        {entity.origin && <span className="rp-chip">{entity.origin}</span>}
      </div>

      <button
        type="button"
        className={"rp-appear-btn" + (inThisChapter ? " on" : "")}
        onClick={onToggleChapter}
      >
        {inThisChapter ? "✓ APARECE EN ESTE CAPÍTULO" : "+ MARCAR QUE APARECE AQUÍ"}
      </button>

      {fields.map(f => {
        const v = entity[f.k];
        if (!v || !v.trim()) return null;
        return (
          <div key={f.k} className="rp-field">
            <div className="rp-field-label">{f.l}</div>
            <div className="rp-field-text">{v}</div>
          </div>
        );
      })}

      {(entity.links || []).length > 0 && (
        <div className="rp-field">
          <div className="rp-field-label">RELACIONES</div>
          <div className="rp-links">
            {(entity.links || []).map(l => {
              const other = (entities || []).find(e => String(e.id) === String(l.toId));
              return (
                <div key={l.id} className="rp-link">
                  <span className="rp-link-label">{l.label || "—"}</span>
                  <span className="rp-link-to" style={{ color: other?.color }}>
                    {other?.name || "(ficha borrada)"}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {chapterNames.length > 0 && (
        <div className="rp-field">
          <div className="rp-field-label">SALE EN</div>
          <div className="rp-chapters">
            {chapterNames.map(c => (
              <span key={c.id} className="rp-chip" style={{ borderColor: c.accent, color: c.accent }}>
                {c.arcTitle} · {c.num}
              </span>
            ))}
          </div>
        </div>
      )}

      {entity.notes && entity.notes.trim() && (
        <div className="rp-field">
          <div className="rp-field-label">NOTAS</div>
          <div className="rp-field-text">{entity.notes}</div>
        </div>
      )}

      {entity.secrets && entity.secrets.trim() && (
        <div className="rp-field rp-secret">
          <div className="rp-field-label">SECRETOS / SPOILERS</div>
          {showSecrets ? (
            <div className="rp-field-text">{entity.secrets}</div>
          ) : (
            <button type="button" className="rp-reveal" onClick={() => setShowSecrets(true)}>
              ●●●●● MOSTRAR
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// Cajón lateral. Se monta solo cuando está abierto (así no pega a la API cada
// vez que abres un capítulo), pero el store trae caché en memoria: la segunda
// vez que lo abres pinta al instante.
function RefPanelRP({ open, onClose, chapterId, arcs }) {
  const B = window.BibleStore;
  const { bible, setBible, status } = B.useBible();
  const [query, setQuery] = useStateRP("");
  const [kind, setKind] = useStateRP("");   // "" = todas
  const [activeId, setActiveId] = useStateRP(null);
  const inputRef = useRefRP(null);

  const entities = bible.entities || [];

  useEffectRP(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  // Esc cierra el panel.
  useEffectRP(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === "Escape") { e.stopPropagation(); onClose(); } };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);

  const visible = useMemoRP(() => entities.filter(e =>
    (!kind || e.kind === kind) && window.wbMatchesQuery(e, query)
  ), [entities, kind, query]);

  const active = entities.find(e => String(e.id) === String(activeId)) || null;

  // Marca/desmarca "esta ficha aparece en el capítulo que estoy escribiendo".
  const toggleChapter = (entity) => {
    if (!chapterId) return;
    const list = entity.chapters || [];
    const has = list.some(c => String(c.chapterId) === String(chapterId));
    const next = has
      ? list.filter(c => String(c.chapterId) !== String(chapterId))
      : [...list, { chapterId: String(chapterId), note: "" }];
    setBible({
      ...bible,
      entities: entities.map(e => String(e.id) === String(entity.id) ? { ...e, chapters: next } : e),
    });
  };

  if (!open) return null;

  // Fichas que ya están marcadas en este capítulo — arriba, como atajo.
  const here = entities.filter(e =>
    (e.chapters || []).some(c => String(c.chapterId) === String(chapterId))
  );

  return (
    <aside className="rp-drawer">
      <div className="rp-head">
        <span className="rp-title">PANEL DE REFERENCIA</span>
        <span className={"rp-status rp-status-" + status}>
          {status === "saving" ? "guardando…" : status === "error" ? "error" : ""}
        </span>
        <button type="button" className="rp-close" onClick={onClose} title="Cerrar (Esc)">✕</button>
      </div>

      {active ? (
        <div className="rp-body">
          <RefEntityDetailRP
            entity={active}
            entities={entities}
            arcs={arcs}
            onBack={() => setActiveId(null)}
            inThisChapter={(active.chapters || []).some(c => String(c.chapterId) === String(chapterId))}
            onToggleChapter={() => toggleChapter(active)}
          />
        </div>
      ) : (
        <div className="rp-body">
          <input
            ref={inputRef}
            className="admin-input rp-search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Buscar personaje, lugar, objeto…"
          />

          <div className="rp-kind-row">
            <button type="button" className={"rp-kind" + (kind === "" ? " on" : "")} onClick={() => setKind("")}>TODAS</button>
            {B.KINDS.map(k => (
              <button
                key={k}
                type="button"
                className={"rp-kind" + (kind === k ? " on" : "")}
                onClick={() => setKind(k)}
                title={B.KIND_LABELS[k].label}
              >
                {B.KIND_LABELS[k].icon}
              </button>
            ))}
          </div>

          {here.length > 0 && !query && (
            <div className="rp-section">
              <div className="rp-section-title">EN ESTE CAPÍTULO</div>
              {here.map(e => (
                <button key={e.id} type="button" className="rp-row" onClick={() => setActiveId(e.id)} style={{ borderLeftColor: e.color }}>
                  <window.EntityAvatar entity={e} size={30} />
                  <span className="rp-row-text">
                    <span className="rp-row-name">{e.name || "(sin nombre)"}</span>
                    <span className="rp-row-sub">{e.oneLiner || "—"}</span>
                  </span>
                </button>
              ))}
            </div>
          )}

          <div className="rp-section">
            <div className="rp-section-title">
              {query ? `RESULTADOS · ${visible.length}` : "TODAS LAS FICHAS"}
            </div>
            {status === "loading" && <div className="wb-empty-hint">Cargando…</div>}
            {status !== "loading" && visible.length === 0 && (
              <div className="wb-empty-hint">
                {entities.length === 0
                  ? "Todavía no hay fichas. Créalas en la pestaña FICHAS."
                  : "Nada con esa búsqueda."}
              </div>
            )}
            {visible.map(e => (
              <button key={e.id} type="button" className="rp-row" onClick={() => setActiveId(e.id)} style={{ borderLeftColor: e.color }}>
                <window.EntityAvatar entity={e} size={30} />
                <span className="rp-row-text">
                  <span className="rp-row-name">{e.name || "(sin nombre)"}</span>
                  <span className="rp-row-sub">{e.oneLiner || e.alias || "—"}</span>
                </span>
              </button>
            ))}
          </div>
        </div>
      )}
    </aside>
  );
}

window.RefPanel = RefPanelRP;
