/* === Main app: router + tweaks === */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "atlantico",
  "headlineFont": "marcellus",
  "showAnimatedLabel": true,
  "couponVisible": true,
  "tagline": "El blanco atlántico de Jerez"
}/*EDITMODE-END*/;

const PALETTES = {
  atlantico: {
    label: "Atlántico (default)",
    swatch: ["#F1ECE0", "#15120D", "#A6863F"],
    vars: {
      "--paper":      "#F1ECE0",
      "--paper-warm": "#E9E2D2",
      "--ink":        "#15120D",
      "--gold":       "#A6863F",
      "--gold-deep":  "#8A6E2E",
      "--olive":      "#5A5D3B",
    },
  },
  bronce: {
    label: "Bronce oxidativo",
    swatch: ["#EDE4D2", "#1B1410", "#B36A3C"],
    vars: {
      "--paper":      "#EDE4D2",
      "--paper-warm": "#E2D7BE",
      "--ink":        "#1B1410",
      "--gold":       "#B36A3C",
      "--gold-deep":  "#8F4F26",
      "--olive":      "#5A5D3B",
    },
  },
  pizarra: {
    label: "Pizarra & oliva",
    swatch: ["#ECE9DF", "#13160F", "#6E7842"],
    vars: {
      "--paper":      "#ECE9DF",
      "--paper-warm": "#DDD9CB",
      "--ink":        "#13160F",
      "--gold":       "#9B8341",
      "--gold-deep":  "#6E7842",
      "--olive":      "#6E7842",
    },
  },
};

const FONT_PAIRS = {
  marcellus: { label: "Marcellus (default)", serif: "'Marcellus', Georgia, serif" },
  newsreader: { label: "Newsreader display", serif: "'Newsreader', Georgia, serif" },
};


