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

const SITE = {
  domain: "vinodepasto.com",
  email: "info@vinodepasto.com",
  buyUrl: "https://bodegasbaron.es/products/vino-blanco-paranormal?utm_source=vinodepasto&utm_medium=referral&utm_campaign=paranormal",
  buyUrlBlanco: "https://bodegasbaron.es/products/vino-blanco-paranormal?utm_source=vinodepasto&utm_medium=referral&utm_campaign=paranormal_blanco",
  buyUrlOxidativo: "https://bodegasbaron.es/products/vino-blanco-oxidativo-paranormal-2023?utm_source=vinodepasto&utm_medium=referral&utm_campaign=paranormal_oxidativo",
  coupon: "PARANORMAL10",
};

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" },
];

/* --- minimal hash router --- */
function useRoute() {
  const [route, setRoute] = React.useState(() => window.location.hash.replace(/^#/, "") || "/");
  React.useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.replace(/^#/, "") || "/");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function go(path) {
  window.location.hash = path;
}

function Link({ to, children, className, style, onClick }) {
  return (
    <a
      href={"#" + to}
      className={className}
      style={style}
      onClick={(e) => {
        if (onClick) onClick(e);
      }}
    >
      {children}
    </a>
  );
}

/* === Header === */
function Header({ route }) {
  const active = (path) => {
    if (path === "/") return route === "/" || route === "";
    return route === path || route.startsWith(path + "/");
  };
  return (
    <header className="site-header">
      <div className="container inner">
        <Link to="/" className="brand">
          <span className="lockup">Vino <em>de</em> Pasto</span>
          <span className="domain">vinodepasto.com</span>
        </Link>
        <nav className="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="/comprar-paranormal" className="btn-link" style={{ fontSize: 12 }}>
            <span>Comprar Caso 001</span><span style={{ fontFamily: "var(--serif)", fontStyle: "italic" }}>→</span>
          </Link>
        </div>
      </div>
    </header>
  );
}

/* === Footer === */
function Footer() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="grid">
          <div className="col">
            <h4>Vino <em style={{ fontStyle: "italic", color: "var(--atlantic-soft)" }}>de</em> Pasto.</h4>
            <p style={{ opacity: .68, maxWidth: 380, fontSize: 14, lineHeight: 1.65 }}>
              Portal editorial dedicado al vino de pasto y a Paranormal, blanco
              oxidativo de Bodegas Barón. Sanlúcar de Barrameda, Marco de Jerez.
            </p>
          </div>
          <div className="col">
            <div className="eyebrow" style={{ marginBottom: 16 }}>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={{ marginBottom: 16 }}>Cuaderno</div>
            <ul>
              <li><Link to="/blog/que-es-vino-de-pasto">Qué es vino de pasto</Link></li>
              <li><Link to="/blog/diferencia-vino-de-pasto-fino-manzanilla">Vino de pasto vs. fino y manzanilla</Link></li>
              <li><Link to="/blog/palomino-fino">Palomino Fino</Link></li>
              <li><Link to="/blog/crianza-sobre-lias">Crianza sobre lías</Link></li>
              <li><Link to="/blog/como-tomar-paranormal">Cómo tomar Paranormal</Link></li>
            </ul>
          </div>
          <div className="col">
            <div className="eyebrow" style={{ marginBottom: 16 }}>Comprar</div>
            <ul>
              <li><Link to="/comprar-paranormal">Tienda oficial Bodegas Barón</Link></li>
              <li><span style={{ opacity: .8 }}>Código: <span style={{ fontFamily: "var(--mono)", letterSpacing: "0.1em" }}>{SITE.coupon}</span></span></li>
            </ul>
            <div className="eyebrow" style={{ marginBottom: 16, marginTop: 32 }}>Contacto</div>
            <ul>
              <li><a href="mailto:info@vinodepasto.com" style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.08em" }}>info@vinodepasto.com</a></li>
              <li><span style={{ opacity: .6, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase" }}>Sanlúcar de Barrameda · Cádiz</span></li>
            </ul>
            <div className="eyebrow" style={{ marginBottom: 16, marginTop: 32 }}>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.</span>
          <span>vinodepasto.com</span>
          <span>Beba con moderación · 18+</span>
        </div>
      </div>
    </footer>
  );
}

/* === 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 [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(242,238,231,0.35)" : "0.5px solid var(--ink)",
        background: dark ? "transparent" : "var(--bone-2)",
        color: dark ? "var(--bone)" : "var(--ink)",
        padding: "26px 30px",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 24,
        cursor: "pointer",
        userSelect: "none",
        transition: "background .25s ease",
      }}
    >
      <div>
        <div className="eyebrow" style={{ color: dark ? "rgba(242,238,231,0.55)" : "var(--engrave)" }}>
          Código de descuento
        </div>
        <div style={{
          fontFamily: "var(--mono)",
          fontSize: 32,
          letterSpacing: "0.14em",
          marginTop: 8,
          color: dark ? "var(--bone)" : "var(--ink)",
          fontWeight: 500,
        }}>
          {SITE.coupon}
        </div>
      </div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.2em", opacity: .7, textTransform: "uppercase" }}>
        {copied ? "Copiado ✓" : "Copiar →"}
      </div>
    </div>
  );
}

function ExternalBuyButton({ children = "Comprar en Bodegas Barón", variant = "solid", small = false, href }) {
  return (
    <a
      className={"btn " + (variant === "ghost" ? "btn-ghost" : "")}
      href={href || SITE.buyUrl}
      target="_blank"
      rel="noopener noreferrer"
      style={small ? { padding: "10px 16px", fontSize: 11.5 } : null}
    >
      <span>{children}</span>
      <span className="arrow">↗</span>
    </a>
  );
}

/* === ZoomImage — large product photo with magnifier lupa on hover/move === */
function ZoomImage({ src, alt, zoom = 2.4, lensSize = 220, captionTop, captionBottom }) {
  const wrapRef = React.useRef(null);
  const imgRef = React.useRef(null);
  const lensRef = React.useRef(null);
  const [active, setActive] = React.useState(false);
  const [coarse, setCoarse] = React.useState(false);
  const [touchOn, setTouchOn] = React.useState(false);

  React.useEffect(() => {
    setCoarse(window.matchMedia && window.matchMedia("(pointer: coarse)").matches);
  }, []);

  const onMove = (e) => {
    const wrap = wrapRef.current, img = imgRef.current, lens = lensRef.current;
    if (!wrap || !img || !lens) return;
    const r = img.getBoundingClientRect();
    const pt = e.touches ? e.touches[0] : e;
    let x = pt.clientX - r.left;
    let y = pt.clientY - r.top;
    if (x < 0 || y < 0 || x > r.width || y > r.height) {
      if (!e.touches) setActive(false);
      return;
    }
    const half = lensSize / 2;
    // clamp lens within the image
    const lx = Math.max(half, Math.min(r.width - half, x));
    const ly = Math.max(half, Math.min(r.height - half, y));
    lens.style.left = (lx - half) + "px";
    lens.style.top = (ly - half) + "px";
    // background position
    const bgX = -(x * zoom - half);
    const bgY = -(y * zoom - half);
    lens.style.backgroundImage = `url('${src}')`;
    lens.style.backgroundSize = `${r.width * zoom}px ${r.height * zoom}px`;
    lens.style.backgroundPosition = `${bgX}px ${bgY}px`;
  };

  const showLens = active || touchOn;

  return (
    <figure className="zoom-figure" ref={wrapRef}>
      {captionTop && <figcaption className="zoom-cap zoom-cap-top">{captionTop}</figcaption>}
      <div
        className={"zoom-stage" + (showLens ? " is-active" : "")}
        onMouseEnter={() => !coarse && setActive(true)}
        onMouseLeave={() => setActive(false)}
        onMouseMove={onMove}
        onTouchStart={(e) => { setTouchOn(true); onMove(e); }}
        onTouchMove={(e) => { e.preventDefault(); onMove(e); }}
        onTouchEnd={() => setTouchOn(false)}
      >
        <img ref={imgRef} src={src} alt={alt} className="zoom-img" draggable={false} />
        <div ref={lensRef} className="zoom-lens" style={{ width: lensSize, height: lensSize }} aria-hidden="true" />
        <div className="zoom-hint" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/><path d="M11 8v6M8 11h6"/></svg>
          <span>{coarse ? "Toca y desliza para ampliar" : "Pasa el ratón para ampliar"}</span>
        </div>
      </div>
      {captionBottom && <figcaption className="zoom-cap zoom-cap-bottom">{captionBottom}</figcaption>}
    </figure>
  );
}

/* AnimatedLabelBackground — placeholder until WebM/MP4 supplied */
function AnimatedLabelBackground({ opacity = 0.55, position = "right", note = "VIDEO IA — etiqueta Paranormal · WebM/MP4" }) {
  return (
    <div className="label-canvas" style={{ opacity }}>
      <div style={{
        position: "absolute",
        left: position === "left" ? "6%" : "auto",
        right: position === "right" ? "6%" : "auto",
        top: "50%", transform: "translateY(-50%)",
        width: "clamp(260px, 28vw, 420px)",
        aspectRatio: "3 / 4.4",
        border: "0.5px solid rgba(241,236,224,0.18)",
        background: "rgba(241,236,224,0.04)",
        display: "flex", alignItems: "center", justifyContent: "center",
        animation: "drift 18s ease-in-out infinite alternate",
      }}>
        <div style={{ textAlign: "center", color: "rgba(241,236,224,0.55)", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em", padding: 24 }}>
          {note}
        </div>
      </div>
      <div style={{
        position: "absolute",
        left: position === "right" ? "8%" : "auto",
        right: position === "left" ? "8%" : "auto",
        top: "50%", transform: "translateY(-50%) rotate(-2deg)",
        width: "clamp(220px, 22vw, 340px)",
        aspectRatio: "3 / 4.4",
        border: "0.5px solid rgba(166,134,63,0.4)",
        background: "rgba(166,134,63,0.04)",
        animation: "drift 22s ease-in-out infinite alternate-reverse",
      }} />
    </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, useRoute, go, Link,
  Header, Footer, SectionNum,
  CouponBox, ExternalBuyButton, AnimatedLabelBackground, WineSpec, Page,
  ZoomImage,
});
