/* FEDUCCE Catálogo — UI compartida: slots de foto, WhatsApp, header, footer. → window.FEDCAT_UI */
const KDS = window.FEDUCCEDesignSystem_349cd6;
const { Icon: KIcon } = KDS;

/* Detección de viewport móvil */
function useIsMobile(bp = 760) {
  const q = "(max-width:" + bp + "px)";
  const [m, setM] = React.useState(() => window.matchMedia(q).matches);
  React.useEffect(() => {
    const mq = window.matchMedia(q);
    const on = (e) => setM(e.matches);
    setM(mq.matches);
    mq.addEventListener("change", on);
    return () => mq.removeEventListener("change", on);
  }, [q]);
  return m;
}

/* ------------------------------------------------------------- WhatsApp -- */
function WAGlyph({ size = 16, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true" style={{ display: "block" }}>
      <path d="M20.5 11.6c0 4.7-3.8 8.5-8.5 8.5-1.5 0-2.9-.4-4.1-1.1L3.5 20.5l1.6-4.3c-.8-1.3-1.2-2.8-1.2-4.4C3.9 6.9 7.7 3.1 12.4 3.1s8.1 3.8 8.1 8.5z" stroke={color} strokeWidth="1.4" strokeLinejoin="round" />
      <path d="M9.3 8c.2 0 .4.1.5.3l.7 1.5c.1.2 0 .4-.1.6l-.5.6c-.1.2-.2.4 0 .6.6 1 1.4 1.7 2.4 2.2.2.1.4.1.6-.1l.6-.6c.2-.2.4-.2.6-.1l1.5.7c.2.1.3.3.3.5 0 1-.9 1.7-1.9 1.7-2.9-.2-5.4-2.7-5.6-5.6 0-1 .7-1.8 1.7-1.8h.2z" fill={color} />
    </svg>
  );
}

/* Botón de WhatsApp — variantes: primary (bloque tinta), emerald, ghost, onDark */
function WAButton({ children, message, product, variant = "primary", style }) {
  const [hover, setHover] = React.useState(false);
  const url = product ? window.CAT_waProduct(product) : window.CAT_wa(message);
  const V = {
    primary: { background: hover ? "var(--ink-800)" : "var(--ink-900)", color: "var(--bone-50)", border: "1px solid var(--ink-900)" },
    emerald: { background: hover ? "var(--emerald-700)" : "var(--emerald-600)", color: "var(--bone-50)", border: "1px solid transparent" },
    ghost: { background: hover ? "var(--ink-900)" : "transparent", color: hover ? "var(--bone-50)" : "var(--ink-900)", border: "1px solid var(--ink-900)" },
    onDark: { background: hover ? "var(--bone-50)" : "transparent", color: hover ? "var(--ink-900)" : "var(--bone-50)", border: "1px solid var(--border-on-dark)" },
  }[variant];
  return (
    <a href={url} target="_blank" rel="noopener"
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: "inline-flex", alignItems: "center", gap: "10px", padding: "14px 22px",
        fontFamily: "var(--font-sans)", fontSize: "11px", fontWeight: 500, letterSpacing: "0.18em",
        textTransform: "uppercase", textDecoration: "none", cursor: "pointer",
        transition: "background var(--dur-base) var(--ease-standard), color var(--dur-base) var(--ease-standard)",
        ...V, ...style,
      }}>
      <WAGlyph size={16} />
      <span>{children}</span>
    </a>
  );
}

