// 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, lang = "en", setLang }) {
  const T = window.TOUR;
  const ch = T.chapters.find((c) => c.id === chId);

  // Resolve language-specific values (durSec / audioSrc / captions / timings).
  const pick = (v) => (v && typeof v === "object" && !Array.isArray(v) ? (v[lang] ?? v.en) : v);
  const durSec = pick(ch?.durSec) || 180;
  const audioSrc = pick(ch?.audioSrc) || null;

  const [mode, setMode] = useState("listen"); // "listen" | "read"
  // Include lang in the key so switching language reloads the correct audio track.
  const audio = useFakeAudio(durSec, ch ? `${ch.id}-${lang}` : null, audioSrc);

  // Auto-advance: when the audio finishes, move to the next chapter / closing.
  useEffect(() => {
    if (!ch) return;
    if (audio.t >= 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, durSec]);

  // Photo carousel images: hero first (at 0s), then the gallery — each carrying
  // an `at` timestamp (seconds) for the CURRENT language's audio track.
  const carouselImages = useMemo(() => {
    if (!ch) return [];
    const hero = {
      src: ch.hero,
      pos: ch.heroPos || "center",
      caption: pick(ch.heroCaption) || ch.tagline,
      at: pick(ch.heroAt) || 0,
    };
    const gallery = ch.gallery.map((g) => ({
      src: g.src,
      pos: g.pos,
      caption: pick(g.caption),
      at: pick(g.at) || 0,
    }));
    return [hero, ...gallery];
  }, [ch, lang]);

  // Image index is driven by the audio's current time: show the last image
  // whose `at` timestamp has been reached. This keeps the visuals in lockstep
  // with the narration (and stays correct through pause / seek / skip).
  const activeIdx = useMemo(() => {
    let idx = 0;
    for (let i = 0; i < carouselImages.length; i++) {
      if (audio.t >= (carouselImages[i].at || 0)) idx = i;
      else break;
    }
    return idx;
  }, [audio.t, carouselImages]);

  const imgIdx = activeIdx;

  // Reset mode when chapter changes (image index follows audio time automatically).
  useEffect(() => {
    setMode("listen");
  }, [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>

        {/* Right side: language toggle + End Tour */}
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <LangToggle lang={lang} setLang={setLang} variant="light" />
          <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>
        </div>
      </header>

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

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

// ─── LISTEN MODE: full-bleed photo carousel, synced to the audio timeline ─────
function ListenMode({ ch, images, playing, imgIdx }) {
  return (
    <section
      style={{
        flex: 1,
        position: "relative",
        overflow: "hidden",
        background: "#1a120c",
      }}
    >
      <AutoCarousel
        images={images}
        index={imgIdx}
        fade={1100}
        fit="contain"
      />

      {/* 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 && (
        <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
        </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, lang = "en" }) {
  const paras = Array.isArray(ch.paragraphs) ? ch.paragraphs : (ch.paragraphs[lang] || ch.paragraphs.en);
  const dropCap = lang === "en"; // Latin drop-cap only; skip for Devanagari.
  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
        </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" }}>
        {paras.map((p, i) => (
          <p
            key={i}
            style={{
              fontFamily: "var(--font-serif)",
              fontSize: i === 0 ? 17 : 15.5,
              lineHeight: lang === "hi" ? 1.85 : 1.7,
              color: i === 0 ? "var(--ink)" : "var(--ink-soft-2)",
              margin: "0 0 16px",
              textWrap: "pretty",
            }}
          >
            {i === 0 && dropCap && (
              <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 && dropCap ? 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;
