/* BeautyBloom — Componentes compartidos */

const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;

// ---------- Logo ----------
function Logo({ size = 32, showWord = true, variant = "mark" }) {
  if (variant === "wide") {
    return <img src="assets/logo-wide.png" alt="Beauty Bloom" style={{ height: size, width: "auto", display: "block" }} />;
  }
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <img src="assets/logo-circle.png" alt="Beauty Bloom" style={{ height: size, width: size, borderRadius: "50%", display: "block" }} />
      {showWord && (
        <span style={{ fontFamily: "var(--font-display)", fontSize: size * 0.55, letterSpacing: "0.12em", fontWeight: 500, color: "var(--gold)", textTransform: "uppercase" }}>
          Beauty Bloom
        </span>
      )}
    </span>
  );
}

// ---------- Price formatter (MXN) ----------
function formatMXN(n) {
  return new Intl.NumberFormat("es-MX", { style: "currency", currency: "MXN", maximumFractionDigits: 0 }).format(n);
}

// ---------- Category → silhouette ----------
const SHAPES = {
  limpieza: <>
    <rect x="36" y="20" width="28" height="10" rx="2" />
    <path d="M36 30 Q 30 36 30 50 V 110 Q 30 120 40 120 H 60 Q 70 120 70 110 V 50 Q 70 36 64 30 Z" />
  </>,
  toner: <>
    <rect x="42" y="14" width="16" height="10" rx="1.5" />
    <rect x="34" y="24" width="32" height="98" rx="3" />
  </>,
  serum: <>
    <rect x="44" y="10" width="12" height="14" rx="1" />
    <rect x="36" y="24" width="28" height="96" rx="2" />
    <rect x="46" y="14" width="8" height="3" fill="rgba(31,36,25,0.35)" />
  </>,
  ampoule: <>
    <rect x="46" y="8" width="8" height="14" rx="1" />
    <path d="M38 22 H 62 L 66 36 V 110 Q 66 120 56 120 H 44 Q 34 120 34 110 V 36 Z" />
  </>,
  cream: <>
    <rect x="28" y="40" width="44" height="14" rx="2" />
    <rect x="24" y="54" width="52" height="56" rx="3" />
  </>,
  spf: <>
    <rect x="42" y="14" width="16" height="8" rx="2" />
    <path d="M36 22 H 64 L 66 32 V 112 Q 66 120 58 120 H 42 Q 34 120 34 112 V 32 Z" />
  </>,
  pads: <>
    <circle cx="50" cy="60" r="32" />
    <circle cx="50" cy="60" r="20" fill="none" stroke="rgba(31,36,25,0.18)" strokeWidth="0.6" />
  </>,
  mist: <>
    <rect x="44" y="10" width="12" height="14" rx="1.5" />
    <rect x="36" y="22" width="28" height="98" rx="14" />
  </>,
  mask: <>
    <rect x="22" y="30" width="56" height="74" rx="3" />
    <rect x="30" y="44" width="40" height="2" fill="rgba(31,36,25,0.25)" />
    <rect x="30" y="52" width="32" height="2" fill="rgba(31,36,25,0.25)" />
  </>,
  kits: <>
    <rect x="20" y="40" width="20" height="70" rx="2" />
    <rect x="42" y="32" width="18" height="78" rx="2" />
    <rect x="62" y="46" width="18" height="64" rx="2" />
  </>,
};

