// Gallery: Arcs + Timeline views. Tracks read state via readIds Set.

const { useState, useEffect, useMemo } = React;

// Renombrado de `shade` a `shadeGallery` porque room.jsx también definía un
// `shade` con escala/formato distintos y los scripts babel comparten scope
// global (ver proto_global_scope_gotcha).
function shadeGallery(hex, pct) {
  if (!hex || hex[0] !== "#") return hex;
  const h = hex.slice(1);
  const bigint = parseInt(h.length === 3 ? h.split("").map(c => c+c).join("") : h, 16);
  let r = (bigint >> 16) & 255, g = (bigint >> 8) & 255, b = bigint & 255;
  const k = pct / 100;
  r = Math.max(0, Math.min(255, Math.round(r + (k >= 0 ? (255 - r) : r) * k)));
  g = Math.max(0, Math.min(255, Math.round(g + (k >= 0 ? (255 - g) : g) * k)));
  b = Math.max(0, Math.min(255, Math.round(b + (k >= 0 ? (255 - b) : b) * k)));
  return `rgb(${r},${g},${b})`;
}

// Little check icon for "read" state
function CheckIcon({ size = 12, color = "#0a0812" }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
      <path d="M5 12 L10 17 L19 7" fill="none" stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function arcProgress(arc, readIds) {
  const total = arc.chapters.length;
  const done = arc.chapters.filter(c => readIds.has(c.id)).length;
  return { done, total, allRead: total > 0 && done === total, any: done > 0 };
}

function VHSCoverFace({ ch, readStat }) {
  const { bg, accent } = ch.cover;
  const ink = ch.spine.text;
  const cardBg = `linear-gradient(180deg, #0a0812 0%, rgba(10,8,18,0.92) 30%, rgba(10,8,18,0.55) 55%, rgba(10,8,18,0.0) 75%), ${bg}`;
  return (
    <div className="vhs3d-cover" style={{ background: cardBg }}>
      <div className="vhs3d-cover-num" style={{ color: accent }}>{ch.num}</div>
      {readStat && readStat.allRead && (
        <div className="read-badge cover-badge" title="Arco completo">
          <CheckIcon size={10} color="#0a0812" />
        </div>
      )}
      <div className="vhs3d-cover-img">
        <div className="vhs3d-cover-imgfill">
          {ch.coverImage ? (
            <img className="vhs3d-cover-imgreal" src={ch.coverImage} alt="" />
          ) : (
            <div className="vhs3d-cover-imgplaceholder">IMG · {ch.num}</div>
          )}
        </div>
      </div>
      <div className="vhs3d-cover-title" style={{ color: ink }}>{ch.title}</div>
      <div className="vhs3d-cover-foot">
        <span style={{ color: ink, opacity: 0.75 }}>TROOPER</span>
        <span style={{ color: accent }}>
          {readStat ? `${readStat.done} / ${readStat.total}` : `${ch.num} / 08`}
        </span>
      </div>
    </div>
  );
}

function VHSSpineFace({ ch }) {
  const { bg, stripe, text } = ch.spine;
  return (
    <div className="vhs3d-spine" style={{
      background: `linear-gradient(90deg, ${shadeGallery(bg,-18)} 0%, ${bg} 25%, ${shadeGallery(bg,12)} 50%, ${bg} 75%, ${shadeGallery(bg,-18)} 100%)`,
      color: text,
    }}>
      <div className="vhs3d-spine-top" style={{ borderColor: stripe, color: stripe }}>{ch.num}</div>
      <div className="vhs3d-spine-title">{ch.title}</div>
      <div className="vhs3d-spine-bot" style={{ color: stripe }}>TROOPER · VHS</div>
    </div>
  );
}

function VHSTape3D({ ch, index, total, active, dimmed, onClick, readStat }) {
  const { bg } = ch.spine;
  return (
    <div
      className={"vhs3d-slot" + (active ? " active" : "") + (dimmed ? " dimmed" : "")}
      style={{ "--slot-i": index, "--slot-total": total }}
      onClick={onClick}
    >
      <div className="vhs3d-box">
        <div className="vhs3d-face f-front"><VHSCoverFace ch={ch} readStat={readStat} /></div>
        <div className="vhs3d-face f-back" style={{ background: shadeGallery(bg,-35) }}>
          <div className="vhs3d-back-stripe" style={{ background: ch.spine.stripe }} />
          <div className="vhs3d-back-text">BE KIND · REWIND</div>
        </div>
        <div className="vhs3d-face f-left"><VHSSpineFace ch={ch} /></div>
        <div className="vhs3d-face f-right" style={{ background: shadeGallery(bg,-20) }} />
        <div className="vhs3d-face f-top" style={{ background: shadeGallery(bg,-25) }} />
        <div className="vhs3d-face f-bottom" style={{ background: shadeGallery(bg,-40) }} />
      </div>
    </div>
  );
}

// =====================================================================
// NETFLIX CHAPTER LIST (Arcs view)
// =====================================================================

function ChapterCard({ arc, chapter, onRead, isRead }) {
  const { accent } = arc.cover;
  const thumbBg = chapter.image
    ? "#000"
    : `linear-gradient(135deg, ${shadeGallery(arc.spine.bg, -10)} 0%, ${arc.spine.bg} 55%, ${shadeGallery(arc.spine.bg, 18)} 100%)`;
  return (
    <div className={"nfx-card" + (isRead ? " is-read" : "")}>
      <div className="nfx-thumb" style={{ background: thumbBg, 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="nfx-thumb-grain" />
        )}
        <div className="nfx-thumb-num" style={{ color: accent, textShadow: chapter.image ? "0 2px 8px rgba(0,0,0,0.9)" : undefined }}>{chapter.num}</div>
        {isRead && (
          <div className="read-badge thumb-badge" title="Leído">
            <CheckIcon size={10} color="#0a0812" />
          </div>
        )}
      </div>
      <div className="nfx-meta">
        <div className="nfx-head">
          <div className="nfx-title">
            {chapter.title}
            {isRead && <span className="read-pill">LEÍDO</span>}
          </div>
          <div className="nfx-sub" style={{ color: accent }}>
            {arc.title} · EP {chapter.num}
          </div>
        </div>
        <div className="nfx-desc">{chapter.desc}</div>
        <div className="nfx-actions">
          <button
            className="nfx-read"
            style={{ background: accent, color: "#0a0812" }}
            onClick={() => onRead(chapter, arc)}
          >
            ▸ {isRead ? "LEER DE NUEVO" : "LEER"}
          </button>
        </div>
      </div>
    </div>
  );
}

function ChapterPanel({ arc, onRead, onClose, readIds }) {
  if (!arc) return null;
  const { accent } = arc.cover;
  const stat = arcProgress(arc, readIds);
  return (
    <div className="nfx-panel">
      <div className="nfx-panel-head">
        <div className="nfx-panel-titles">
          <div className="nfx-panel-eyebrow" style={{ color: accent }}>
            ARCO {arc.num} · {stat.done} / {stat.total} LEÍDOS
          </div>
          <div className="nfx-panel-title">
            {arc.title}
            {stat.allRead && (
              <span className="read-pill" style={{ marginLeft: 10 }}>COMPLETO</span>
            )}
          </div>
          <div className="nfx-panel-tagline">{arc.tagline}</div>
        </div>
        <button className="nfx-close" onClick={onClose}>✕ CERRAR</button>
      </div>
      <div className="nfx-list">
        {arc.chapters.map((c) => (
          <ChapterCard
            key={c.id}
            arc={arc}
            chapter={c}
            onRead={onRead}
            isRead={readIds.has(c.id)}
          />
        ))}
      </div>
    </div>
  );
}

// =====================================================================
// TIMELINE VIEW
// =====================================================================

function TimelineArcRow({ arc, open, onToggle, onRead, readIds }) {
  const { accent } = arc.cover;
  const bandBg = `linear-gradient(90deg, ${arc.spine.bg} 0%, ${shadeGallery(arc.spine.bg, -25)} 100%)`;
  const stat = arcProgress(arc, readIds);
  return (
    <div className={"tl-arc" + (open ? " open" : "") + (stat.allRead ? " all-read" : "")}>
      <button
        className="tl-arc-head"
        onClick={onToggle}
        style={{ background: bandBg, borderLeft: `4px solid ${accent}` }}
      >
        <div className="tl-arc-num" style={{ color: accent }}>
          {arc.num}
          {stat.allRead && (
            <span className="read-badge arc-badge" title="Arco completo">
              <CheckIcon size={9} color="#0a0812" />
            </span>
          )}
        </div>
        <div className="tl-arc-titles">
          <div className="tl-arc-title">
            {arc.title}
            {stat.allRead && <span className="read-pill">COMPLETO</span>}
          </div>
          <div className="tl-arc-sub">
            {arc.subtitle} · {stat.done} / {stat.total} LEÍDOS
          </div>
          <div className="tl-arc-progress">
            <div
              className="tl-arc-progress-fill"
              style={{
                width: `${(stat.done / stat.total) * 100}%`,
                background: accent,
              }}
            />
          </div>
        </div>
        <div className="tl-arc-tagline">{arc.tagline}</div>
        <div className="tl-arc-chev" style={{ color: accent }}>{open ? "▲" : "▼"}</div>
      </button>

      <div className="tl-arc-body">
        <div className="tl-chapters">
          {arc.chapters.map((c) => {
            const isRead = readIds.has(c.id);
            return (
              <div className={"tl-chapter" + (isRead ? " is-read" : "")} key={c.id}>
                <div className="tl-ch-rail">
                  <div
                    className="tl-ch-dot"
                    style={{ background: isRead ? accent : "rgba(239,233,220,0.2)" }}
                  >
                    {isRead && <CheckIcon size={8} color="#0a0812" />}
                  </div>
                  <div className="tl-ch-line" style={{ background: `${accent}55` }} />
                </div>
                <div
                  className="tl-ch-thumb"
                  style={{
                    background: c.image
                      ? "#000"
                      : `linear-gradient(135deg, ${shadeGallery(arc.spine.bg, -10)} 0%, ${arc.spine.bg} 55%, ${shadeGallery(arc.spine.bg, 18)} 100%)`,
                    position: "relative",
                    overflow: "hidden",
                  }}
                >
                  {c.image && (
                    <img
                      src={c.image}
                      alt=""
                      draggable={false}
                      style={{
                        position: "absolute", inset: 0,
                        width: "100%", height: "100%",
                        objectFit: "cover",
                        objectPosition: `${c.imageOffsetX ?? 50}% ${c.imageOffsetY ?? 50}%`,
                        transform: `scale(${c.imageScale ?? 1})`,
                        transformOrigin: `${c.imageOffsetX ?? 50}% ${c.imageOffsetY ?? 50}%`,
                        userSelect: "none",
                      }}
                    />
                  )}
                  <div className="tl-ch-thumb-num" style={{ color: accent, textShadow: c.image ? "0 2px 8px rgba(0,0,0,0.9)" : undefined }}>{c.num}</div>
                  {isRead && (
                    <div className="read-badge thumb-badge" title="Leído">
                      <CheckIcon size={9} color="#0a0812" />
                    </div>
                  )}
                </div>
                <div className="tl-ch-info">
                  <div className="tl-ch-eyebrow" style={{ color: accent }}>CAP · {c.num}</div>
                  <div className="tl-ch-title">
                    {c.title}
                    {isRead && <span className="read-pill">LEÍDO</span>}
                  </div>
                  <div className="tl-ch-desc">{c.desc}</div>
                </div>
                <button
                  className="tl-ch-read"
                  style={{ background: accent, color: "#0a0812" }}
                  onClick={() => onRead(c, arc)}
                >
                  ▸ {isRead ? "LEER DE NUEVO" : "LEER"}
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ReaderTimelineView({ arcs, onRead, readIds }) {
  const [openId, setOpenId] = useState(arcs[0]?.id ?? null);
  const totalCh = arcs.reduce((n, a) => n + a.chapters.length, 0);
  const readCh = arcs.reduce(
    (n, a) => n + a.chapters.filter(c => readIds.has(c.id)).length,
    0
  );
  return (
    <div className="tl-wrap">
      <div className="tl-head">
        <div className="tl-head-title">LÍNEA DE TIEMPO</div>
        <div className="tl-head-sub">
          {arcs.length} ARCOS · {readCh} / {totalCh} CAPÍTULOS LEÍDOS
        </div>
      </div>
      <div className="tl-list">
        {arcs.map((a) => (
          <TimelineArcRow
            key={a.id}
            arc={a}
            open={openId === a.id}
            onToggle={() => setOpenId(openId === a.id ? null : a.id)}
            onRead={onRead}
            readIds={readIds}
          />
        ))}
      </div>
    </div>
  );
}

// =====================================================================
// GALLERY
// =====================================================================

function Gallery({ open, initialId, onClose, onRead, readIds }) {
  // Use the shared store hook so Gallery siempre tiene la última versión —
  // se re-fetch cuando cambia user, novel-update, o cuando el componente remonta
  // (por ejemplo al alternar EDITOR/LECTOR).
  const [store] = window.NovelStore.useNovelStore();
  const storeArcs = (store && Array.isArray(store.arcs)) ? store.arcs : [];
  const arcs = storeArcs.length ? storeArcs : (window.TROOPER_ARCS || []);
  const [selectedId, setSelectedId] = useState(null);
  const [viewMode, setViewMode] = useState("arcs");
  const safeReadIds = readIds || new Set();

  useEffect(() => {
    if (open) {
      const t = setTimeout(() => setSelectedId(initialId ?? null), 400);
      return () => clearTimeout(t);
    } else {
      setSelectedId(null);
    }
  }, [open, initialId]);

  const current = arcs.find(a => a.id === selectedId) || null;

  const handleRead = (chapter, arc) => {
    onRead(chapter, arc);
  };

  return (
    <div className={"gallery" + (open ? " open" : "")}>
      <button className="gallery-close" onClick={onClose} aria-label="Cerrar">✕</button>

      <div className="view-tabs">
        <div
          className={"view-tab" + (viewMode === "arcs" ? " active" : "")}
          onClick={() => setViewMode("arcs")}
        >
          ARCOS
        </div>
        <div
          className={"view-tab" + (viewMode === "timeline" ? " active" : "")}
          onClick={() => setViewMode("timeline")}
        >
          LÍNEA DE TIEMPO
        </div>
      </div>

      {viewMode === "arcs" ? (
        <>
          <div className="gallery-stage">
            <div className="vhs3d-row">
              {arcs.map((a, i) => (
                <VHSTape3D
                  key={a.id}
                  ch={a}
                  index={i}
                  total={arcs.length}
                  active={current && current.id === a.id}
                  dimmed={current && current.id !== a.id}
                  onClick={() => setSelectedId(a.id)}
                  readStat={arcProgress(a, safeReadIds)}
                />
              ))}
            </div>
          </div>

          <div className="chapter-meta compact">
            <div className="title-mb" style={{ opacity: current ? 1 : 0.3 }}>
              {current ? current.title : "· · ·"}
            </div>
            <div className="ep-tag-arial" style={{ opacity: current ? 1 : 0 }}>
              {current ? current.subtitle : ""}
            </div>
            <div className="year-arial">
              {current ? `${current.year} · ${current.chapters.length} CAPÍTULOS` : "SELECCIONA UN ARCO"}
            </div>
          </div>

          <div className={"nfx-shell" + (current ? " open" : "")}>
            <ChapterPanel
              arc={current}
              onRead={handleRead}
              onClose={() => setSelectedId(null)}
              readIds={safeReadIds}
            />
          </div>
        </>
      ) : (
        <ReaderTimelineView arcs={arcs} onRead={handleRead} readIds={safeReadIds} />
      )}

    </div>
  );
}

window.Gallery = Gallery;
window.ReaderTimelineView = ReaderTimelineView;
