// pages-home.jsx — Home + Sobre Santiago

function HeroVideo() {
  return (
    <div className="hero-media">
      <picture>
        <source media="(max-width: 768px)" srcSet="img/hero-mobile.png" />
        <img
          src="img/hero-desktop.jpg"
          alt="Retrato de Santiago Roncagliolo"
          className="hero-img"
          fetchpriority="high"
        />
      </picture>
      <div className="hero-overlay"></div>
      <div className="hero-grain" aria-hidden="true"></div>
    </div>
  );
}

// ─── Tira de citas de prensa rotando ─────────────────────────────
function PressTicker() {
  const T = useT();
  const quotes = PRESS
    .filter((p) => p.kind !== 'video')  // citas literarias, no docu
    .map((p) => ({
      q: p.desc.replace(/^[«"]?/, '').replace(/[»"]?$/, ''),
      src: p.src,
    }));
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) return;
    const t = setInterval(() => setIdx((i) => (i + 1) % quotes.length), 5200);
    return () => clearInterval(t);
  }, [quotes.length]);
  if (!quotes.length) return null;
  return (
    <section className="press-ticker" data-screen-label="01 Inicio · Citas prensa" aria-label={T('Citas de prensa','Press quotes','Παραθέματα Τύπου','Cytaty prasowe')}>
      <div className="container">
        <div className="rule-h reveal"><span className="num">III</span> {T('La crítica dice','The press says','Η κριτική λέει','Prasa mówi')}</div>
        <div className="press-ticker-stage reveal">
          {quotes.map((q, i) => (
            <blockquote key={i} className={`press-ticker-quote ${i === idx ? 'on' : ''}`}>
              <p className="serif">“{q.q}”</p>
              <cite className="mono">— {q.src}</cite>
            </blockquote>
          ))}
        </div>
        <div className="press-ticker-dots" role="tablist">
          {quotes.map((_, i) => (
            <button
              key={i}
              type="button"
              role="tab"
              aria-selected={i === idx}
              aria-label={`${T('Cita','Quote','Παράθεμα','Cytat')} ${i + 1}`}
              className={`press-ticker-dot ${i === idx ? 'on' : ''}`}
              onClick={() => setIdx(i)}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

function HomePage({ heroPhrase }) {
  const { go } = useRoute();
  const T = useT();
  const { lang } = useLang();
  const click = (e, p) => { e.preventDefault(); go(p); };
  const featured = BOOKS.find((b) => b.slug === 'el-elegido-del-sur');

  const featuredBlurb = lang === 'en'
    ? 'Robert Prevost fought the dark side of the Church: sexual abuse, financial crime, criminal networks… And it was that talent that took him all the way to becoming Pope Leo XIV. At once thriller, reportage and personal memoir, this book explores the thin line between good and evil.'
    : featured.blurb;

  return (
    <>
      <section className="hero" data-screen-label="01 Inicio · Hero">
        <HeroVideo />
        <div className="hero-content">
          <div>
            <div className="eyebrow hero-eyebrow reveal-soft in" style={{ marginBottom: 24 }}>
              {T('Escritor · Lima 1975','Writer · Lima 1975','Συγγραφέας · Λίμα 1975','Pisarz · Lima 1975')}
            </div>
            <h1 className="hero-name">
              <span className="word"><span>Santiago</span></span><br />
              <span className="word"><span>Roncagliolo</span></span>
            </h1>
            <p className="hero-phrase">{heroPhrase}</p>
          </div>
        </div>
        <div className="hero-scroll">
          <span>{T('Descubrir','Discover','Ανακαλύψτε','Odkryj')}</span>
          <span className="line"></span>
        </div>
      </section>

      <section className="section featured-pope" data-screen-label="01 Inicio · Nueva publicación">
        <div className="container">
          <div className="rule-h reveal"><span className="num">I</span> {T('Nueva publicación','New release','Νέα κυκλοφορία','Nowa publikacja')}</div>
          <div className="lit-featured">
            <div className="lit-featured-cover reveal float-in" style={{ '--delay': '0.1s' }}>
              <BookCover title={featured.title} year={featured.year} color={featured.cover} image={featured.image} publisher={featured.publisher} />
            </div>
            <div className="lit-featured-text reveal" style={{ '--delay': '0.2s' }}>
              <div className="eyebrow">Seix Barral · 2026 · {T('No ficción','Non-fiction','Δοκίμιο','Literatura faktu')}</div>
              <h2 className="display-l" style={{ marginTop: 18 }}>{featured.title}</h2>
              <p className="body-l" style={{ marginTop: 20, maxWidth: '46ch' }}>
                {featuredBlurb}
              </p>
              <div className="buy-row">
                <a href="/libro/el-elegido-del-sur" onClick={(e) => click(e, '/libro/el-elegido-del-sur')} className="btn">
                  {T('Ficha del libro','Book details','Πλήρης φιχα','Pełne dane')} <span className="btn-arrow">→</span>
                </a>
              </div>
              <BuyBlock slug={featured.slug} compact />
            </div>
          </div>
        </div>
      </section>

      <section className="section section-doors" data-screen-label="01 Inicio · Tres caminos">
        <div className="container">
          <div className="rule-h reveal"><span className="num">II</span> {T('La obra','The works','Το έργο','Twórczość')}</div>
          <h2 className="display-l reveal" style={{ maxWidth: '20ch', marginBottom: 'clamp(24px, 4vw, 48px)' }}>
            {T('Tres puertas hacia el mismo universo.','Three doors to the same universe.','Τρεις πόρτες προς το ίδιο σύμπαν.','Trzy drzwi do tego samego wszechświata.')}
          </h2>
        </div>
        <div className="doors-teaser doors-three reveal-soft">
          <a href="/obra/literatura" onClick={(e) => click(e, '/obra/literatura')} className="door">
            <img className="door-img" src="img/door-literatura.avif" alt={T('Biblioteca','Library','Βιβλιοθήκη','Biblioteka')} loading="lazy" />
            <div className="door-content">
              <div className="door-num">{T('Camino I','Path I','Διαδρομή I','Ścieżka I')}</div>
              <div className="door-title serif">{T('Literatura','Literature','Λογοτεχνία','Literatura')}</div>
              <div className="door-arrow">{T('Entrar','Enter','Είσοδος','Wejdź')} <span>→</span></div>
            </div>
          </a>
          <a href="/obra/cine" onClick={(e) => click(e, '/obra/cine')} className="door">
            <img className="door-img" src="img/door-cine.jpg" alt={T('Cine','Film','Σινεμά','Film')} loading="lazy" />
            <div className="door-content">
              <div className="door-num">{T('Camino II','Path II','Διαδρομή II','Ścieżka II')}</div>
              <div className="door-title serif">{T('Cine','Film','Σινεμά','Film')}</div>
              <div className="door-arrow">{T('Entrar','Enter','Είσοδος','Wejdź')} <span>→</span></div>
            </div>
          </a>
          <a href="/obra/teatro" onClick={(e) => click(e, '/obra/teatro')} className="door">
            <img className="door-img" src="img/door-teatro.jpg" alt={T('Teatro','Theatre','Θέατρο','Teatr')} loading="lazy" />
            <div className="door-content">
              <div className="door-num">{T('Camino III','Path III','Διαδρομή III','Ścieżka III')}</div>
              <div className="door-title serif">{T('Teatro','Theatre','Θέατρο','Teatr')}</div>
              <div className="door-arrow">{T('Entrar','Enter','Είσοδος','Wejdź')} <span>→</span></div>
            </div>
          </a>
        </div>
      </section>

      <PressTicker />
    </>
  );
}

// ─── SOBRE SANTIAGO ─────────────────────────────────────────────
const MOBILE_BREAKPOINT = 720;

// Los títulos de libros y obras van marcados con *asteriscos* dentro de los
// textos de la biografía; aquí se convierten en cursiva.
function withTitles(text) {
  if (typeof text !== 'string' || text.indexOf('*') === -1) return text;
  return text.split(/\*([^*]+)\*/).map((part, i) => (i % 2 ? <em key={i}>{part}</em> : part));
}

function bioChapters(T) {
  return [
    {
      n: '01', t: T('Personajes rotos','Broken characters','Τσακισμένοι χαρακτήρες','Złamani bohaterowie'),
      p: T(
        'Santiago Roncagliolo sufrió la violencia doméstica y la violencia política del Perú de los ochenta. Marcado por esa niñez, escribe sobre el Mal.',
        'Santiago Roncagliolo lived through domestic violence and the political violence of 1980s Peru. Marked by that childhood, he writes about Evil.'
      ),
      img: 'img/santiago-retrato.webp', imgMobile: 'img/santiago-americana.jpg',
      objPos: '50% 35%', objPosMobile: '50% 50%',
    },
    {
      n: '02', t: T('Trilogía sobre la Iglesia y el poder','A trilogy on the Church and power'),
      p: T(
        'Es autor de tres novelas sobre la Iglesia católica y el poder. *Abril rojo* ganó el Premio Alfaguara y el Independent Foreign Fiction Prize. *Y líbranos del mal* se mantuvo un año en la lista de las novelas peruanas más vendidas. *El año en que nació el demonio* fue considerada una de las novelas del año por la revista Forbes España.',
        'He is the author of three novels about the Catholic Church and power. *Abril rojo* won the Alfaguara Prize and the Independent Foreign Fiction Prize. *Y líbranos del mal* stayed on the Peruvian bestsellers list for a year. *El año en que nació el demonio* was named one of the novels of the year by Forbes Spain.'
      ),
      img: 'img/santiago-libreria.jpg', imgMobile: 'img/santiago-cap2.jpg',
      objPos: '50% 40%', objPosMobile: '20% 50%',
    },
    {
      n: '03', t: T('Tres historias reales','Three true stories'),
      p: T(
        'También ha publicado tres historias reales sobre personajes que encontraron en los libros su sentido y su locura. *El amante uruguayo*, retrato del escritor que amó a Federico García Lorca. *La cuarta espada*, sobre el líder del grupo terrorista Sendero Luminoso. Y *El pastor y los lobos*, sobre el actual papa León XIV.',
        'He has also published three works of non-fiction about real figures who found meaning—and madness—in books. *El amante uruguayo*, a portrait of the writer who loved Federico García Lorca. *La cuarta espada*, about the leader of the terrorist group Shining Path. And *El pastor y los lobos*, about the current Pope Leo XIV.'
      ),
      img: 'img/santiago-cap3-desktop.jpg', imgMobile: 'img/santiago-cap3.jpg',
      objPos: '50% 25%', objPosMobile: '50% 50%',
    },
    {
      n: '04', t: T('Cruzar fronteras y géneros','Crossing borders and genres'),
      p: T(
        'Sus libros han cruzado las fronteras de los países y los géneros. *Pudor* fue llevada al cine en España; *La pena máxima*, en Perú. *La noche de los alfileres* se adaptó al teatro en Polonia. *El accidente* fue un podcast en México, donde también se llevó a plataforma su obra teatral *Tus amigos nunca te harían daño*.',
        'His books have crossed borders and genres. *Pudor* was adapted for film in Spain; *La pena máxima*, in Peru. *La noche de los alfileres* was adapted for theatre in Poland. *El accidente* became a podcast in Mexico, where his play *Tus amigos nunca te harían daño* was also adapted for streaming.'
      ),
      img: 'img/santiago-cap4-desktop.jpg', imgMobile: 'img/santiago-cap4.jpg',
      objPos: '50% 30%', objPosMobile: '50% 50%',
    },
    {
      n: '05', t: T('De Lima a Barcelona','From Lima to Barcelona'),
      p: T(
        'Nació en Lima en 1975. Vivió varios años en México durante su infancia y se trasladó a Madrid en los 2000, donde se asentó como escritor y se consolidó su carrera literaria. Hoy escribe desde Barcelona.',
        'He was born in Lima in 1975. He spent several childhood years in Mexico and moved to Madrid in the 2000s, where he settled as a writer and his literary career took off. Today he writes from Barcelona.'
      ),
      img: 'img/santiago-cap5-desktop.jpg', imgMobile: 'img/santiago-cap5.jpg',
      objPos: '50% 30%', objPosMobile: '70% 50%',
    },
    {
      n: '06', t: T('Reconocimientos','Awards & recognition'),
      p: T(
        'Premio Alfaguara de Novela 2006 por *Abril rojo*. Independent Foreign Fiction Prize 2011 (Reino Unido). Premio El Barco de Vapor 2013 por *El gran escape*. Seleccionado por la revista Granta entre los mejores narradores jóvenes en español. Reconocido por Forbes España entre los mejores libros del año 2023. Sus libros están traducidos a más de 20 idiomas.',
        'Alfaguara Novel Prize 2006 for *Abril rojo*. Independent Foreign Fiction Prize 2011 (UK). Premio El Barco de Vapor 2013 for *El gran escape*. Selected by Granta magazine as one of the best young Spanish-language novelists. Named by Forbes Spain among the best books of 2023. His books are translated into more than 20 languages.'
      ),
      img: 'img/santiago-premio-alfaguara.jpg', imgMobile: 'img/santiago-cap6.jpg',
      objPos: '50% 30%', objPosMobile: '50% 50%',
    },
  ];
}

function BioSticky() {
  const ref = useRef(null);
  const T = useT();
  const BIO_CHAPTERS = useMemo(() => bioChapters(T), [T]);
  const [isMobile, setIsMobile] = useState(
    typeof window !== 'undefined' ? window.innerWidth < MOBILE_BREAKPOINT : false
  );
  const [activeFrame, setActiveFrame] = useState(0);
  const [progress, setProgress] = useState(0);

  const frames = useMemo(() => {
    return BIO_CHAPTERS.map((ch, ci) => ({
      chapterIdx: ci,
      type: 'img',
      src: isMobile ? ch.imgMobile : ch.img,
      objPos: isMobile ? (ch.objPosMobile || ch.objPos) : ch.objPos,
    }));
  }, [isMobile, BIO_CHAPTERS]);

  const activeChapter = frames[activeFrame]?.chapterIdx ?? 0;

  useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onScroll = () => {
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = rect.height - vh;
      if (total <= 0) { setActiveFrame(0); return; }
      const scrolled = Math.max(0, -rect.top);
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
      const idx = Math.min(frames.length - 1, Math.floor(p * frames.length * 0.999));
      setActiveFrame(idx);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [frames.length]);

  return (
    <section
      ref={ref}
      className="bio-sticky"
      style={{ height: `${frames.length * 100}vh` }}
      data-screen-label="02 Sobre · Capítulos"
    >
      <div className="bio-sticky-frame">
        <div className="bio-sticky-images">
          {frames.map((f, i) => {
            const isOn = i === activeFrame;
            return (
              <img
                key={i}
                src={f.src}
                alt=""
                className={`bio-sticky-img ${isOn ? 'on' : ''}`}
                style={{ objectPosition: f.objPos || '50% 50%' }}
                loading="lazy"
              />
            );
          })}
          <div className="bio-sticky-img-overlay" aria-hidden="true"></div>
        </div>

        <div className="bio-sticky-text">
          <div className="bio-sticky-count mono">
            {String(activeChapter + 1).padStart(2, '0')} / {String(BIO_CHAPTERS.length).padStart(2, '0')}
          </div>
          {BIO_CHAPTERS.map((c, i) => (
            <div key={i} className={`bio-sticky-chapter ${i === activeChapter ? 'on' : ''}`}>
              <div className="bio-sticky-year mono">{c.n}</div>
              <h3 className="display-m serif">{c.t}</h3>
              <p className="body-l">{withTitles(c.p)}</p>
            </div>
          ))}
        </div>

        <div className="bio-sticky-progress" aria-hidden="true">
          <div className="bio-sticky-progress-bar" style={{ height: `${progress * 100}%` }}></div>
          {BIO_CHAPTERS.map((_, i) => (
            <span key={i} className={`bio-sticky-dot ${i <= activeChapter ? 'on' : ''}`}></span>
          ))}
        </div>
      </div>
    </section>
  );
}

function SobrePage() {
  return (
    <>
      <BioSticky />
    </>
  );
}

Object.assign(window, { HomePage, SobrePage });