// ---------- Product placeholder ----------
function ProductPlaceholder({ product, ratio = "4 / 5", showSku = true, bare = false }) {
  if (!product) return null;
  const { swatch, hero, sku, category } = product;
  // If we have a real product image, render it instead of the placeholder
  // Resolve cover image: prefer images[] array, fall back to hero filename
  const coverSrc = (() => {
    if (product.images && product.images.length > 0) {
      return product.images[product.coverIndex ?? 0] || product.images[0];
    }
    if (hero) return `products/${hero}.jpg`;
    return null;
  })();

  if (coverSrc) {
    return (
      <div
        className={bare ? "bb-prod-bare" : "bb-prod-ph"}
        style={{
          aspectRatio: ratio,
          background: `${swatch}22`,
          position: "relative",
          overflow: "hidden",
        }}
      >
        <img
          src={coverSrc}
          alt={product.name}
          loading="lazy"
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
          onError={(e) => { e.currentTarget.style.display = "none"; }}
        />
        {showSku && (
          <span className="bb-prod-sku" style={{ position: "absolute", bottom: 8, left: 10 }}>{sku}</span>
        )}
      </div>
    );
  }
  const shape = SHAPES[category] || SHAPES.serum;
  return (
    <div
      className="bb-ph"
      style={{
        aspectRatio: ratio,
        background: `radial-gradient(120% 100% at 50% 0%, ${swatch}66 0%, ${swatch}11 70%), var(--cream)`,
        position: "relative",
        overflow: "hidden",
        borderRadius: bare ? 0 : 2,
      }}
    >
      <div className="bb-ph-grain" />
      <div className="bb-ph-leaf" aria-hidden="true">
        {/* botanical leaf accent */}
        <svg viewBox="0 0 200 200" width="100%" height="100%">
          <path d="M 30 170 Q 40 90 100 60 Q 160 30 180 50 Q 170 110 110 140 Q 60 170 30 170 Z"
                fill="none" stroke="rgba(38,52,30,0.10)" strokeWidth="0.8" />
          <path d="M 38 162 Q 80 130 130 100 Q 170 75 178 55"
                fill="none" stroke="rgba(38,52,30,0.08)" strokeWidth="0.8" />
        </svg>
      </div>
      <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <svg viewBox="0 0 100 130" width="44%" height="64%" preserveAspectRatio="xMidYMid meet" style={{ filter: "drop-shadow(0 18px 24px rgba(31,36,25,0.10))" }}>
          <defs>
            <linearGradient id={`g-${sku}`} x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor={swatch} stopOpacity="0.98" />
              <stop offset="100%" stopColor={swatch} stopOpacity="0.62" />
            </linearGradient>
          </defs>
          <g fill={`url(#g-${sku})`} stroke="rgba(31,36,25,0.22)" strokeWidth="0.6">
            {shape}
          </g>
          <text x="50" y="78" textAnchor="middle"
            style={{ fontFamily: "var(--font-display)", fontStyle: "italic" }}
            fontSize="9" fill="rgba(31,36,25,0.55)">
            {hero}
          </text>
        </svg>
      </div>
      {showSku && (
        <div className="bb-ph-sku">{sku} · imagen pendiente</div>
      )}
    </div>
  );
}

// ---------- Top nav ----------
function TopNav({ onScrollTo, onOpenDownload, query, setQuery, resultCount, total }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled((document.scrollingElement?.scrollTop || 0) > 12);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <header className={`bb-nav ${scrolled ? "is-scrolled" : ""}`}>
      <div className="bb-nav-marquee">
        <div className="bb-marquee-track">
          {Array.from({ length: 6 }).map((_, i) => (
            <span key={i}>
              ✦ 15% OFF en todos los productos · válido hasta el 15 de mayo · envíos a todo México · Aguascalientes · Tel 449 468 5174 ·
            </span>
          ))}
        </div>
      </div>
      <div className="bb-nav-bar">
        <button className="bb-nav-logo" onClick={() => onScrollTo("hero")} aria-label="BeautyBloom inicio">
          <Logo size={26} />
        </button>
        <nav className="bb-nav-links">
          <a onClick={() => onScrollTo("rutina")}>Rutina</a>
          <a onClick={() => onScrollTo("catalogo")}>Catálogo</a>
          <a onClick={() => onScrollTo("ingredientes")}>Ingredientes</a>
          <a onClick={() => onScrollTo("contacto")}>Contacto</a>
        </nav>
        <div className="bb-nav-right">
          <button className="bb-nav-dl" onClick={onOpenDownload}>
            Descargar catálogo
          </button>
          <div className="bb-nav-search">
            <svg width="16" height="16" viewBox="0 0 20 20" fill="none"><circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.4"/><path d="m14 14 4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
            <input
              value={query}
              onChange={(e) => { setQuery(e.target.value); onScrollTo("catalogo"); }}
              placeholder="Busca: centella, hidratante, acné…"
              aria-label="Buscar productos"
            />
            {query && <button className="bb-nav-search-clear" onClick={() => setQuery("")} aria-label="Borrar">×</button>}
          </div>
          <a className="bb-nav-tel" href="tel:4494685174">
            <svg width="14" height="14" viewBox="0 0 20 20" fill="none"><path d="M5 3.5 7 3l2 4-2 1.5a10 10 0 0 0 4.5 4.5L13 11l4 2-.5 2A2 2 0 0 1 14.4 17 12 12 0 0 1 3 5.6 2 2 0 0 1 5 3.5Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>
            <span>449 468 5174</span>
          </a>
        </div>
      </div>
    </header>
  );
}