function getPageMeta(route) {
  const en = route === "/en" || route.startsWith("/en/");
  const base = "Vino de Pasto";
  const metas = {
    "/": {
      title: "Vino de Pasto | Paranormal, Palomino Fino de Sanlúcar",
      description: "Vino de pasto, Palomino Fino, albariza y Paranormal de Bodegas Barón. Una guía cercana y elegante del blanco seco del Marco de Jerez. Código PASTO10.",
      keywords: "vino de pasto, comprar vino de pasto, Palomino Fino, vino blanco Jerez, Paranormal Bodegas Barón, albariza, Sanlúcar de Barrameda"
    },
    "/que-es-vino-de-pasto": {
      title: "Qué es un vino de pasto | Palomino Fino, albariza y Jerez",
      description: "Qué es un vino de pasto: blanco seco del Marco de Jerez, normalmente Palomino Fino, sin fortificar, con raíz histórica y lectura contemporánea.",
      keywords: "qué es vino de pasto, vino de pasto Jerez, vino de pasto Sanlúcar, Palomino Fino sin fortificar, albariza"
    },
    "/paranormal": {
      title: "Comprar Paranormal | Vino de Pasto de Bodegas Barón",
      description: "Compra Blanco Paranormal y Blanco Oxidativo Paranormal. Palomino Fino de Sanlúcar, vino de pasto de Bodegas Barón y código PASTO10.",
      keywords: "comprar Paranormal, Blanco Paranormal, Blanco Oxidativo Paranormal, Bodegas Barón, vino de pasto comprar"
    },
    "/bodegas-baron": {
      title: "Bodegas Barón | Sanlúcar, El Poedo y Paranormal",
      description: "Bodegas Barón en Sanlúcar de Barrameda: viñedo El Poedo, Palomino Fino y Paranormal como lectura contemporánea del vino de pasto.",
      keywords: "Bodegas Barón, Sanlúcar de Barrameda, El Poedo, Paranormal vino, Palomino Fino"
    },
    "/blog": {
      title: "Cuaderno de Vino de Pasto | Palomino, albariza y Paranormal",
      description: "Artículos sobre vino de pasto, Palomino Fino, crianza sobre lías, vinos de Jerez sin fortificar y servicio de Paranormal.",
      keywords: "blog vino de pasto, guías vino Jerez, Palomino Fino, vinos de albariza"
    },
    "/en": {
      title: "Vino de Pasto | Paranormal, Palomino Fino from Jerez",
      description: "Vino de Pasto, Palomino Fino, albariza soils and Paranormal by Bodegas Barón. A calm, elegant guide to the dry white side of the Marco de Jerez.",
      keywords: "Vino de Pasto, buy Vino de Pasto, Palomino Fino, dry white wine Jerez, Paranormal Bodegas Barón, albariza, Sanlúcar"
    },
    "/en/wine-de-pasto": {
      title: "What is Vino de Pasto | Palomino Fino, albariza and Jerez",
      description: "What is Vino de Pasto: an unfortified dry white wine from the Marco de Jerez, usually made from Palomino Fino and rooted in the table wines of the region.",
      keywords: "what is Vino de Pasto, Vino de Pasto Jerez, unfortified white wine Jerez, Palomino Fino, albariza soil"
    },
    "/en/paranormal": {
      title: "Buy Paranormal | Vino de Pasto by Bodegas Barón",
      description: "Buy Paranormal White and Paranormal Oxidative White from Bodegas Barón. Palomino Fino from Sanlúcar and code PASTO10.",
      keywords: "buy Paranormal wine, Paranormal White, Paranormal Oxidative White, Bodegas Barón, Vino de Pasto buy"
    },

    "/en/notebook": {
      title: "Vino de Pasto Notebook | Palomino, albariza and Paranormal",
      description: "Editorial notebook in English about Vino de Pasto, Palomino Fino, albariza, Sanlúcar and Paranormal by Bodegas Barón.",
      keywords: "Vino de Pasto notebook, Palomino Fino, albariza, Jerez dry white wine, Paranormal wine"
    },
    "/en/bodegas-baron": {
      title: "Bodegas Barón | Sanlúcar, El Poedo and Paranormal",
      description: "Bodegas Barón in Sanlúcar de Barrameda: El Poedo vineyard, Palomino Fino and Paranormal as a contemporary reading of Vino de Pasto.",
      keywords: "Bodegas Barón, Sanlúcar de Barrameda, El Poedo, Paranormal wine, Palomino Fino"
    },
  };
  if (route.startsWith("/blog/")) {
    const slug = route.slice("/blog/".length);
    const post = window.BLOG_POSTS && window.BLOG_POSTS.find(p => p.slug === slug);
    if (post) return { title: `${post.title} | ${base}`, description: post.excerpt, keywords: "vino de pasto, Palomino Fino, Jerez, Sanlúcar, Paranormal" };
  }
  return metas[route] || { title: `${base} | Paranormal`, description: en ? "Editorial site about Vino de Pasto and Paranormal by Bodegas Barón, with vineyard, Palomino Fino and albariza context." : "Portal editorial sobre vino de pasto y Paranormal de Bodegas Barón, con contexto de viña, Palomino Fino y albariza.", keywords: "vino de pasto, Vino de Pasto, Paranormal" };
}