/* Burbuja fija, esquina inferior derecha */
function WAFloat() {
  const [hover, setHover] = React.useState(false);
  return (
    <a href={window.CAT_wa()} target="_blank" rel="noopener" aria-label="Escribir por WhatsApp"
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        position: "fixed", right: "18px", bottom: "calc(18px + env(safe-area-inset-bottom))", zIndex: 120,
        display: "flex", alignItems: "center", justifyContent: "center", gap: "10px",
        minWidth: "56px", minHeight: "56px", boxSizing: "border-box",
        background: hover ? "var(--emerald-700)" : "var(--emerald-600)", color: "var(--bone-50)",
        padding: "14px 16px", textDecoration: "none", boxShadow: "var(--shadow-md)",
        transition: "background var(--dur-base) var(--ease-standard)",
      }}>
      <WAGlyph size={22} />
      <span style={{
        fontFamily: "var(--font-sans)", fontSize: "10.5px", fontWeight: 500, letterSpacing: "0.18em",
        textTransform: "uppercase", maxWidth: hover ? "160px" : "0px", overflow: "hidden",
        whiteSpace: "nowrap", transition: "max-width var(--dur-slow) var(--ease-out)",
      }}>Escríbenos</span>
    </a>
  );
}

/* ------------------------------------------------------------- ImageSlot -- */
function CImageSlot({ label = "Fotografía de producto", index, ratio = "3 / 4", tone = "bone", style }) {
  const dark = tone === "dark";
  return (
    <div style={{
      position: "relative", aspectRatio: ratio, overflow: "hidden",
      background: dark ? "var(--ink-900)" : "var(--bone-200)",
      border: dark ? "1px solid var(--border-on-dark)" : "1px solid var(--border-hairline)",
      display: "flex", alignItems: "center", justifyContent: "center", ...style,
    }}>
      <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true"
        style={{ position: "absolute", inset: 0, opacity: dark ? 0.16 : 0.5 }}>
        <line x1="0" y1="0" x2="100" y2="100" stroke={dark ? "var(--border-on-dark)" : "var(--border-hairline)"} strokeWidth="0.4" vectorEffect="non-scaling-stroke" />
        <line x1="100" y1="0" x2="0" y2="100" stroke={dark ? "var(--border-on-dark)" : "var(--border-hairline)"} strokeWidth="0.4" vectorEffect="non-scaling-stroke" />
      </svg>
      {index && (
        <span style={{
          position: "absolute", top: 11, left: 12, fontFamily: "var(--font-sans)", fontSize: "10px",
          fontWeight: 500, letterSpacing: "0.14em", color: dark ? "var(--text-on-dark-muted)" : "var(--ink-400)",
        }}>{index}</span>
      )}
      <span style={{
        position: "relative", fontFamily: "var(--font-sans)", fontSize: "10px", fontWeight: 500,
        letterSpacing: "0.2em", textTransform: "uppercase", textAlign: "center", whiteSpace: "nowrap",
        color: dark ? "var(--text-on-dark-muted)" : "var(--ink-400)",
        background: dark ? "var(--ink-900)" : "var(--bone-200)", padding: "0 10px",
      }}>[ {label} ]</span>
    </div>
  );
}

function CFrame({ src, alt, index, label, ratio = "3 / 4", tone = "bone", hoverZoom = true, style }) {
  const [hover, setHover] = React.useState(false);
  if (!src) return <CImageSlot label={label || "Fotografía de producto"} index={index} ratio={ratio} tone={tone} style={style} />;
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ position: "relative", aspectRatio: ratio, overflow: "hidden", background: "var(--ink-900)", ...style }}>
      <img src={src} alt={alt || ""} style={{
        width: "100%", height: "100%", objectFit: "cover",
        transform: hoverZoom && hover ? "scale(1.04)" : "scale(1)",
        transition: "transform var(--dur-slower) var(--ease-out)",
      }} />
      {index && (
        <span style={{
          position: "absolute", top: 11, left: 12, fontFamily: "var(--font-sans)", fontSize: "10px",
          fontWeight: 500, letterSpacing: "0.14em", color: "rgba(255,255,255,.92)",
        }}>{index}</span>
      )}
    </div>
  );
}