// ---------- Footer ----------
function Footer({ onScrollTo, onOpenDownload }) {
  return (
    <footer className="bb-foot" id="contacto">
      <div className="bb-foot-grid">
        <div>
          <Logo size={26} />
          <p className="bb-foot-tag">
            Skincare coreano importado directo desde Corea con Centella Asiática de Madagascar.
            Distribuido desde Aguascalientes para todo México.
          </p>
        </div>
        <div>
          <h5>Catálogo</h5>
          <a onClick={() => onScrollTo("catalogo")}>Todos los productos</a>
          <a onClick={() => onScrollTo("rutina")}>Por paso de rutina</a>
          <a onClick={() => onScrollTo("ingredientes")}>Por ingrediente</a>
        </div>
        <div>
          <h5>Contacto</h5>
          <div className="bb-foot-actions">
            <a className="bb-foot-btn bb-foot-btn--wa" href="https://wa.me/524494685174?text=Hola%20Beauty%20Bloom%2C%20me%20interesa%20su%20cat%C3%A1logo." target="_blank" rel="noopener">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.8.9-1 1.1-.2.2-.4.2-.6.1-.9-.4-1.8-.9-2.7-2-.7-.8-1.1-1.7-1.3-2-.1-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.2-.5 0-.2 0-.4-.1-.5-.1-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.3 5.1 4.6.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.3.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.9.5 3.7 1.5 5.3L2 22l4.8-1.5C8.4 21.5 10.2 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
              </svg>
              <span>WhatsApp · 449 468 5174</span>
            </a>
            <a className="bb-foot-btn bb-foot-btn--mail" href="mailto:ventas@beautybloom.com.mx?subject=Pedido%20desde%20cat%C3%A1logo%20Beauty%20Bloom">
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                <rect x="2" y="4" width="16" height="12" rx="2" stroke="currentColor" strokeWidth="1.4"/>
                <path d="m3 6 7 5 7-5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <span>ventas@beautybloom.com.mx</span>
            </a>
            <a className="bb-foot-btn bb-foot-btn--tel" href="tel:4494685174">
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M5 3.5 7 3l2 4-2 1.5a10 10 0 0 0 4.5 4.5L13 11l4 2-.5 2A2 2 0 0 1 14.4 17 12 12 0 0 1 3 5.6 2 2 0 0 1 5 3.5Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>
              <span>Llamar · 449 468 5174</span>
            </a>
            <a className="bb-foot-btn bb-foot-btn--mail" href="mailto:contacto@beautybloom.com.mx">
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                <rect x="2" y="4" width="16" height="12" rx="2" stroke="currentColor" strokeWidth="1.4"/>
                <path d="m3 6 7 5 7-5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <span>contacto@beautybloom.com.mx</span>
            </a>
            <button className="bb-foot-btn bb-foot-btn--dl" onClick={onOpenDownload}>Descargar catálogo</button>
            <a className="bb-foot-btn bb-foot-btn--ig" href="https://instagram.com/beautybloom.mx_" target="_blank" rel="noopener">
              Instagram · @beautybloom.mx_
            </a>
          </div>
        </div>
        <div>
          <h5>Ubicación</h5>
          <p>Aguascalientes, Ags · México</p>
          <p>Envíos a todo el país</p>
          <p>www.beautybloom.com.mx</p>
        </div>
      </div>
      <div className="bb-foot-base">
        <span>© 2026 BeautyBloom · MADAGASCAR CENTELLA SKINCARE</span>
        <span>2026 Product Catalog</span>
      </div>
      <div className="bb-foot-credit">
        crafted with care by <a href="https://acaciaco.com.mx" target="_blank" rel="noopener">ACACIA Consultoría en Informática y Cómputo</a> 2026
      </div>
    </footer>
  );
}

