// shared.jsx — Nav, Footer, Placeholder, Router, Lang (i18n)
const { useState, useEffect, useRef, useCallback, useMemo, createContext, useContext } = React;

// ─── Router (History API: cada página con su URL real) ────────────
const RouteCtx = createContext({ path: '/', go: () => {} });
const useRoute = () => useContext(RouteCtx);

function RouteProvider({ children }) {
  const [path, setPath] = useState(() => {
    // Compatibilidad con los enlaces antiguos: si alguien llega a /#/obra por
    // un marcador o un enlace ya publicado, lo pasamos a /obra sin recargar.
    const viejo = window.location.hash.replace(/^#/, '');
    if (viejo.startsWith('/')) {
      window.history.replaceState(null, '', viejo);
      return viejo;
    }
    return window.location.pathname || '/';
  });

  useEffect(() => {
    // Atrás y adelante del navegador.
    const onPop = () => {
      setPath(window.location.pathname || '/');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const go = useCallback((to) => {
    if (to === window.location.pathname) return;
    window.history.pushState(null, '', to);
    setPath(to);
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, []);

  return <RouteCtx.Provider value={{ path, go }}>{children}</RouteCtx.Provider>;
}

// ─── i18n (ES/EN/EL/PL) ──────────────────────────────────────────
// Estrategia "C": UI traducida en los 4 idiomas. Contenido literario
// largo (sinopsis, blurbs de libros, descripciones de films/plays/press)
// solo en ES+EN. Quien elija EL/PL ve esa parte en español por defecto.
const LANG_STORAGE_KEY = 'sr-lang';
const LANGS = [
  { code: 'es', name: 'Español',  flag: '🇪🇸' },
  { code: 'en', name: 'English',  flag: '🇬🇧' },
  { code: 'el', name: 'Ελληνικά', flag: '🇬🇷' },
  { code: 'pl', name: 'Polski',   flag: '🇵🇱' },
];

const LangCtx = createContext({ lang: 'es', setLang: () => {} });
const useLang = () => useContext(LangCtx);

// Devuelve la cadena en el idioma activo. Uso: T(es, en, el, pl).
// Si falta EL o PL, cae a EN, y si falta EN cae a ES.
const useT = () => {
  const { lang } = useLang();
  return (es, en, el, pl) => {
    if (lang === 'en') return en ?? es;
    if (lang === 'el') return el ?? en ?? es;
    if (lang === 'pl') return pl ?? en ?? es;
    return es;
  };
};

function LangProvider({ children }) {
  const [lang, setLangState] = useState(() => {
    try {
      const saved = localStorage.getItem(LANG_STORAGE_KEY);
      if (LANGS.find((l) => l.code === saved)) return saved;
    } catch (e) {}
    return null;
  });
  const setLang = useCallback((code) => {
    setLangState(code);
    try { localStorage.setItem(LANG_STORAGE_KEY, code); } catch (e) {}
    try { document.documentElement.lang = code; } catch (e) {}
  }, []);
  useEffect(() => {
    if (lang) { try { document.documentElement.lang = lang; } catch (e) {} }
  }, [lang]);
  const value = useMemo(() => ({ lang: lang || 'es', setLang }), [lang, setLang]);
  return <LangCtx.Provider value={value}>{children}</LangCtx.Provider>;
}

// ─── Selector de idioma (en nav) ─────────────────────────────────
function LangSelector() {
  const { lang, setLang } = useLang();
  const T = (a, b, c, d) => (lang === 'en' ? b : lang === 'el' ? c : lang === 'pl' ? d : a);
  return (
    <label className="buy-country-select lang-select">
      <span className="sr-only">{T('Idioma', 'Language', 'Γλώσσα', 'Język')}</span>
      <select value={lang} onChange={(e) => setLang(e.target.value)}>
        {LANGS.map((l) => (
          <option key={l.code} value={l.code}>{l.name}</option>
        ))}
      </select>
      <span aria-hidden="true" className="buy-country-caret">▾</span>
    </label>
  );
}

// ─── País de compra ──────────────────────────────────────────────
// Se resuelve solo: /api/geo lee la cabecera que Vercel pone en el edge y
// devuelve el país del visitante. Sin cookies ni consentimiento, así que
// funciona igual para quien rechaza la analítica.
//
// Si el visitante lo cambia a mano, esa elección manda y se guarda en local
// (un peruano en Madrid quiere comprar en Perú, y la IP dice España).
const COUNTRY_STORAGE_KEY = 'sr-country';

// Ojo: shared.jsx se carga antes que data.jsx, así que aquí arriba todavía no
// existe STORE_DEFAULT. El valor por defecto del contexto va literal; dentro
// del provider (que se ejecuta al renderizar) ya sí se usa STORE_DEFAULT.
const CountryCtx = createContext({ country: 'ES', setCountry: () => {}, detected: false });
const useCountry = () => useContext(CountryCtx);

function CountryProvider({ children }) {
  const [manual, setManual] = useState(() => {
    try {
      const saved = localStorage.getItem(COUNTRY_STORAGE_KEY);
      if (STORE_COUNTRIES.some((c) => c.code === saved)) return saved;
    } catch (e) {}
    return null;
  });
  const [geo, setGeo] = useState(null);

  useEffect(() => {
    if (manual) return;             // ya eligió: no hace falta preguntar
    let vivo = true;
    fetch('/api/geo')
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (!vivo || !d || !d.country) return;
        if (STORE_COUNTRIES.some((c) => c.code === d.country)) setGeo(d.country);
      })
      .catch(() => {});             // en local o si falla: se queda el defecto
    return () => { vivo = false; };
  }, [manual]);

  const setCountry = useCallback((code) => {
    setManual(code);
    try { localStorage.setItem(COUNTRY_STORAGE_KEY, code); } catch (e) {}
  }, []);

  const value = useMemo(() => ({
    country: manual || geo || STORE_DEFAULT,
    setCountry,
    detected: !!(manual || geo),
  }), [manual, geo, setCountry]);

  return <CountryCtx.Provider value={value}>{children}</CountryCtx.Provider>;
}

// ─── Bloque de compra ────────────────────────────────────────────
// Solo aparece en los libros con tienda: Planeta o Penguin (ver storeUrl).
function BuyBlock({ slug, compact = false }) {
  const T = useT();
  const { country, setCountry } = useCountry();
  const tienda = storeUrl(slug, country);
  if (!tienda) return null;   // ninguna de las dos editoriales lo vende online

  const actual = tienda.country;

  return (
    <div className={`buy-block ${compact ? 'compact' : ''}`}>
      <a href={tienda.url} className="btn btn-solid" target="_blank" rel="noopener noreferrer">
        {tienda.exact
          ? T('Comprar el libro', 'Buy the book', 'Αγοράστε το βιβλίο', 'Kup książkę')
          : T(`Ver en ${tienda.store}`, `See on ${tienda.store}`, `Δείτε στο ${tienda.store}`, `Zobacz na ${tienda.store}`)}
        {' '}<span className="btn-arrow">→</span>
      </a>
      <div className="buy-block-country">
        <span className="mono">{T('Comprando desde', 'Buying from', 'Αγορά από', 'Kupujesz z')}</span>
        <label className="buy-country-select">
          <span className="sr-only">{T('Elige tu país', 'Choose your country', 'Επιλέξτε χώρα', 'Wybierz kraj')}</span>
          <select value={actual.code} onChange={(e) => setCountry(e.target.value)}>
            {STORE_COUNTRIES.map((c) => (
              <option key={c.code} value={c.code}>{c.name}</option>
            ))}
          </select>
          <span aria-hidden="true" className="buy-country-caret">▾</span>
        </label>
      </div>
    </div>
  );
}

// ─── Scroll reveal (respeta prefers-reduced-motion) ──────────────
function useReveal() {
  useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) {
      document.querySelectorAll('.reveal, .reveal-soft').forEach((el) => el.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.05 });
    document.querySelectorAll('.reveal, .reveal-soft').forEach((el) => {
      if (!el.classList.contains('in')) io.observe(el);
    });
    return () => io.disconnect();
  });
}