function setOrCreateMeta(selector, attrName, attrValue, content) {
  let el = document.querySelector(selector);
  if (!el) {
    el = document.createElement('meta');
    el.setAttribute(attrName, attrValue);
    document.head.appendChild(el);
  }
  el.setAttribute('content', content);
  return el;
}
function setOrCreateLink(selector, rel, href, extra = {}) {
  let el = document.querySelector(selector);
  if (!el) {
    el = document.createElement('link');
    el.setAttribute('rel', rel);
    document.head.appendChild(el);
  }
  Object.entries(extra).forEach(([k, v]) => el.setAttribute(k, v));
  el.setAttribute('href', href);
  return el;
}
function routeAlternates(route) {
  const clean = route.replace(/\/$/, '') || '/';
  const toEn = { '/': '/en', '/que-es-vino-de-pasto': '/en/wine-de-pasto', '/paranormal': '/en/paranormal', '/comprar-paranormal': '/en/buy-paranormal', '/bodegas-baron': '/en/bodegas-baron', '/blog': '/en/notebook' };
  const toEs = { '/en': '/', '/en/wine-de-pasto': '/que-es-vino-de-pasto', '/en/paranormal': '/paranormal', '/en/buy-paranormal': '/comprar-paranormal', '/en/bodegas-baron': '/bodegas-baron', '/en/notebook': '/blog' };
  const esPath = clean.startsWith('/en') ? (toEs[clean] || '/') : clean;
  const enPath = clean.startsWith('/en') ? clean : (toEn[clean] || '/en');
  return { esPath, enPath };
}
function updateStructuredData(route, meta) {
  const en = route === '/en' || route.startsWith('/en/');
  const canonical = 'https://www.vinodepasto.com' + (route === '/' ? '/' : route.replace(/\/$/, '') + '/');
  const graph = [
    { '@type': 'WebSite', '@id': 'https://www.vinodepasto.com/#website', name: 'Vino de Pasto', url: 'https://www.vinodepasto.com/', inLanguage: en ? 'en' : 'es' },
    { '@type': ['Organization','Winery'], '@id': 'https://www.vinodepasto.com/#bodega-baron-context', name: 'Bodegas Barón', url: 'https://bodegasbaron.es/', address: { '@type': 'PostalAddress', addressLocality: 'Sanlúcar de Barrameda', addressRegion: 'Cádiz', addressCountry: 'ES' } },
    { '@type': 'BreadcrumbList', '@id': canonical + '#breadcrumb', itemListElement: [
      { '@type': 'ListItem', position: 1, name: en ? 'Home' : 'Inicio', item: en ? 'https://www.vinodepasto.com/en/' : 'https://www.vinodepasto.com/' },
      { '@type': 'ListItem', position: 2, name: meta.title.replace(' | Vino de Pasto',''), item: canonical }
    ]}
  ];
  if (route.includes('paranormal') || route === '/' || route === '/en') {
    graph.push({ '@type': 'Product', '@id': 'https://www.vinodepasto.com/paranormal/#blanco-paranormal', name: en ? 'Paranormal White' : 'Blanco Paranormal', image: 'https://www.vinodepasto.com/uploads/Vino-blanco-paranormal-2023-baron.jpg.webp', brand: { '@type': 'Brand', name: 'Bodegas Barón' }, category: en ? 'Vino de Pasto white wine' : 'Vino blanco de pasto', offers: { '@type': 'Offer', price: '15', priceCurrency: 'EUR', availability: 'https://schema.org/InStock', url: SITE.buyUrlBlanco } });
    graph.push({ '@type': 'Product', '@id': 'https://www.vinodepasto.com/paranormal/#paranormal-oxidative-white', name: en ? 'Paranormal Oxidative White' : 'Blanco Oxidativo Paranormal', image: 'https://www.vinodepasto.com/uploads/PARANORMAL AMONTILLADO.jpeg', brand: { '@type': 'Brand', name: 'Bodegas Barón' }, category: en ? 'Oxidative Vino de Pasto white wine' : 'Vino blanco oxidativo de pasto', offers: { '@type': 'Offer', price: '20', priceCurrency: 'EUR', availability: 'https://schema.org/InStock', url: SITE.buyUrlOxidativo } });
  }
  if (route.includes('/blog') || route.includes('/notebook') || route.includes('vino-de-pasto')) {
    graph.push({ '@type': 'Article', '@id': canonical + '#article', headline: meta.title, description: meta.description, image: 'https://www.vinodepasto.com/uploads/DSCF1827.JPG', inLanguage: en ? 'en' : 'es', author: { '@type': 'Organization', name: 'Vino de Pasto' }, publisher: { '@id': 'https://www.vinodepasto.com/#website' } });
  }
  let el = document.getElementById('route-jsonld');
  if (!el) { el = document.createElement('script'); el.type = 'application/ld+json'; el.id = 'route-jsonld'; document.head.appendChild(el); }
  el.textContent = JSON.stringify({ '@context': 'https://schema.org', '@graph': graph });
}