function CatalogDownloadModal({ open, onClose }) {
  const [name, setName] = useState("");
  const [mode, setMode] = useState("email");
  const [contact, setContact] = useState("");
  const [err, setErr] = useState("");
  const [done, setDone] = useState(false);
  useEffect(() => {
    if (!open) return;
    const onEsc = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onEsc);
    return () => window.removeEventListener("keydown", onEsc);
  }, [open, onClose]);
  if (!open) return null;
  const submit = (e) => {
    e.preventDefault();
    const v = contact.trim();
    if (!name.trim()) return setErr("Ingresa tu nombre.");
    if (!v) return setErr("Ingresa email o teléfono.");
    if (mode === "email" && !/^\S+@\S+\.\S+$/.test(v)) return setErr("Email inválido.");
    setErr("");
    const payload = {
      nombre: name.trim(),
      canal: mode === "email" ? "Email" : "Teléfono",
      contacto: v,
      origen: "Descarga catálogo web",
      fecha: new Date().toISOString(),
      _subject: "Nuevo lead - descarga de catálogo",
      _template: "table",
      _captcha: "false",
    };
    const downloadCatalog = () => {
      const a = document.createElement("a");
      a.href = "assets/BeautyBloom-Catalogo-2026.pdf";
      a.download = "BeautyBloom-Catalogo-2026.pdf";
      a.click();
      setDone(true);
    };
    fetch("https://formsubmit.co/ajax/contacto@beautybloom.com.mx", {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json" },
      body: JSON.stringify(payload),
    }).finally(downloadCatalog);
  };
  return (
    <div className="bb-dl-scrim" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="bb-dl-modal">
        <button className="bb-dl-close" onClick={onClose}>×</button>
        {done ? <div className="bb-dl-done"><div className="bb-dl-check">✓</div><h3 className="bb-dl-title">¡Listo!</h3></div> : <>
          <h3 className="bb-dl-title">Descargar catálogo PDF</h3>
          <p className="bb-dl-sub">Déjanos tus datos para compartirte promociones y dar seguimiento.</p>
          <form onSubmit={submit}>
            <label className="bb-dl-label">Nombre<input value={name} onChange={(e) => setName(e.target.value)} /></label>
            <div className="bb-dl-tabs">
              <button type="button" className={mode === "email" ? "on" : ""} onClick={() => { setMode("email"); setContact(""); }}>Email</button>
              <button type="button" className={mode === "phone" ? "on" : ""} onClick={() => { setMode("phone"); setContact(""); }}>Teléfono</button>
            </div>
            <label className="bb-dl-label">{mode === "email" ? "Email" : "Teléfono"}<input value={contact} onChange={(e) => setContact(e.target.value)} /></label>
            {err ? <div className="bb-dl-err">{err}</div> : null}
            <button className="bb-btn bb-btn--primary bb-dl-submit" type="submit">Enviar y descargar</button>
          </form>
        </>}
      </div>
    </div>
  );
}

function CookieDisclaimer({ onClose }) {
  return (
    <aside className="bb-cookie" role="status" aria-live="polite">
      <p>
        Usamos almacenamiento local del navegador para recordar ajustes técnicos (por ejemplo, sesión de administrador y cambios del catálogo).
        No usamos cookies de rastreo ni publicidad en este sitio.
      </p>
      <button className="bb-cookie-btn" onClick={onClose}>Entendido</button>
    </aside>
  );
}

Object.assign(window, { Logo, ProductPlaceholder, TopNav, Footer, CatalogDownloadModal, CookieDisclaimer, formatMXN });