/* ---------------------------------------------------------------- Header -- */
function CHeader({ route, go }) {
  const links = [["Catálogo", "catalogo"], ["La Casa", "about"], ["Contacto", "contacto"]];
  const mobile = useIsMobile(760);
  const shell = {
    position: "sticky", top: 0, zIndex: 100, background: "rgba(240,238,231,0.94)",
    backdropFilter: "blur(10px)", WebkitBackdropFilter: "blur(10px)",
    borderBottom: "1px solid var(--border-hairline)", paddingTop: "env(safe-area-inset-top)",
  };
  if (mobile) {
    return (
      <header style={shell}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px", padding: "11px 18px" }}>
          <button onClick={() => go("home")} style={{ background: "none", border: 0, padding: "4px 0", cursor: "pointer", textAlign: "left" }}>
            <div style={{ fontFamily: "var(--font-logo)", fontWeight: 700, fontSize: "21px", letterSpacing: "-0.01em", color: "var(--ink-900)", lineHeight: 1 }}>FEDUCCE</div>
            <div style={{ fontFamily: "var(--font-sans)", fontSize: "7px", fontWeight: 500, letterSpacing: "0.24em", color: "var(--ink-500)", marginTop: "4px" }}>CASA DE JOYERÍA EN ESMERALDA</div>
          </button>
          <a href={window.CAT_wa()} target="_blank" rel="noopener" aria-label="Escribir por WhatsApp" style={{
            display: "flex", alignItems: "center", justifyContent: "center", width: "44px", height: "44px",
            border: "1px solid var(--ink-900)", color: "var(--ink-900)", textDecoration: "none", flexShrink: 0,
          }}><WAGlyph size={20} /></a>
        </div>
        <nav style={{ display: "flex", borderTop: "1px solid var(--border-hairline)" }}>
          {links.map(([label, to]) => {
            const active = route === to;
            return (
              <button key={to} onClick={() => go(to)} style={{
                flex: 1, minHeight: "44px", background: active ? "var(--ink-900)" : "none", border: 0, cursor: "pointer",
                fontFamily: "var(--font-sans)", fontSize: "10px", fontWeight: 500, letterSpacing: "0.16em", textTransform: "uppercase",
                color: active ? "var(--bone-50)" : "var(--ink-500)",
                borderLeft: "1px solid var(--border-hairline)",
              }}>{label}</button>
            );
          })}
        </nav>
      </header>
    );
  }
  const navItem = ([label, to]) => {
    const active = route === to;
    return (
      <button key={to} onClick={() => go(to)} style={{
        background: "none", border: 0, cursor: "pointer", padding: "4px 0",
        fontFamily: "var(--font-sans)", fontSize: "11px", fontWeight: 500,
        letterSpacing: "0.18em", textTransform: "uppercase",
        color: active ? "var(--ink-900)" : "var(--ink-500)",
        borderBottom: active ? "1px solid var(--ink-900)" : "1px solid transparent",
        transition: "color var(--dur-base) var(--ease-standard)",
      }}>{label}</button>
    );
  };
  return (
    <header style={shell}>
      <div style={{
        display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center",
        padding: "16px 40px", maxWidth: "var(--container-wide)", margin: "0 auto",
      }}>
        <nav style={{ display: "flex", gap: "26px", alignItems: "center" }}>{links.map(navItem)}</nav>
        <button onClick={() => go("home")} style={{ background: "none", border: 0, cursor: "pointer", textAlign: "center" }}>
          <div style={{ fontFamily: "var(--font-logo)", fontWeight: 700, fontSize: "27px", letterSpacing: "-0.01em", color: "var(--ink-900)", lineHeight: 1 }}>FEDUCCE</div>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: "8px", fontWeight: 500, letterSpacing: "0.26em", color: "var(--ink-500)", marginTop: "5px" }}>CASA DE JOYERÍA EN ESMERALDA</div>
        </button>
        <div style={{ justifySelf: "end" }}>
          <WAButton variant="ghost" style={{ padding: "10px 16px", fontSize: "10px" }}>WhatsApp</WAButton>
        </div>
      </div>
    </header>
  );
}

