// Reader: paper / dark / CRT. Recibe capítulo + arco.
//
// Marca el capítulo como leído SOLO cuando el scroll llega al final
// (o el contenido entra completo en la pantalla sin necesidad de scroll).
// Botones al final del cuerpo:
//   - Si hay siguiente capítulo  → CONTINUAR
//   - Si no hay siguiente        → ANTERIOR + VOLVER
// El botón "VOLVER" arriba a la izquierda regresa a la galería de donde vino,
// no al cuarto.

function Reader({
  open,
  chapter,
  arc,
  onClose,
  onContinue,
  onPrevious,
  onScrolledToBottom,
  nextLabel,
}) {
  const [theme, setTheme] = React.useState("paper");
  const scrollRef = React.useRef(null);
  const markedRef = React.useRef(null);

  // Reset el "ya marcado" cada vez que cambia de capítulo.
  React.useEffect(() => {
    markedRef.current = null;
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [chapter?.id]);

  // Listener de scroll: marca leído al llegar (casi) al fondo. También dispara
  // si el contenido entra completo en la pantalla y no hay nada que scrollear.
  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el || !chapter || !onScrolledToBottom) return;

    const checkBottom = () => {
      if (markedRef.current === chapter.id) return;
      const { scrollTop, scrollHeight, clientHeight } = el;
      if (scrollTop + clientHeight >= scrollHeight - 60) {
        markedRef.current = chapter.id;
        onScrolledToBottom(chapter, arc);
      }
    };

    el.addEventListener("scroll", checkBottom);
    // Pequeño delay para que el DOM se asiente antes del primer check.
    const t = setTimeout(checkBottom, 200);
    return () => {
      el.removeEventListener("scroll", checkBottom);
      clearTimeout(t);
    };
  }, [chapter?.id, onScrolledToBottom, arc]);

  if (!chapter) return <div className="reader-wrap" />;

  const body = (chapter && chapter.body) || window.SAMPLE_CHAPTER_BODY;
  const arcTitle = arc ? arc.title : "TROOPER";
  const arcNum = arc ? arc.num : chapter.num;
  const chTotal = arc ? arc.chapters.length : 1;

  const accent = arc ? arc.cover.accent : "#efe9dc";
  const btnBase = {
    fontFamily: "'JetBrains Mono', monospace",
    fontSize: 12,
    letterSpacing: "0.4em",
    fontWeight: 700,
    padding: "16px 32px",
    border: "none",
    borderRadius: 3,
    cursor: "pointer",
    textTransform: "uppercase",
    transition: "transform 0.15s, filter 0.2s",
  };
  const btnPrimary = { ...btnBase, background: accent, color: "#0a0812" };
  const btnSecondary = {
    ...btnBase,
    background: "transparent",
    color: "currentColor",
    border: "1px solid currentColor",
    opacity: 0.7,
  };

  const hover = (e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.filter = "brightness(1.15)"; };
  const unhover = (e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.filter = "brightness(1)"; };

  return (
    <div className={"reader-wrap" + (open ? " open" : "")}>
      <div className={"reader " + theme}>
        <div className="page-bg" />

        <div className="top">
          <div className="left">
            <button className="back" onClick={onClose}>◄ VOLVER</button>
          </div>
          <div style={{ letterSpacing: "0.3em", fontWeight: 600 }}>
            TROOPER · ARCO {arcNum} · CAP {chapter.num}
          </div>
          <div className="right">
            <div className="theme-toggle">
              {["paper","dark","crt"].map(t => (
                <button
                  key={t}
                  className={theme === t ? "active" : ""}
                  onClick={() => setTheme(t)}
                >
                  <span>{t === "paper" ? "PAPEL" : t === "dark" ? "NOCHE" : "CRT"}</span>
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="scroll" ref={scrollRef}>
          <div className="content">
            <div
              className="reader-hero"
              style={{
                background: chapter.image
                  ? "#000"
                  : (arc
                      ? `linear-gradient(135deg, ${arc.spine.bg} 0%, ${arc.cover.accent}33 55%, ${arc.spine.bg} 100%)`
                      : "#1a1520"),
                position: "relative",
                overflow: "hidden",
              }}
            >
              {chapter.image ? (
                <img
                  src={chapter.image}
                  alt=""
                  draggable={false}
                  style={{
                    position: "absolute",
                    inset: 0,
                    width: "100%",
                    height: "100%",
                    objectFit: "cover",
                    objectPosition: `${chapter.imageOffsetX ?? 50}% ${chapter.imageOffsetY ?? 50}%`,
                    transform: `scale(${chapter.imageScale ?? 1})`,
                    transformOrigin: `${chapter.imageOffsetX ?? 50}% ${chapter.imageOffsetY ?? 50}%`,
                    userSelect: "none",
                  }}
                />
              ) : (
                <div className="reader-hero-ph">
                  <span className="reader-hero-num" style={{ color: arc ? arc.cover.accent : "#efe9dc" }}>
                    {chapter.num}
                  </span>
                  <span className="reader-hero-label">IMG · {chapter.num}</span>
                </div>
              )}
            </div>
            <span className="ep">{arcTitle} · CAPÍTULO {chapter.num}</span>
            <h1>{chapter.title}</h1>
            {body.map((p, i) =>
              p === "___" ? <hr key={i} /> : <p key={i}>{p}</p>
            )}

            {(onContinue || onPrevious || onClose) && (
              <div style={{
                display: "flex",
                gap: 14,
                justifyContent: "center",
                flexWrap: "wrap",
                marginTop: 60,
                marginBottom: 20,
              }}>
                {onContinue ? (
                  <button
                    onClick={onContinue}
                    style={btnPrimary}
                    onMouseEnter={hover}
                    onMouseLeave={unhover}
                  >
                    ▸ {nextLabel || "CONTINUAR"}
                  </button>
                ) : (
                  <>
                    {onPrevious && (
                      <button
                        onClick={onPrevious}
                        style={btnSecondary}
                        onMouseEnter={hover}
                        onMouseLeave={unhover}
                      >
                        ◄ ANTERIOR
                      </button>
                    )}
                    <button
                      onClick={onClose}
                      style={btnPrimary}
                      onMouseEnter={hover}
                      onMouseLeave={unhover}
                    >
                      ▸ VOLVER
                    </button>
                  </>
                )}
              </div>
            )}
          </div>
        </div>

        <div className="bottom">
          <div>CAP {chapter.num} / {String(chTotal).padStart(2,"0")}</div>
          <div>BE KIND · REWIND</div>
          <div>AUTOSAVE ●</div>
        </div>
      </div>
    </div>
  );
}

window.Reader = Reader;
