// Jai Mahal Audio Tour — Checkpoint screen (fixed, no outer scroll)
// Top: brand + chapter counter.
// Middle: photo carousel (auto-cycle) or scrollable transcript panel.
// Bottom: PlayerBar with Home · Prev · Play/Pause · Next · Read/Listen.

const { useState, useEffect, useRef, useMemo } = React;

function CheckpointScreen({ chId, onHome, onNext, onPrev, onComplete }) {
  const T = window.TOUR;
  const ch = T.chapters.find((c) => c.id === chId);

  const [mode, setMode] = useState("listen"); // "listen" | "read"
  const audio = useFakeAudio(ch?.durSec || 180, ch?.id, ch?.audioSrc || null);

  // Auto-advance: when the final chapter's audio finishes, surface the closing.
  useEffect(() => {
    if (!ch) return;
    if (audio.t >= ch.durSec && !audio.playing) {
      const isLast = ch.id === T.chapters.length;
      const delay = setTimeout(() => {
        if (isLast) onComplete && onComplete();
        else onNext && onNext();
      }, 1200);
      return () => clearTimeout(delay);
    }
  }, [audio.t, audio.playing, ch]);

  // Photo carousel images: hero first, then gallery
  const carouselImages = useMemo(() => {
    if (!ch) return [];
    const hero = { src: ch.hero, pos: ch.heroPos || "center", caption: ch.tagline };
    return [hero, ...ch.gallery.slice(0, 5)];
  }, [ch]);

  const [imgIdx, setImgIdx] = useState(0);

  // Reset mode + image idx when chapter changes
  useEffect(() => {
    setMode("listen");
    setImgIdx(0);
  }, [chId]);

  if (!ch) return null;

  return (
    <main
      data-screen-label={`0${ch.id} ${ch.title}`}
      style={{
        position: "relative",
        height: "100%",
        background: "var(--cream)",
        color: "var(--ink)",
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
      }}
    >
      {/* ── TOP BAR ───────────────────────────────────────── */}
      <header
        style={{
          flexShrink: 0,
          padding: "14px 18px 12px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          borderBottom: "1px solid var(--border)",
          background: "var(--cream)",
          zIndex: 5,
        }}
      >
        {/* Logo + title — clickable, goes home */}
        <button
          onClick={onHome}
          aria-label="Home"
          style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            background: "transparent",
            border: "none",
            padding: 0,
            margin: 0,
            cursor: "pointer",
            color: "inherit",
            textAlign: "left",
          }}
        >
          <BrandCrest size={26} opacity={0.95} />
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 1,
              lineHeight: 1,
            }}
          >
            <div
              style={{
                fontFamily: "var(--font-serif)",
                fontStyle: "italic",
                fontSize: 14,
                color: "var(--ink)",
              }}
            >
              The Palace Speaks
            </div>
            <div
              style={{
                fontFamily: "var(--font-sans)",
                fontSize: 8,
                letterSpacing: 2,
                color: "var(--gold-dark)",
                textTransform: "uppercase",
                marginTop: 3,
              }}
            >
              Jai Mahal · Audio Tour
            </div>
          </div>
        </button>

        {/* End Tour — jumps to closing screen */}
        <button
          onClick={onComplete}
          aria-label="End tour"
          style={{
            background: "transparent",
            border: "1px solid var(--gold-dark)",
            color: "var(--gold-dark)",
            fontFamily: "var(--font-sans)",
            fontSize: 9,
            letterSpacing: 2,
            textTransform: "uppercase",
            fontWeight: 600,
            padding: "7px 12px",
            cursor: "pointer",
            borderRadius: 2,
          }}
        >
          End Tour
        </button>
      </header>

      {/* ── CONTENT AREA ─────────────────────────────────── */}
      {mode === "listen" ? (
        <ListenMode
          ch={ch}
          images={carouselImages}
          playing={audio.playing}
          imgIdx={imgIdx}
          setImgIdx={setImgIdx}
        />
      ) : (
        <ReadMode ch={ch} />
      )}

      {/* ── PLAYER BAR ──────────────────────────────────── */}
      <PlayerBar
        ch={ch}
        audio={audio}
        onHome={onHome}
        onPrev={onPrev}
        onNext={onNext}
        mode={mode}
        setMode={setMode}
      />
    </main>
  );
}