/* ---------------------------------------------------------------- Footer -- */
function CFooter({ go }) {
  const col = (title, items) => (
    <div style={{ display: "flex", flexDirection: "column", gap: "14px" }}>
      <div style={{ fontFamily: "var(--font-sans)", fontSize: "10px", fontWeight: 500, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--text-on-dark-muted)" }}>{title}</div>
      {items.map(([label, fn]) => (
        <button key={label} onClick={fn} style={{
          background: "none", border: 0, padding: "3px 0", textAlign: "left", cursor: "pointer",
          fontFamily: "var(--font-sans)", fontSize: "13px", letterSpacing: "0.02em", color: "var(--bone-100)",
        }}>{label}</button>
      ))}
    </div>
  );
  return (
    <footer data-surface="invert" className="r-pad" style={{ background: "var(--ink-900)", padding: "80px 40px calc(32px + env(safe-area-inset-bottom))" }}>
      <div style={{ maxWidth: "var(--container-wide)", margin: "0 auto" }}>
        <div className="r-foot" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1.2fr", gap: "48px", alignItems: "start" }}>
          <div>
            <div style={{ fontFamily: "var(--font-logo)", fontWeight: 700, fontSize: "clamp(40px, 5vw, 72px)", letterSpacing: "-0.02em", color: "var(--bone-50)", lineHeight: 0.9 }}>FEDUCCE</div>
            <p style={{ fontFamily: "var(--font-body)", fontSize: "14px", color: "var(--text-on-dark-muted)", marginTop: "22px", maxWidth: "30ch", lineHeight: 1.6 }}>
              Joyería contemporánea en esmeralda. Formas escultóricas. Materiales atemporales. Hecha para vivirse.
            </p>
          </div>
          {col("Catálogo", window.CAT_PRODUCTS.map((p) => [window.CAT_full(p), () => go("product", { id: p.id })]))}
          {col("La Casa", [["Nuestra historia", () => go("about")], ["Origen — Colombia", () => go("about")], ["Cómo comprar", () => go("contacto")]])}
          <div style={{ display: "flex", flexDirection: "column", gap: "16px", alignItems: "flex-start" }}>
            <div style={{ fontFamily: "var(--font-sans)", fontSize: "10px", fontWeight: 500, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--text-on-dark-muted)" }}>Contacto</div>
            <p style={{ fontFamily: "var(--font-body)", fontSize: "13px", color: "var(--text-on-dark-muted)", lineHeight: 1.6 }}>
              Atendemos por WhatsApp. Escríbenos y te acompañamos en la elección de tu par.
            </p>
            <WAButton variant="onDark" style={{ padding: "12px 18px", fontSize: "10px" }}>{window.CAT_WHATSAPP_LABEL}</WAButton>
            <a href={"https://instagram.com/" + window.CAT_INSTAGRAM.replace("@", "")} target="_blank" rel="noopener" style={{
              fontFamily: "var(--font-sans)", fontSize: "11px", fontWeight: 500, letterSpacing: "0.16em",
              textTransform: "uppercase", color: "var(--bone-100)", textDecoration: "none",
              borderBottom: "1px solid var(--border-on-dark)", paddingBottom: "3px",
            }}>Instagram {window.CAT_INSTAGRAM}</a>
          </div>
        </div>
        <div className="r-footbar" style={{
          marginTop: "64px", paddingTop: "22px", borderTop: "1px solid var(--border-on-dark)",
          display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center",
          fontFamily: "var(--font-sans)", fontSize: "10px", fontWeight: 500, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--text-on-dark-muted)",
        }}>
          <span style={{ justifySelf: "start" }}>FEDUCCE.COM</span>
          <span style={{ justifySelf: "center" }}>BOGOTÁ · COLOMBIA</span>
          <span style={{ justifySelf: "end" }}>TODOS LOS DERECHOS RESERVADOS</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { WAGlyph, WAButton, WAFloat, CImageSlot, CFrame, useIsMobile });
window.FEDCAT_UI = { WAGlyph, WAButton, WAFloat, CImageSlot, CFrame, CHeader, CFooter, useIsMobile };