// ─── SEO por ruta ────────────────────────────────────────────────
// Con rutas reales cada página es indexable por separado, así que cada una
// necesita su propio título, su descripción y su canonical. Antes todo el
// sitio compartía los del index.html.
const SITE_URL = 'https://santiagoroncagliolo.com';

function setMeta(sel, attr, value) {
  const el = document.head.querySelector(sel);
  if (el) el.setAttribute(attr, value);
}

function useSeo() {
  const { path } = useRoute();
  const { lang } = useLang();
  useEffect(() => {
    const T = (es, en, el, pl) => (lang === 'en' ? en : lang === 'el' ? (el || en) : lang === 'pl' ? (pl || en) : es);

    // Título y descripción por ruta. La descripción es lo que Google enseña
    // debajo del enlace: una por página, no la misma repetida.
    const base = 'Santiago Roncagliolo';
    const map = {
      '/':                [T(`${base} · Escritor · Premio Alfaguara`, `${base} · Writer · Alfaguara Prize`, `${base} · Συγγραφέας`, `${base} · Pisarz`),
                           T('Sitio oficial del escritor peruano Santiago Roncagliolo, Premio Alfaguara. Novelas, cine, teatro y prensa.','Official site of Peruvian writer Santiago Roncagliolo, Alfaguara Prize winner. Novels, film, theatre and press.')],
      '/sobre':           [T(`Sobre Santiago · ${base}`, `About Santiago · ${base}`, `Σχετικά · ${base}`, `O autorze · ${base}`),
                           T('Quién es Santiago Roncagliolo: de Lima a Barcelona, su trilogía sobre la Iglesia y el poder, sus historias reales y sus premios.','Who Santiago Roncagliolo is: from Lima to Barcelona, his trilogy on the Church and power, his true stories and his awards.')],
      '/obra':            [T(`Obra · ${base}`, `Works · ${base}`, `Έργο · ${base}`, `Twórczość · ${base}`),
                           T('Toda la obra de Santiago Roncagliolo: libros, cine y series, y teatro.','The complete work of Santiago Roncagliolo: books, film and series, and theatre.')],
      '/obra/literatura': [T(`Literatura · ${base}`, `Books · ${base}`, `Βιβλία · ${base}`, `Książki · ${base}`),
                           T('Los libros de Santiago Roncagliolo: novela, no ficción, cuentos y literatura infantil.','Santiago Roncagliolo’s books: fiction, non-fiction, short stories and children’s books.')],
      '/obra/cine':       [T(`Cine · ${base}`, `Film · ${base}`, `Σινεμά · ${base}`, `Film · ${base}`),
                           T('Películas, series y documentales de Santiago Roncagliolo: adaptaciones de sus novelas y su trabajo como guionista.','Films, series and documentaries: adaptations of his novels and his work as a screenwriter.')],
      '/obra/teatro':     [T(`Teatro · ${base}`, `Theatre · ${base}`, `Θέατρο · ${base}`, `Teatr · ${base}`),
                           T('Santiago Roncagliolo en escena: su monólogo, sus adaptaciones teatrales y sus novelas llevadas al teatro.','Santiago Roncagliolo on stage: his monologue, his stage adaptations and his novels adapted for theatre.')],
      '/medios':          [T(`Crítica · ${base}`, `Press · ${base}`, `Κριτική · ${base}`, `Prasa · ${base}`),
                           T('Lo que dice la crítica sobre los libros de Santiago Roncagliolo: reseñas y entrevistas.','What the press says about Santiago Roncagliolo’s books: reviews and interviews.')],
      '/contacto':        [T(`Contacto · ${base}`, `Contact · ${base}`, `Επικοινωνία · ${base}`, `Kontakt · ${base}`),
                           T('Contacto profesional de Santiago Roncagliolo a través de su agencia literaria Casanovas & Lynch.','Professional contact for Santiago Roncagliolo through his literary agency Casanovas & Lynch.')],
    };

    let titulo, descripcion;
    const libro = path.startsWith('/libro/') && BOOKS.find((b) => b.slug === path.replace('/libro/', ''));
    const film  = path.startsWith('/cine/')  && FILMS.find((f) => f.slug === path.replace('/cine/', ''));

    if (libro) {
      titulo = `${libro.title} · ${base}`;
      descripcion = libro.blurb;
    } else if (film) {
      titulo = `${film.title} · ${base}`;
      descripcion = film.desc;
    } else {
      [titulo, descripcion] = map[path] || map['/'];
    }

    document.title = titulo;
    const url = SITE_URL + (path === '/' ? '/' : path);

    setMeta('meta[name="description"]', 'content', descripcion);
    setMeta('link[rel="canonical"]', 'href', url);
    setMeta('meta[property="og:url"]', 'content', url);
    setMeta('meta[property="og:title"]', 'content', titulo);
    setMeta('meta[property="og:description"]', 'content', descripcion);
    setMeta('meta[name="twitter:title"]', 'content', titulo);
    setMeta('meta[name="twitter:description"]', 'content', descripcion);

    // Datos estructurados de la página. En las fichas de libro describimos el
    // libro (Google puede mostrarlo como resultado enriquecido); en el resto
    // se retira para no dejar el de la página anterior.
    let ld = document.getElementById('ld-page');
    if (libro) {
      if (!ld) {
        ld = document.createElement('script');
        ld.type = 'application/ld+json';
        ld.id = 'ld-page';
        document.head.appendChild(ld);
      }
      ld.textContent = JSON.stringify({
        '@context': 'https://schema.org',
        '@type': 'Book',
        name: libro.title,
        author: { '@type': 'Person', name: 'Santiago Roncagliolo' },
        publisher: { '@type': 'Organization', name: libro.publisher },
        datePublished: String(libro.year),
        inLanguage: 'es',
        genre: libro.genre,
        description: libro.blurb,
        image: SITE_URL + '/' + libro.image,
        url: url,
      });
    } else if (ld) {
      ld.remove();
    }
  }, [path, lang]);
}