// ─── LISTEN MODE: full-bleed auto-cycling photo carousel ─────────
function ListenMode({ ch, images, playing, imgIdx, setImgIdx }) {
  return (
    <section
      style={{
        flex: 1,
        position: "relative",
        overflow: "hidden",
        background: "#1a120c",
      }}
    >
      <AutoCarousel
        images={images}
        interval={5000}
        fade={1100}
        paused={!playing}
        onIndexChange={setImgIdx}
      />

      {/* Top gradient — to keep dots legible if needed */}
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          height: 110,
          background:
            "linear-gradient(180deg, rgba(13,9,6,0.55) 0%, rgba(13,9,6,0) 100%)",
          pointerEvents: "none",
        }}
      />
      {/* Bottom gradient — for title legibility */}
      <div
        style={{
          position: "absolute",
          left: 0,
          right: 0,
          bottom: 0,
          height: "55%",
          background:
            "linear-gradient(180deg, rgba(13,9,6,0) 0%, rgba(13,9,6,0.85) 100%)",
          pointerEvents: "none",
        }}
      />

      {/* Caption (active image) — top-left */}
      {images[imgIdx]?.caption && imgIdx > 0 && (
        <div
          key={imgIdx}
          style={{
            position: "absolute",
            top: 16,
            left: 22,
            right: 22,
            fontFamily: "var(--font-serif)",
            fontStyle: "italic",
            fontSize: 12,
            lineHeight: 1.35,
            color: "rgba(255,255,255,0.85)",
            textShadow: "0 1px 6px rgba(0,0,0,0.45)",
            animation: "captionIn 0.6s ease",
          }}
        >
          {images[imgIdx].caption}
        </div>
      )}

      {/* Chapter title overlay — bottom-left */}
      <div
        style={{
          position: "absolute",
          left: 22,
          right: 22,
          bottom: 22,
          color: "white",
        }}
      >
        <div
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: 10,
            letterSpacing: 3.5,
            color: "var(--gold-on-dark)",
            textTransform: "uppercase",
            marginBottom: 8,
          }}
        >
          Chapter {String(ch.id).padStart(2, "0")} of 05
        </div>
        <h1
          style={{
            fontFamily: "var(--font-serif)",
            fontWeight: 400,
            fontStyle: "italic",
            fontSize: 28,
            lineHeight: 1.05,
            margin: 0,
            textWrap: "balance",
            textShadow: "0 2px 14px rgba(0,0,0,0.4)",
          }}
        >
          {ch.title}
        </h1>
      </div>
    </section>
  );
}

// ─── READ MODE: scrollable transcript (text + heading only) ──────
function ReadMode({ ch }) {
  return (
    <section
      style={{
        flex: 1,
        overflowY: "auto",
        overflowX: "hidden",
        background: "var(--cream)",
        WebkitOverflowScrolling: "touch",
        animation: "fadeInUp .4s ease",
      }}
    >
      {/* Title block */}
      <div style={{ padding: "26px 26px 0", textAlign: "center" }}>
        <div
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: 10,
            letterSpacing: 3,
            color: "var(--gold-dark)",
            textTransform: "uppercase",
            marginBottom: 10,
          }}
        >
          Chapter {String(ch.id).padStart(2, "0")} of 05
        </div>
        <h1
          style={{
            fontFamily: "var(--font-serif)",
            fontWeight: 400,
            fontStyle: "italic",
            fontSize: 26,
            lineHeight: 1.12,
            margin: "0 0 14px",
            color: "var(--ink)",
            textWrap: "balance",
          }}
        >
          {ch.title}
        </h1>
        <Rule width={48} />
      </div>

      {/* Transcript */}
      <article style={{ padding: "26px 26px 36px" }}>
        {ch.paragraphs.map((p, i) => (
          <p
            key={i}
            style={{
              fontFamily: "var(--font-serif)",
              fontSize: i === 0 ? 17 : 15.5,
              lineHeight: 1.7,
              color: i === 0 ? "var(--ink)" : "var(--ink-soft-2)",
              margin: "0 0 16px",
              textWrap: "pretty",
            }}
          >
            {i === 0 && (
              <span
                style={{
                  float: "left",
                  fontFamily: "var(--font-serif)",
                  fontSize: 58,
                  lineHeight: 0.85,
                  paddingTop: 6,
                  paddingRight: 10,
                  color: "var(--gold-dark)",
                  fontStyle: "italic",
                }}
              >
                {p.charAt(0)}
              </span>
            )}
            {i === 0 ? p.slice(1) : p}
          </p>
        ))}
      </article>
    </section>
  );
}

