// ============================================
// minhahistoria — "Olhe por dentro" com visualizador real
// ============================================
const { useMemo: useMemoS, useState: useStateS, useEffect: useEffectS } = React;

const PageSpread = () => {
  const showcase = useMemoS(() => {
    const stories = window.STORIES || [];
    const preferred = [
      'castelo de cristal',
      'astronauta',
      'tesouro pirata',
    ];

    const selected = [];
    preferred.forEach((slug) => {
      const found = stories.find((s) => (s.title || '').toLowerCase().includes(slug) && (s.previewPages || []).length > 0);
      if (found) selected.push(found);
    });

    stories.forEach((s) => {
      if (selected.length < 3 && !selected.some((x) => x.id === s.id) && (s.previewPages || []).length > 0) selected.push(s);
    });

    return selected.slice(0, 3);
  }, []);

  const [bookIdx, setBookIdx] = useStateS(0);
  const [pageIdx, setPageIdx] = useStateS(0);

  const activeBook = showcase[bookIdx] || null;
  const pages = (activeBook?.previewPages || []).slice(0, 6);

  useEffectS(() => {
    setPageIdx(0);
  }, [bookIdx]);

  useEffectS(() => {
    if (!pages.length) return;
    const id = setInterval(() => {
      setPageIdx((p) => (p + 1) % pages.length);
    }, 3500);
    return () => clearInterval(id);
  }, [pages.length]);

  if (!activeBook || pages.length === 0) {
    return (
      <section className="container-x" style={{ paddingTop: 64 }}>
        <div style={{ background: 'var(--paper)', borderRadius: 22, padding: '28px 22px', boxShadow: 'var(--shadow-card)', border: '1px solid var(--line)', textAlign: 'center', color: 'var(--muted)', fontWeight: 700 }}>
          Ainda não encontramos páginas internas publicadas para exibir nesta seção.
        </div>
      </section>
    );
  }

  return (
    <section className="container-x" style={{ paddingTop: 64 }}>
      <div style={{ textAlign: 'center', marginBottom: 24 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 12, fontWeight: 900, letterSpacing: '0.16em', color: 'var(--tangerine-deep)', textTransform: 'uppercase' }}><Icon name="book" size={13} /> Como o livro fica por dentro</div>
        <h2 className="font-display" style={{ fontSize: 36, fontWeight: 900, color: 'var(--navy)', margin: '10px auto 6px', textWrap: 'balance', maxWidth: 780 }}>Veja páginas internas <span style={{ color: 'var(--tangerine)' }}>reais</span> antes de comprar</h2>
        <p style={{ margin: 0, fontSize: 15, color: 'var(--muted)' }}>Navegue pelas páginas e veja a qualidade visual da história final impressa.</p>
      </div>

      <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 18 }}>
        {showcase.map((book, idx) => (
          <button key={book.id} onClick={() => setBookIdx(idx)} className={'chip' + (idx === bookIdx ? ' is-active' : '')}>{book.title}</button>
        ))}
      </div>

      <div style={{ background: 'var(--paper)', borderRadius: 24, padding: 16, boxShadow: 'var(--shadow-card)', border: '1px solid var(--line)' }}>
        <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden', background: '#eef1f7', aspectRatio: '16 / 9' }}>
          <img
            src={pages[pageIdx]}
            alt={`Prévia da história ${activeBook.title}, página ${pageIdx + 1}`}
            loading="lazy"
            style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          />

          <button aria-label="Página anterior" onClick={() => setPageIdx((p) => (p - 1 + pages.length) % pages.length)} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', width: 42, height: 42, borderRadius: '50%', border: 'none', background: 'rgba(15,25,52,0.75)', color: 'white', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevron-left" /></button>
          <button aria-label="Próxima página" onClick={() => setPageIdx((p) => (p + 1) % pages.length)} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', width: 42, height: 42, borderRadius: '50%', border: 'none', background: 'rgba(15,25,52,0.75)', color: 'white', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevron-right" /></button>

          <div style={{ position: 'absolute', bottom: 12, left: '50%', transform: 'translateX(-50%)', display: 'flex', gap: 8 }}>
            {pages.map((_, i) => (
              <button
                key={i}
                aria-label={`Ir para página ${i + 1}`}
                onClick={() => setPageIdx(i)}
                style={{ width: i === pageIdx ? 24 : 8, height: 8, borderRadius: 99, border: 'none', background: i === pageIdx ? 'var(--tangerine)' : 'rgba(255,255,255,0.8)', cursor: 'pointer' }}
              />
            ))}
          </div>
        </div>

        <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
          <div>
            <strong style={{ color: 'var(--navy)' }}>{activeBook.title}</strong>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>Página {pageIdx + 1} de {pages.length}</div>
          </div>
          <button className="btn btn-solid-orange" onClick={() => { window.__landing2ScrollToId("catalogo"); }}><Icon name="sparkle" size={14} /> Personalizar esta história</button>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { PageSpread });