// Se mantiene el nombre viejo por compatibilidad con app.jsx.
const useDocTitle = useSeo;

// ─── Nav ─────────────────────────────────────────────────────────
function navItems(lang) {
  const T = (a, b, c, d) => (lang === 'en' ? b : lang === 'el' ? c : lang === 'pl' ? d : a);
  return [
    { num: '01', label: T('Inicio',        'Home',    'Αρχή',     'Strona główna'), path: '/' },
    { num: '02', label: T('Sobre Santiago','About',   'Σχετικά',  'O autorze'),     path: '/sobre' },
    { num: '03', label: T('Obra',          'Works',   'Έργο',     'Twórczość'),     path: '/obra' },
    { num: '04', label: T('Crítica',       'Press',   'Κριτική',  'Prasa'),         path: '/medios' },
    { num: '05', label: T('Contacto',      'Contact', 'Επικοινωνία','Kontakt'),     path: '/contacto' },
  ];
}
const NAV_ITEMS = navItems('es');

function Nav({ menuStyle = 'hamburger' }) {
  const { path, go } = useRoute();
  const { lang } = useLang();
  const NAV = navItems(lang);
  const [scrolled, setScrolled] = useState(false);
  // En la portada el nombre ya está en grande dentro del hero, así que el de
  // la barra sobra: solo aparece cuando el hero se ha ido de la pantalla.
  const [pastHero, setPastHero] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 40);
      setPastHero(window.scrollY > window.innerHeight * 0.6);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [path]);   // al cambiar de página el scroll vuelve arriba: hay que recalcular

  useEffect(() => { setOpen(false); }, [path]);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const isActive = (p) => {
    if (p === '/') return path === '/';
    return path.startsWith(p);
  };

  const handleNav = (e, p) => { e.preventDefault(); go(p); };
  const T = (a, b, c, d) => (lang === 'en' ? b : lang === 'el' ? c : lang === 'pl' ? d : a);

  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''} ${path === '/sobre' ? 'nav-over-image' : ''}`}>
        <a
          href="/"
          onClick={(e) => handleNav(e, '/')}
          className={`nav-brand ${path === '/' && !pastHero ? 'is-hidden' : ''}`}
          aria-hidden={path === '/' && !pastHero ? 'true' : undefined}
          tabIndex={path === '/' && !pastHero ? -1 : undefined}
        >
          Santiago Roncagliolo<span className="dot">.</span>
        </a>

        {menuStyle === 'minimal' && (
          <div className="nav-links show-desktop">
            {NAV.slice(1).map((it) => (
              <a key={it.path} href={it.path} onClick={(e) => handleNav(e, it.path)}
                 className={`nav-link ${isActive(it.path) ? 'active' : ''}`}>
                {it.label}
              </a>
            ))}
          </div>
        )}

        <div className="nav-right">
          <LangSelector />
          <button
            type="button"
            className={`nav-toggle ${open ? 'open' : ''} ${menuStyle === 'minimal' ? 'hide-desktop' : ''}`}
            onClick={() => setOpen(!open)}
            aria-label={T('Menú', 'Menu', 'Μενού', 'Menu')}
            aria-expanded={open}
            aria-controls="nav-overlay"
          >
            <span></span>
            <span></span>
          </button>
        </div>
      </nav>

      <div id="nav-overlay" className={`nav-overlay ${open ? 'open' : ''}`}>
        <div className="nav-overlay-links">
          {NAV.map((it, i) => (
            <a
              key={it.path}
              href={it.path}
              onClick={(e) => handleNav(e, it.path)}
              className="nav-overlay-link"
              style={{ transitionDelay: open ? `${0.1 + i * 0.06}s` : '0s' }}
            >
              <span className="num">{it.num}</span>
              <span>{it.label}</span>
            </a>
          ))}
        </div>
        <div className="nav-overlay-foot">
          <span>{T('Premio Alfaguara · Granta · Seix Barral', 'Alfaguara Prize · Granta · Seix Barral', 'Βραβείο Alfaguara · Granta · Seix Barral', 'Nagroda Alfaguara · Granta · Seix Barral')}</span>
          <span>Lima · Madrid · Barcelona</span>
        </div>
      </div>
    </>
  );
}

// ─── Placeholder primitive ───────────────────────────────────────
function Placeholder({ kind = 'IMAGEN', label = '', tag, className = '', style }) {
  return (
    <div className={`ph ${className}`} style={style}>
      {tag && <div className="ph-tag">{tag}</div>}
      <div className="ph-label">
        <span className="kind">{kind}</span>
        {label}
      </div>
    </div>
  );
}

// ─── Book cover ──────────────────────────────────────────────────
function BookCover({ title, year, color = '#1a212b', titleColor, image, publisher = 'Seix Barral' }) {
  if (image) {
    return (
      <div className="book-cover-img-wrap">
        <img className="book-cover-img" src={image} alt={`Portada de ${title}`} loading="lazy" />
      </div>
    );
  }
  return (
    <div className="ph-cover" style={{ '--cover-color': color }}>
      <div className="ph-cover-author">SANTIAGO RONCAGLIOLO</div>
      <div className="ph-cover-title" style={titleColor ? { color: titleColor } : undefined}>{title}</div>
      <div className="ph-cover-pub">{publisher} · {year}</div>
    </div>
  );
}

// ─── Footer ──────────────────────────────────────────────────────
function Footer() {
  const { go } = useRoute();
  const { lang } = useLang();
  const NAV = navItems(lang);
  const click = (e, p) => { e.preventDefault(); go(p); };
  const T = (a, b, c, d) => (lang === 'en' ? b : lang === 'el' ? c : lang === 'pl' ? d : a);
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-grid">
          <div>
            {/* La ficha de autor se ha sustituido por la puerta a /sobre: dice
                lo mismo pero lleva a alguna parte. */}
            <a href="/sobre" onClick={(e) => click(e, '/sobre')} className="foot-about">
              <span className="foot-about-eyebrow">
                {T('El autor','The author','Ο συγγραφέας','Autor')}
              </span>
              <span className="foot-about-title serif">
                {T(
                  'Conoce la historia de Santiago',
                  'Get to know Santiago’s story',
                  'Γνωρίστε την ιστορία του Σαντιάγο',
                  'Poznaj historię Santiago'
                )}
              </span>
              <span className="foot-about-cta">
                {T('Lima, 1975','Lima, 1975','Λίμα, 1975','Lima, 1975')}
                <span className="foot-about-arrow" aria-hidden="true">→</span>
              </span>
            </a>
          </div>
          <div>
            <h4>{T('Sitio','Site','Σελίδα','Strona')}</h4>
            <ul>
              {/* Sobre Santiago y Obra ya tienen su sitio en las otras dos
                  columnas: aquí sobrarían. */}
              {NAV.filter((it) => it.path !== '/sobre' && it.path !== '/obra').map((it) => (
                <li key={it.path}><a href={it.path} onClick={(e) => click(e, it.path)}>{it.label}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>{T('Obra','Works','Έργο','Twórczość')}</h4>
            <ul>
              <li><a href="/obra/literatura" onClick={(e) => click(e, '/obra/literatura')}>{T('Literatura','Books','Βιβλία','Książki')}</a></li>
              <li><a href="/obra/cine" onClick={(e) => click(e, '/obra/cine')}>{T('Cine','Film','Σινεμά','Film')}</a></li>
              <li><a href="/obra/teatro" onClick={(e) => click(e, '/obra/teatro')}>{T('Teatro','Theatre','Θέατρο','Teatr')}</a></li>
            </ul>
          </div>
          <div>
            <h4>{T('Síguelo','Follow','Ακολούθα','Obserwuj')}</h4>
            <ul>
              <li><a href={SOCIAL.instagram} target="_blank" rel="noopener noreferrer">Instagram</a></li>
              <li><a href={SOCIAL.twitter} target="_blank" rel="noopener noreferrer">Twitter / X</a></li>
              <li><a href={SOCIAL.facebook} target="_blank" rel="noopener noreferrer">Facebook</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 Santiago Roncagliolo</span>
          <div className="social" aria-label={T('Redes sociales','Social','Κοινωνικά δίκτυα','Media społecznościowe')}>
            <a href={SOCIAL.instagram} aria-label="Instagram" target="_blank" rel="noopener noreferrer">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="4"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.8" fill="currentColor"/></svg>
            </a>
            <a href={SOCIAL.twitter} aria-label="Twitter / X" target="_blank" rel="noopener noreferrer">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18 3h3l-7 8 8 10h-6l-5-6-5 6H3l7-9L3 3h6l5 5z"/></svg>
            </a>
            <a href={SOCIAL.facebook} aria-label="Facebook" target="_blank" rel="noopener noreferrer">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M13 10h3V7h-3a3 3 0 0 0-3 3v2H8v3h2v6h3v-6h2.5l.5-3H13v-2a1 1 0 0 1 1-1z" fill="currentColor" stroke="none"/></svg>
            </a>
          </div>
          <span className="foot-credit">
            <a href="https://mateoroncagliolo.com" target="_blank" rel="noopener noreferrer">
              {T('Hecho por Mateo Roncagliolo','Made by Mateo Roncagliolo','Δημιουργήθηκε από τον Mateo Roncagliolo','Wykonane przez Mateo Roncagliolo')}
            </a>
          </span>
          <span className="foot-legal">
            <a href="/legal/aviso" onClick={(e) => { e.preventDefault(); go('/legal/aviso'); }}>{T('Aviso legal','Legal','Νομική','Prawo')}</a>
            <span aria-hidden="true">·</span>
            <a href="/legal/privacidad" onClick={(e) => { e.preventDefault(); go('/legal/privacidad'); }}>{T('Privacidad','Privacy','Απόρρητο','Prywatność')}</a>
            <span aria-hidden="true">·</span>
            <a href="/legal/cookies" onClick={(e) => { e.preventDefault(); go('/legal/cookies'); }}>Cookies</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

// ─── Cookie banner + Vercel Analytics (carga condicional) ────────
const COOKIES_KEY = 'sr-cookies';

function loadVercelAnalytics() {
  if (window.__sr_va_loaded) return;
  window.__sr_va_loaded = true;
  window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };
  const s = document.createElement('script');
  s.defer = true;
  s.src = '/_vercel/insights/script.js';
  document.head.appendChild(s);
}

function CookieBanner() {
  const { lang } = useLang();
  const { go } = useRoute();
  const [decision, setDecision] = useState(() => {
    try { return localStorage.getItem(COOKIES_KEY); } catch (e) { return null; }
  });

  useEffect(() => {
    if (decision === 'accepted') loadVercelAnalytics();
  }, [decision]);

  if (decision === 'accepted' || decision === 'rejected') return null;

  const T = (a, b, c, d) => (lang === 'en' ? b : lang === 'el' ? c : lang === 'pl' ? d : a);
  const set = (val) => {
    try { localStorage.setItem(COOKIES_KEY, val); } catch (e) {}
    setDecision(val);
  };

  return (
    <div className="cookie-banner" role="dialog" aria-live="polite" aria-label={T('Aviso de cookies','Cookie notice','Ειδοποίηση cookies','Informacja o ciasteczkach')}>
      <div className="cookie-banner-text">
        <strong>{T('Cookies','Cookies','Cookies','Ciasteczka')}.</strong>{' '}
        {T(
          'Usamos analítica anónima para saber cuánta gente visita la web. No te identificamos ni cedemos tus datos. Tu idioma se guarda localmente para que la web funcione.',
          'We use anonymous analytics to know how many people visit the site. We don’t identify you or share your data. Your language is saved locally so the site works.',
          'Χρησιμοποιούμε ανώνυμη ανάλυση επισκεψιμότητας. Δεν σας ταυτοποιούμε.',
          'Używamy anonimowej analityki. Nie identyfikujemy użytkowników.'
        )}{' '}
        <a href="/legal/cookies" onClick={(e) => { e.preventDefault(); go('/legal/cookies'); }}>
          {T('Más info','More info','Περισσότερα','Więcej')}
        </a>
      </div>
      <div className="cookie-banner-actions">
        <button type="button" className="btn cookie-btn-reject" onClick={() => set('rejected')}>
          {T('Rechazar','Reject','Απόρριψη','Odrzuć')}
        </button>
        <button type="button" className="btn btn-solid cookie-btn-accept" onClick={() => set('accepted')}>
          {T('Aceptar','Accept','Αποδοχή','Akceptuję')}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, {
  RouteProvider, useRoute, useReveal, useDocTitle, Nav, Footer, Placeholder, BookCover, NAV_ITEMS, navItems,
  CountryProvider, useCountry, BuyBlock,
  LangProvider, useLang, useT, LangSelector, LANGS, useSeo, SITE_URL,
  CookieBanner, loadVercelAnalytics,
});