// ─── Side panels (kept from earlier version) ──────────────────────
function Timeline({ items }) {
  return (
    <div
      style={{
        background: "var(--cream-2)",
        border: "1px solid var(--border)",
        padding: "18px 20px",
      }}
    >
      <Eyebrow>A Brief Chronology</Eyebrow>
      <ol style={{ listStyle: "none", padding: 0, margin: "12px 0 0" }}>
        {items.map((m, i) => (
          <li
            key={i}
            style={{
              display: "flex",
              gap: 14,
              padding: "10px 0",
              borderBottom: i < items.length - 1 ? "1px dashed var(--border)" : "none",
              alignItems: "baseline",
            }}
          >
            <div
              style={{
                flex: "0 0 60px",
                fontFamily: "var(--font-serif)",
                fontStyle: "italic",
                fontSize: 20,
                lineHeight: 1,
                color: "var(--gold-dark)",
                fontVariantNumeric: "tabular-nums",
              }}
            >
              {m.year}
            </div>
            <div
              style={{
                flex: 1,
                fontFamily: "var(--font-serif)",
                fontSize: 14,
                lineHeight: 1.45,
                color: "var(--ink-soft)",
                textWrap: "pretty",
              }}
            >
              {m.text}
            </div>
          </li>
        ))}
      </ol>
    </div>
  );
}

function FactsGrid({ facts }) {
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        border: "1px solid var(--border)",
        background: "var(--cream-2)",
      }}
    >
      {facts.map((f, i) => (
        <div
          key={i}
          style={{
            padding: "14px 16px",
            borderRight: i % 2 === 0 ? "1px solid var(--border)" : "none",
            borderBottom: i < facts.length - 2 ? "1px solid var(--border)" : "none",
          }}
        >
          <div
            style={{
              fontFamily: "var(--font-sans)",
              fontSize: 9,
              letterSpacing: 2,
              textTransform: "uppercase",
              color: "var(--gold-dark)",
              marginBottom: 4,
            }}
          >
            {f.k}
          </div>
          <div
            style={{
              fontFamily: "var(--font-serif)",
              fontStyle: "italic",
              fontSize: 16,
              lineHeight: 1.2,
              color: "var(--ink)",
            }}
          >
            {f.v}
          </div>
        </div>
      ))}
    </div>
  );
}

function VenuesList({ venues }) {
  return (
    <div
      style={{
        background: "var(--cream-2)",
        border: "1px solid var(--border)",
        padding: "16px 20px 6px",
      }}
    >
      <Eyebrow>Within the Walls</Eyebrow>
      <ul style={{ listStyle: "none", padding: 0, margin: "10px 0 0" }}>
        {venues.map((v, i) => (
          <li
            key={i}
            style={{
              padding: "9px 0",
              borderBottom: i < venues.length - 1 ? "1px dashed var(--border)" : "none",
            }}
          >
            <div
              style={{
                fontFamily: "var(--font-serif)",
                fontStyle: "italic",
                fontSize: 17,
                lineHeight: 1.2,
                color: "var(--ink)",
                marginBottom: 2,
              }}
            >
              {v.name}
            </div>
            <div
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 13,
                lineHeight: 1.4,
                color: "var(--ink-soft)",
              }}
            >
              {v.desc}
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

function Pullquote({ text, attr }) {
  return (
    <blockquote
      style={{
        margin: 0,
        padding: "22px 8px",
        textAlign: "center",
        borderTop: "1px solid var(--border)",
        borderBottom: "1px solid var(--border)",
      }}
    >
      <div style={{ color: "var(--gold-dark)", marginBottom: 10 }}>
        <Icon.Diamond size={8} />
      </div>
      <p
        style={{
          fontFamily: "var(--font-serif)",
          fontStyle: "italic",
          fontWeight: 400,
          fontSize: 20,
          lineHeight: 1.35,
          color: "var(--ink)",
          margin: 0,
          textWrap: "balance",
        }}
      >
        &ldquo;{text}&rdquo;
      </p>
      {attr && (
        <div
          style={{
            marginTop: 12,
            fontFamily: "var(--font-sans)",
            fontSize: 10,
            letterSpacing: 2.5,
            color: "var(--gold-dark)",
            textTransform: "uppercase",
          }}
        >
          {attr}
        </div>
      )}
    </blockquote>
  );
}

window.CheckpointScreen = CheckpointScreen;