function App() {
  const route = useRoute();
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [ageOk, setAgeOk] = React.useState(() => localStorage.getItem("vdp_age_ok") === "1");

  // Apply tweaks to root
  React.useEffect(() => {
    const r = document.documentElement;
    const pal = PALETTES[t.palette] || PALETTES.atlantico;
    Object.entries(pal.vars).forEach(([k, v]) => r.style.setProperty(k, v));
    const font = FONT_PAIRS[t.headlineFont] || FONT_PAIRS.marcellus;
    r.style.setProperty("--serif", font.serif);
  }, [t.palette, t.headlineFont]);

  React.useEffect(() => {
    const meta = getPageMeta(route);
    document.title = meta.title;
    document.documentElement.lang = route === "/en" || route.startsWith("/en/") ? "en" : "es";
    const canonicalUrl = "https://www.vinodepasto.com" + (route === "/" ? "/" : route.replace(/\/$/, "") + "/");
    setOrCreateMeta('meta[name="description"]', 'name', 'description', meta.description);
    setOrCreateMeta('meta[name="keywords"]', 'name', 'keywords', meta.keywords || "vino de pasto, Paranormal");
    setOrCreateLink('link[rel="canonical"]', 'canonical', canonicalUrl);
    const alt = routeAlternates(route);
    setOrCreateLink('link[rel="alternate"][hreflang="es"]', 'alternate', "https://www.vinodepasto.com" + (alt.esPath === "/" ? "/" : alt.esPath + "/"), { hreflang: 'es' });
    setOrCreateLink('link[rel="alternate"][hreflang="en"]', 'alternate', "https://www.vinodepasto.com" + (alt.enPath === "/en" ? "/en/" : alt.enPath + "/"), { hreflang: 'en' });
    setOrCreateLink('link[rel="alternate"][hreflang="x-default"]', 'alternate', "https://www.vinodepasto.com/", { hreflang: 'x-default' });
    setOrCreateMeta('meta[property="og:type"]', 'property', 'og:type', route.includes('/blog') || route.includes('/notebook') ? 'article' : 'website');
    setOrCreateMeta('meta[property="og:title"]', 'property', 'og:title', meta.title);
    setOrCreateMeta('meta[property="og:description"]', 'property', 'og:description', meta.description);
    setOrCreateMeta('meta[property="og:url"]', 'property', 'og:url', canonicalUrl);
    setOrCreateMeta('meta[property="og:image"]', 'property', 'og:image', 'https://www.vinodepasto.com/uploads/DSCF1827.JPG');
    setOrCreateMeta('meta[name="twitter:card"]', 'name', 'twitter:card', 'summary_large_image');
    setOrCreateMeta('meta[name="twitter:title"]', 'name', 'twitter:title', meta.title);
    setOrCreateMeta('meta[name="twitter:description"]', 'name', 'twitter:description', meta.description);
    setOrCreateMeta('meta[name="twitter:image"]', 'name', 'twitter:image', 'https://www.vinodepasto.com/uploads/DSCF1827.JPG');
    updateStructuredData(route, meta);
  }, [route]);

  // Route to page
  let page = null;
  const r = route;
  if (r === "/" || r === "" || r === "/en") page = <Home />;
  else if (r === "/que-es-vino-de-pasto" || r === "/en/wine-de-pasto") page = <QueEs />;
  else if (r === "/paranormal" || r === "/en/paranormal") page = <Paranormal />;
  else if (r === "/bodegas-baron" || r === "/en/bodegas-baron") page = <BodegaPage />;
  else if (r === "/comprar-paranormal" || r === "/en/buy-paranormal") page = <Paranormal />; // Redirige a paranormal / translated buy route
  else if (r === "/blog" || r === "/en/notebook") page = <BlogIndex />;
  else if (r.startsWith("/blog/")) page = <BlogPost slug={r.slice("/blog/".length)} />;
  else if (r.startsWith("/en/notebook/")) page = <BlogPost slug={r.slice("/en/notebook/".length)} />;
  else if (r === "/aviso-legal") page = <AvisoLegal />;
  else if (r === "/politica-privacidad") page = <PoliticaPrivacidad />;
  else if (r === "/politica-cookies") page = <PoliticaCookies />;
  else {
    page = (
      <Page>
        <section className="section-pad">
          <div className="container">
            <div className="eyebrow">404</div>
            <h1 style={{ marginTop: 20 }}>Página no encontrada.</h1>
            <Link to="/" className="btn-link" style={{ marginTop: 24, display: "inline-block" }}>Volver al inicio</Link>
          </div>
        </section>
      </Page>
    );
  }

  return (
    <React.Fragment>
      <Header route={route} />
      {page}
      <Footer />
      {!ageOk && <AgeGate onAccept={() => setAgeOk(true)} />}
      {ageOk && <CookieBanner />}

      {/* Production build: tweak panel disabled */}

    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
