/* === Shared: constants, Header, Footer, building blocks === */

const SITE = {
  domain: "vinodepasto.com",
  buyUrl: "https://bodegasbaron.es/collections/tienda-online?filter.p.tag=Paranormal&utm_source=vinodepasto.com&utm_medium=referral&utm_campaign=paranormal_pasto10",
  buyUrlBlanco: "https://bodegasbaron.es/products/vino-blanco-paranormal?utm_source=vinodepasto.com&utm_medium=referral&utm_campaign=paranormal_blanco_pasto10",
  buyUrlOxidativo: "https://bodegasbaron.es/products/vino-blanco-oxidativo-paranormal-2023?utm_source=vinodepasto.com&utm_medium=referral&utm_campaign=paranormal_oxidativo_pasto10",
  coupon: "PASTO10",
};

const NAV = [
  { id: "home",        label: "Inicio",            path: "/" },
  { id: "que-es",      label: "Vino de Pasto",     path: "/que-es-vino-de-pasto" },
  { id: "paranormal",  label: "Paranormal",        path: "/paranormal" },
  { id: "bodega",      label: "Bodegas Barón",     path: "/bodegas-baron" },
  { id: "blog",        label: "Cuaderno",          path: "/blog" },
];
const NAV_EN = [
  { id: "home",        label: "Home",              path: "/en" },
  { id: "que-es",      label: "Vino de Pasto",     path: "/en/wine-de-pasto" },
  { id: "paranormal",  label: "Paranormal",        path: "/en/paranormal" },
  { id: "bodega",      label: "Bodegas Barón",     path: "/en/bodegas-baron" },
  { id: "blog",        label: "Notebook",          path: "/en/notebook" },
];
function currentLang() { return window.location.pathname.startsWith("/en") ? "en" : "es"; }
function langPath(path) { return currentLang() === "en" ? "/en" + (path === "/" ? "" : path) : path; }
function isExternalUrl(to) { return typeof to === "string" && /^(https?:)?\/\//.test(to); }
function switchLangPath() {
  const p = window.location.pathname.replace(/\/$/, "") || "/";
  if (p === "/en") return "/";
  if (p.startsWith("/en/")) {
    const rest = p.slice(3);
    const map = { "/wine-de-pasto": "/que-es-vino-de-pasto", "/paranormal": "/paranormal", "/bodegas-baron": "/bodegas-baron", "/notebook": "/blog" };
    return map[rest] || "/";
  }
  const map = { "/": "/en", "/que-es-vino-de-pasto": "/en/wine-de-pasto", "/paranormal": "/en/paranormal", "/bodegas-baron": "/en/bodegas-baron", "/blog": "/en/notebook" };
  return map[p] || "/en";
}


/* --- clean URL router with hash fallback for old links --- */
function normalisePath() {
  const hash = window.location.hash.replace(/^#/, "");
  if (hash && hash.startsWith("/")) return hash;
  return window.location.pathname.replace(/\/$/, "") || "/";
}

function useRoute() {
  const [route, setRoute] = React.useState(() => normalisePath());
  React.useEffect(() => {
    const refresh = () => {
      setRoute(normalisePath());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", refresh);
    window.addEventListener("hashchange", refresh);
    return () => {
      window.removeEventListener("popstate", refresh);
      window.removeEventListener("hashchange", refresh);
    };
  }, []);
  return route;
}

function go(path) {
  window.history.pushState({}, "", path);
  window.dispatchEvent(new PopStateEvent("popstate"));
}

function Link({ to, children, className, style, onClick }) {
  return (
    <a
      href={to}
      className={className}
      style={style}
      onClick={(e) => {
        if (onClick) onClick(e);
        if (!e.defaultPrevented && to && to.startsWith("/")) {
          e.preventDefault();
          go(to);
        }
      }}
    >
      {children}
    </a>
  );
}

/* === Header === */
function Header({ route }) {
  const lang = currentLang();
  const nav = lang === "en" ? NAV_EN : NAV;
  const en = lang === "en";
  const active = (path) => {
    if (path === "/" || path === "/en") return route === path || (path === "/" && route === "");
    return route === path || route.startsWith(path + "/");
  };
  const buyPath = en ? "/en/paranormal" : "/paranormal";
  const langTarget = switchLangPath();
  return (
    <header className="site-header">
      <div className="container inner">
        <Link to={en ? "/en" : "/"} className="brand">
          <span>VINO</span><span className="dot"></span><span>DE</span><span className="dot"></span><span>PASTO</span>
          <span className="domain" style={{ marginLeft: 10 }}>· {SITE.domain}</span>
        </Link>
        <nav className="nav desktop-nav">
          {nav.map((n) => (
            <Link key={n.id} to={n.path} className={active(n.path) ? "active" : ""}>{n.label}</Link>
          ))}
        </nav>
        <div className="header-cta">
          <Link to={buyPath} className="btn-link">{en ? "Buy Paranormal" : "Comprar Paranormal"}</Link>
          <Link to={langTarget} className="lang-switch desktop-lang-switch">{en ? "ES" : "EN"}</Link>
          <Link to={langTarget} className="mobile-lang-switch" aria-label={en ? "Ver la versión española" : "View the English version"}>{en ? "ESPAÑOL" : "ENGLISH"}</Link>
        </div>
      </div>
      <details className="mobile-main-drawer">
        <summary><span>{en ? "Sections" : "Secciones"}</span><span>{en ? "Open" : "Abrir"}</span></summary>
        <div className="mobile-main-drawer-panel">
          {nav.map((n) => (
            <Link key={n.id} to={n.path} className={active(n.path) ? "active" : ""}>{n.label}</Link>
          ))}
          <Link to={buyPath}>{en ? "Buy Paranormal" : "Comprar Paranormal"}</Link>
          <Link to={langTarget} className="drawer-lang">{en ? "Español" : "English version"}</Link>
        </div>
      </details>
    </header>
  );
}

/* === Footer === */
function Footer() {
  const lang = currentLang();
  const nav = lang === "en" ? NAV_EN : NAV;
  const en = lang === "en";
  const buyPath = en ? "/en/paranormal" : "/paranormal";
  return (
    <React.Fragment>
    <div className="mobile-buy-bar" role="navigation" aria-label={en ? "Quick purchase" : "Compra rápida"}>
      <Link to={buyPath} className="mobile-buy-main">{en ? "Buy Paranormal" : "Comprar Paranormal"}</Link>
      <a href={SITE.buyUrl} target="_blank" rel="noopener noreferrer" className="mobile-buy-code">{SITE.coupon}</a>
    </div>
    <footer className="site-footer">
      <div className="container">
        <div className="grid">
          <div className="col">
            <h4>Vino de Pasto</h4>
            <p style={{ opacity: .72, maxWidth: 340 }}>
              {en ? "A calm entry into Vino de Pasto and Paranormal, the Bodegas Barón white wine that brings a dry, vineyard-led side of Jerez back to the table." : "Un lugar para entrar con calma en el vino de pasto y en Paranormal: el blanco de Bodegas Barón que acerca a la mesa una memoria seca del Marco."}
            </p>
          </div>
          <div className="col">
            <div className="eyebrow" style={{ color: "rgba(241,236,224,0.6)", marginBottom: 14 }}>{en ? "Navigation" : "Navegación"}</div>
            <ul>{nav.map(n => <li key={n.id}><Link to={n.path}>{n.label}</Link></li>)}</ul>
          </div>
          <div className="col">
            <div className="eyebrow" style={{ color: "rgba(241,236,224,0.6)", marginBottom: 14 }}>{en ? "Notebook" : "Cuaderno"}</div>
            <ul>
              <li><Link to={en ? "/en/wine-de-pasto" : "/blog/que-es-vino-de-pasto"}>{en ? "What is Vino de Pasto" : "Qué es vino de pasto"}</Link></li>
              <li><Link to={en ? "/en/notebook/difference-vino-de-pasto-fino-manzanilla" : "/blog/diferencia-vino-de-pasto-fino-manzanilla"}>{en ? "Vino de Pasto, fino and manzanilla" : "Vino de pasto vs. fino y manzanilla"}</Link></li>
              <li><Link to={en ? "/en/notebook/palomino-fino" : "/blog/palomino-fino"}>Palomino Fino</Link></li>
              <li><Link to={en ? "/en/notebook/lees-ageing" : "/blog/crianza-sobre-lias"}>{en ? "Lees ageing" : "Crianza sobre lías"}</Link></li>
              <li><Link to={en ? "/en/notebook/how-to-serve-paranormal" : "/blog/como-tomar-paranormal"}>{en ? "How to serve Paranormal" : "Cómo tomar Paranormal"}</Link></li>
            </ul>
          </div>
          <div className="col">
            <div className="eyebrow" style={{ color: "rgba(241,236,224,0.6)", marginBottom: 14 }}>{en ? "Buy" : "Comprar"}</div>
            <ul>
              <li><Link to={en ? "/en/paranormal" : "/paranormal"}>{en ? "Official Bodegas Barón store" : "Tienda oficial Bodegas Barón"}</Link></li>
              <li><span style={{ opacity: .72 }}>{en ? "Code" : "Código"}: <span style={{ color: "var(--gold)" }}>{SITE.coupon}</span></span></li>
            </ul>
            <div className="eyebrow" style={{ color: "rgba(241,236,224,0.6)", marginBottom: 14, marginTop: 28 }}>Legal</div>
            <ul>
              <li><Link to="/aviso-legal">Aviso legal</Link></li>
              <li><Link to="/politica-privacidad">Privacidad</Link></li>
              <li><Link to="/politica-cookies">Cookies</Link></li>
            </ul>
          </div>
        </div>
        <div className="colofon">
          <span>© MMXXVI · Wine &amp; Cask Consulting, S.L. · vinodepasto.com</span>
          <span>{en ? "Drink responsibly · 18+" : "Beba con moderación · 18+"}</span>
        </div>
      </div>
    </footer>
    </React.Fragment>
  );
}

/* === Reusable bits === */
function SectionNum({ n, children }) {
  return <div className="section-num"><span>{n}</span><span>{children}</span></div>;
}

function CouponBox({ tone = "light" }) {
  const dark = tone === "dark";
  const en = currentLang() === "en";
  const [copied, setCopied] = React.useState(false);
  const copy = () => {
    navigator.clipboard && navigator.clipboard.writeText(SITE.coupon);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  return (
    <div
      onClick={copy}
      style={{
        border: dark ? "0.5px solid rgba(241,236,224,0.35)" : "0.5px solid var(--ink)",
        background: dark ? "transparent" : "var(--paper-warm)",
        color: dark ? "var(--paper)" : "var(--ink)",
        padding: "22px 26px",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 24,
        cursor: "pointer",
        userSelect: "none",
      }}
    >
      <div>
        <div className="eyebrow" style={{ color: dark ? "rgba(241,236,224,0.6)" : "var(--engrave)" }}>
          {en ? "Discount code" : "Código de descuento"}
        </div>
        <div style={{
          fontFamily: "var(--mono)",
          fontSize: 28,
          letterSpacing: "0.16em",
          marginTop: 6,
          color: dark ? "var(--gold)" : "var(--gold-deep)",
        }}>
          {SITE.coupon}
        </div>
      </div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", opacity: .7, textTransform: "uppercase" }}>
        {copied ? (en ? "Copied ✓" : "Copiado ✓") : (en ? "Copy →" : "Copiar →")}
      </div>
    </div>
  );
}

function InlineCoupon({ tone = "dark" }) {
  const dark = tone === "dark";
  const [copied, setCopied] = React.useState(false);
  const copy = (e) => {
    e.stopPropagation();
    navigator.clipboard && navigator.clipboard.writeText(SITE.coupon);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  return (
    <div onClick={copy} className="inline-coupon" style={{
      display: "inline-flex", alignItems: "center", gap: 10,
      padding: "8px 14px",
      border: dark ? "0.5px solid rgba(241,236,224,0.3)" : "0.5px solid var(--rule)",
      background: dark ? "rgba(241,236,224,0.06)" : "var(--paper-warm)",
      cursor: "pointer", userSelect: "none",
    }}>
      <span style={{
        fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em",
        color: dark ? "rgba(241,236,224,0.6)" : "var(--engrave)",
        textTransform: "uppercase",
      }}>{currentLang() === "en" ? "Code" : "Código"}</span>
      <span style={{
        fontFamily: "var(--mono)", fontSize: 15, letterSpacing: "0.12em",
        color: dark ? "var(--gold)" : "var(--gold-deep)",
        fontWeight: 600,
      }}>{SITE.coupon}</span>
      <span style={{
        fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.12em",
        color: dark ? "rgba(241,236,224,0.45)" : "var(--engrave-soft)",
        textTransform: "uppercase",
      }}>{copied ? "✓" : (currentLang() === "en" ? "Copy" : "Copiar")}</span>
    </div>
  );
}

function ExternalBuyButton({ children = null, variant = "solid", small = false, showCoupon = true, href = SITE.buyUrl }) {
  const en = currentLang() === "en";
  const label = children || (en ? "Buy from Bodegas Barón" : "Comprar en Bodegas Barón");
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, alignItems: "flex-start" }}>
      <a
        className={"btn " + (variant === "ghost" ? "btn-ghost" : "")}
        href={href}
        target="_blank"
        rel="noopener noreferrer"
        style={small ? { padding: "10px 16px", fontSize: 11.5 } : null}
      >
        <span>{label}</span>
        <span className="arrow">↗</span>
      </a>
      {showCoupon && <InlineCoupon tone={variant === "ghost" ? "dark" : "light"} />}
    </div>
  );
}

/* AnimatedLabelBackground — video de etiqueta animada */
function AnimatedLabelBackground({ opacity = 0.55, position = "right" }) {
  return (
    <div className="label-canvas" style={{ opacity }}>
      <video
        src="/uploads/VIDEO IA - etiqueta paranormal.mp4"
        autoPlay loop muted playsInline
        style={{
          position: "absolute",
          right: position === "right" ? "4%" : "auto",
          left: position === "left" ? "4%" : "auto",
          top: "50%", transform: "translateY(-50%)",
          width: "clamp(280px, 30vw, 440px)",
          height: "auto",
          objectFit: "cover",
          opacity: 0.7,
          animation: "drift 18s ease-in-out infinite alternate",
        }}
      />
    </div>
  );
}

/* WineSpecCard — used in product page and home */
function WineSpec({ label, value }) {
  return (
    <div style={{
      borderTop: "0.5px solid var(--rule)",
      padding: "16px 0",
      display: "grid",
      gridTemplateColumns: "1fr 1.4fr",
      gap: 24,
      alignItems: "baseline",
    }}>
      <div className="eyebrow">{label}</div>
      <div style={{ fontFamily: "var(--editorial)", fontSize: 17, color: "var(--ink)" }}>{value}</div>
    </div>
  );
}

/* Page wrapper with mount animation */
function Page({ children }) {
  return <main className="page-enter">{children}</main>;
}

Object.assign(window, {
  SITE, NAV, NAV_EN, currentLang, langPath, useRoute, go, Link,
  Header, Footer, SectionNum,
  CouponBox, InlineCoupon, ExternalBuyButton, AnimatedLabelBackground, WineSpec, Page,
});
