// Shared components for Artesanías Chepe

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

// ----- Currency -----
const formatMXN = (n) => "$" + n.toLocaleString("es-MX", { maximumFractionDigits: 0 });

// ----- Logo (proxy to Lockup system) -----
const Logo = ({ size = 48, light = false, orientation = "stacked", variant = "henequen", showTagline = true }) => {
  return (
    <window.Lockup
      size={size}
      color={light ? "bone" : "ink"}
      orientation={orientation}
      variant={variant}
      showTagline={showTagline}
    />
  );
};

// ----- Top Bar -----
const TopBar = ({ onMenu, onCart, cartCount, onLogo, scrolled }) => (
  <header style={{
    position: "sticky", top: 0, zIndex: 30,
    background: scrolled ? "color-mix(in srgb, var(--bone) 92%, transparent)" : "transparent",
    backdropFilter: scrolled ? "saturate(140%) blur(12px)" : "none",
    WebkitBackdropFilter: scrolled ? "saturate(140%) blur(12px)" : "none",
    borderBottom: scrolled ? "1px solid var(--hair)" : "1px solid transparent",
    transition: "all .25s ease",
  }}>
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "14px 20px",
    }}>
      <button onClick={onMenu} aria-label="Menú"
        style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: 999, color: "var(--ink)" }}>
        <Icon name="menu" size={20} />
      </button>
      <button onClick={onLogo} style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <window.Mark size={28} strokeWidth={3.2} />
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", lineHeight: 0.92 }}>
          <span style={{
            fontFamily: "var(--serif)", fontWeight: 500,
            fontSize: 11, color: "var(--ink-80)",
            letterSpacing: "0.05em",
          }}>Artesanías</span>
          <span className="logo-chepe" style={{ fontSize: 24, marginTop: 1 }}>Chepe</span>
        </div>
      </button>
      <button onClick={onCart} aria-label="Bolsa"
        style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: 999, color: "var(--ink)", position: "relative" }}>
        <Icon name="bag" size={20} />
        {cartCount > 0 && (
          <span style={{
            position: "absolute", top: 2, right: 2,
            background: "var(--clay)", color: "var(--bone)",
            minWidth: 18, height: 18, borderRadius: 999,
            display: "grid", placeItems: "center",
            fontFamily: "var(--mono)", fontSize: 10, fontWeight: 600,
            padding: "0 5px",
          }}>{cartCount}</span>
        )}
      </button>
    </div>
  </header>
);

// ----- Drawer Menu -----
const DrawerMenu = ({ open, onClose, onNav, page }) => {
  const drawerRef = useRef(null);
  const items = [
    { id: "home",       label: "Inicio" },
    { id: "catalog",    label: "Catálogo" },
    { id: "projects",   label: "Proyectos comerciales" },
    { id: "wholesale",  label: "Mayoreo" },
    { id: "about",      label: "Sobre Chepe" },
    { id: "brand",      label: "Marca · Identidad" },
    { id: "contact",    label: "Contacto" },
  ];

  // Esc + focus trap
  useEffect(() => {
    const el = drawerRef.current;
    if (!el) return;
    if (!open) {
      el.setAttribute("inert", "");
      el.setAttribute("aria-hidden", "true");
      return;
    }
    el.removeAttribute("inert");
    el.setAttribute("aria-hidden", "false");

    const FOCUSABLE = 'button:not([disabled]), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
    const focusable = [...el.querySelectorAll(FOCUSABLE)];
    if (focusable.length) focusable[0].focus();

    const onKeyDown = (e) => {
      if (e.key === "Escape") { onClose(); return; }
      if (e.key !== "Tab" || !focusable.length) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (e.shiftKey) {
        if (document.activeElement === first) { e.preventDefault(); last.focus(); }
      } else {
        if (document.activeElement === last) { e.preventDefault(); first.focus(); }
      }
    };
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [open, onClose]);

  return (
    <React.Fragment>
      {open && (
        <div onClick={onClose} style={{
          position: "fixed", inset: 0, background: "color-mix(in srgb, var(--ink) 50%, transparent)", zIndex: 40,
          animation: "fadeIn .25s ease",
        }} />
      )}
      <aside
        ref={drawerRef}
        role="dialog"
        aria-modal="true"
        aria-label="Menú de navegación"
        style={{
        position: "fixed", top: 0, left: 0, bottom: 0,
        width: "min(360px, 86vw)", background: "var(--bone)",
        zIndex: 50, transform: open ? "translateX(0)" : "translateX(-100%)",
        transition: "transform .35s cubic-bezier(.2,.7,.2,1)",
        boxShadow: "var(--shadow)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 20px 8px" }}>
          <span className="eyebrow">Menú</span>
          <button onClick={onClose} aria-label="Cerrar"
            style={{ width: 38, height: 38, display: "grid", placeItems: "center", borderRadius: 999, color: "var(--ink)" }}>
            <Icon name="close" size={20} />
          </button>
        </div>
        <div style={{ padding: "0 24px", flex: 1 }}>
          <div style={{ marginTop: 12, marginBottom: 24, display: "flex", justifyContent: "flex-start" }}>
            <window.Lockup size={54} orientation="integrated" color="ink" wordSize={48} />
          </div>
          <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {items.map((it) => (
              <button key={it.id}
                onClick={() => { onNav(it.id); onClose(); }}
                style={{
                  textAlign: "left", padding: "14px 0",
                  borderBottom: "1px solid var(--hair)",
                  fontFamily: "var(--serif)", fontSize: 26, fontWeight: 500,
                  color: page === it.id ? "var(--clay)" : "var(--ink)",
                  fontStyle: page === it.id ? "italic" : "normal",
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                }}>
                <span>{it.label}</span>
                {page === it.id && <Icon name="arrow" size={18} />}
              </button>
            ))}
          </nav>
        </div>
        <div style={{ padding: "24px", borderTop: "1px solid var(--hair)" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Síguenos</div>
          <div style={{ display: "flex", gap: 10 }}>
            {[
              { n: "ig",  label: "Instagram" },
              { n: "fb",  label: "Facebook" },
              { n: "pin", label: "Pinterest" },
              { n: "wa",  label: "WhatsApp" },
            ].map(({ n, label }) => (
              <button key={n} aria-label={label} className="hair" style={{
                width: 40, height: 40, borderRadius: 999, display: "grid", placeItems: "center", color: "var(--ink-80)"
              }}><Icon name={n} size={18} /></button>
            ))}
          </div>
          <p className="mono" style={{ fontSize: 10, letterSpacing: "0.12em", color: "var(--ink-60)", marginTop: 18 }}>
            Calle 60 × 41, Centro · Mérida<br />Lun–Sáb · 10:00–19:00
          </p>
        </div>
      </aside>
    </React.Fragment>
  );
};

// ----- Cart Drawer -----
const CartDrawer = ({ open, onClose, items, onChangeQty, onRemove, onCheckout, onContinue }) => {
  const drawerRef = useRef(null);
  const subtotal = items.reduce((a, it) => a + it.price * it.qty, 0);

  // Esc + focus trap
  useEffect(() => {
    const el = drawerRef.current;
    if (!el) return;
    if (!open) {
      el.setAttribute("inert", "");
      el.setAttribute("aria-hidden", "true");
      return;
    }
    el.removeAttribute("inert");
    el.setAttribute("aria-hidden", "false");

    const FOCUSABLE = 'button:not([disabled]), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
    const focusable = [...el.querySelectorAll(FOCUSABLE)];
    if (focusable.length) focusable[0].focus();

    const onKeyDown = (e) => {
      if (e.key === "Escape") { onClose(); return; }
      if (e.key !== "Tab" || !focusable.length) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (e.shiftKey) {
        if (document.activeElement === first) { e.preventDefault(); last.focus(); }
      } else {
        if (document.activeElement === last) { e.preventDefault(); first.focus(); }
      }
    };
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [open, onClose]);

  return (
    <React.Fragment>
      {open && (
        <div onClick={onClose} style={{
          position: "fixed", inset: 0, background: "color-mix(in srgb, var(--ink) 50%, transparent)", zIndex: 60,
          animation: "fadeIn .25s ease",
        }} />
      )}
      <aside
        ref={drawerRef}
        role="dialog"
        aria-modal="true"
        aria-label="Tu bolsa de compra"
        style={{
        position: "fixed", top: 0, right: 0, bottom: 0,
        width: "min(420px, 92vw)", background: "var(--bone)",
        zIndex: 70, transform: open ? "translateX(0)" : "translateX(100%)",
        transition: "transform .35s cubic-bezier(.2,.7,.2,1)",
        boxShadow: "var(--shadow)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "18px 20px", borderBottom: "1px solid var(--hair)" }}>
          <div>
            <div className="eyebrow">Tu bolsa</div>
            <div className="serif" style={{ fontSize: 22, marginTop: 2 }}>
              {items.length} {items.length === 1 ? "pieza" : "piezas"}
            </div>
          </div>
          <button onClick={onClose} aria-label="Cerrar"
            style={{ width: 38, height: 38, display: "grid", placeItems: "center", borderRadius: 999 }}>
            <Icon name="close" size={20} />
          </button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "12px 20px" }}>
          {items.length === 0 && (
            <div style={{ textAlign: "center", padding: "60px 12px" }}>
              <div className="ph" style={{ width: 100, height: 100, borderRadius: 999, margin: "0 auto 18px" }}></div>
              <div className="serif italic" style={{ fontSize: 26, marginBottom: 8 }}>Tu bolsa está vacía</div>
              <p style={{ color: "var(--ink-60)", fontSize: 14, marginBottom: 22 }}>Encuentra piezas tejidas a mano para tu casa.</p>
              <button className="btn btn-primary" onClick={() => { onClose(); onContinue(); }}>
                Ver catálogo <Icon name="arrow" size={16} />
              </button>
            </div>
          )}
          {items.map((it, i) => (
            <div key={it.lineId} className="fade-up" style={{
              display: "grid", gridTemplateColumns: "84px 1fr", gap: 14,
              padding: "14px 0", borderBottom: "1px solid var(--hair)",
              animationDelay: (i * 40) + "ms",
            }}>
              <div className={"ph " + (it.placeholderClass || "")} style={{
                width: 84, height: 96, borderRadius: 10,
                fontSize: 8,
              }}>{it.placeholderLabel}</div>
              <div style={{ display: "flex", flexDirection: "column" }}>
                <div className="serif" style={{ fontSize: 18, lineHeight: 1.15 }}>{it.name}</div>
                <div className="mono" style={{ fontSize: 10, color: "var(--ink-60)", letterSpacing: "0.1em", marginTop: 4, textTransform: "uppercase" }}>
                  {[it.finish, it.size, it.material].filter(Boolean).join(" · ")}
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: "auto", paddingTop: 8 }}>
                  <div className="hair" style={{
                    display: "inline-flex", alignItems: "center", borderRadius: 999,
                    overflow: "hidden",
                  }}>
                    <button aria-label="Quitar uno" onClick={() => onChangeQty(it.lineId, -1)} style={{ width: 32, height: 32, display: "grid", placeItems: "center" }}>
                      <Icon name="minus" size={14} />
                    </button>
                    <span className="mono" style={{ fontSize: 13, width: 24, textAlign: "center" }}>{it.qty}</span>
                    <button aria-label="Agregar uno" onClick={() => onChangeQty(it.lineId, +1)} style={{ width: 32, height: 32, display: "grid", placeItems: "center" }}>
                      <Icon name="plus" size={14} />
                    </button>
                  </div>
                  <div className="mono" style={{ fontSize: 13, fontWeight: 600 }}>{formatMXN(it.price * it.qty)}</div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {items.length > 0 && (
          <div style={{ padding: "16px 20px", borderTop: "1px solid var(--hair)", background: "var(--paper)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-60)" }}>Subtotal</span>
              <span className="serif" style={{ fontSize: 22 }}>{formatMXN(subtotal)}</span>
            </div>
            <p className="mono" style={{ fontSize: 10, color: "var(--ink-60)", letterSpacing: "0.08em", marginBottom: 14 }}>
              Envío e impuestos calculados al pagar
            </p>
            <button className="btn btn-primary btn-block" onClick={onCheckout}>
              Continuar al pago <Icon name="arrow" size={16} />
            </button>
            <button className="btn btn-ghost btn-block" style={{ marginTop: 8 }} onClick={() => { onClose(); onContinue(); }}>
              Seguir comprando
            </button>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
};

// ----- Footer -----
const Footer = ({ onNav }) => (
  <footer style={{ background: "var(--ink)", color: "var(--bone)", padding: "48px 24px 32px", marginTop: 60 }}>
    <div style={{ marginBottom: 32, display: "flex", justifyContent: "center" }}>
      <window.Lockup size={64} orientation="stacked" color="bone" wordSize={56} />
    </div>

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "28px 20px", marginBottom: 32 }}>
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "color-mix(in srgb, var(--bone) 50%, transparent)", marginBottom: 12 }}>Tienda</div>
        {[["catalog","Catálogo"],["projects","Proyectos"],["wholesale","Mayoreo"]].map(([id,l]) => (
          <button key={id} onClick={() => onNav(id)} style={{ display: "block", padding: "6px 0", color: "var(--bone)", fontSize: 14 }}>{l}</button>
        ))}
      </div>
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "color-mix(in srgb, var(--bone) 50%, transparent)", marginBottom: 12 }}>Casa</div>
        {[["about","Historia"],["contact","Contacto"],["contact","WhatsApp"]].map(([id,l],i) => (
          <button key={i} onClick={() => onNav(id)} style={{ display: "block", padding: "6px 0", color: "var(--bone)", fontSize: 14 }}>{l}</button>
        ))}
      </div>
    </div>

    <div style={{ display: "flex", gap: 10, justifyContent: "center", marginBottom: 28 }}>
      {[
        { n: "ig",  label: "Instagram" },
        { n: "fb",  label: "Facebook" },
        { n: "pin", label: "Pinterest" },
        { n: "wa",  label: "WhatsApp" },
      ].map(({ n, label }) => (
        <button key={n} aria-label={label} style={{
          width: 40, height: 40, borderRadius: 999,
          border: "1px solid color-mix(in srgb, var(--bone) 25%, transparent)", color: "var(--bone)",
          display: "grid", placeItems: "center",
        }}><Icon name={n} size={18} /></button>
      ))}
    </div>

    <div className="mono" style={{ fontSize: 9, letterSpacing: "0.12em", color: "color-mix(in srgb, var(--bone) 45%, transparent)", textAlign: "center", lineHeight: 1.8 }}>
      <div>Calle 60 × 41, Centro Histórico · Mérida, Yuc.</div>
      <div>Lun – Sáb · 10:00 – 19:00</div>
      <div style={{ marginTop: 18 }}>© 2026 Artesanías Chepe · Hecho a mano en Yucatán</div>
    </div>
  </footer>
);

// ----- Section header -----
const SectionHead = ({ eyebrow, title, action, onAction }) => (
  <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 18 }}>
    <div>
      {eyebrow && <div className="eyebrow" style={{ marginBottom: 6 }}>{eyebrow}</div>}
      <h2 className="display" style={{ fontSize: 30, margin: 0 }}>{title}</h2>
    </div>
    {action && (
      <button onClick={onAction} style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--ink-80)", fontSize: 13, paddingBottom: 6 }}>
        {action} <Icon name="arrow" size={14} />
      </button>
    )}
  </div>
);

// ----- Product Card -----
const ProductCard = ({ product, onClick, onAdd, compact }) => {
  const images = product.images || [];
  const hasImages = images.length > 0;
  const [activeImg, setActiveImg] = useState(0);
  const touchStartX = useRef(null);
  const didSwipe = useRef(false);

  const onTouchStart = (e) => {
    touchStartX.current = e.touches[0].clientX;
    didSwipe.current = false;
  };
  const onTouchEnd = (e) => {
    if (touchStartX.current === null || images.length <= 1) return;
    const diff = touchStartX.current - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 40) {
      didSwipe.current = true;
      if (diff > 0) setActiveImg(i => Math.min(i + 1, images.length - 1));
      else setActiveImg(i => Math.max(i - 1, 0));
    }
    touchStartX.current = null;
  };
  const handleClick = () => { if (!didSwipe.current) onClick(product); };

  return (
    <article
      onClick={handleClick}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onClick(product); } }}
      tabIndex={0}
      role="article"
      aria-label={product.name}
      className="fade-up"
      style={{ cursor: "pointer", width: compact ? 240 : "100%", outline: "none" }}
    >
      <div
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{
          aspectRatio: compact ? "3/4" : "4/5",
          borderRadius: 14,
          marginBottom: 10,
          position: "relative",
          overflow: "hidden",
        }}
      >
        {/* Imagen real o placeholder */}
        {hasImages ? (
          <img
            src={images[activeImg]}
            alt={product.name}
            style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", userSelect: "none" }}
            draggable={false}
          />
        ) : (
          <div className={"ph " + (product.placeholderClass || "")} style={{ position: "absolute", inset: 0 }}>
            <span style={{ position: "absolute", bottom: 12, left: 12 }}>{product.placeholderLabel}</span>
          </div>
        )}

        {/* Badge */}
        {product.badge && (
          <span style={{
            position: "absolute", top: 10, left: 10, zIndex: 2,
            background: "var(--ink)", color: "var(--bone)",
            padding: "5px 10px", borderRadius: 999,
            fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase",
          }}>{product.badge}</span>
        )}

        {/* Botón agregar */}
        <button onClick={(e) => { e.stopPropagation(); onAdd && onAdd(product, e); }}
          aria-label="Agregar a bolsa"
          style={{
            position: "absolute", bottom: 10, right: 10, zIndex: 2,
            width: 40, height: 40, borderRadius: 999,
            background: "var(--bone)", color: "var(--ink)",
            display: "grid", placeItems: "center",
            boxShadow: "var(--shadow-sm)",
          }}>
          <Icon name="plus" size={18} />
        </button>

        {/* Dots estilo Instagram */}
        {images.length > 1 && (
          <div aria-hidden="true" style={{
            position: "absolute", bottom: 12, left: "50%", transform: "translateX(-50%)",
            display: "flex", gap: 5, zIndex: 2,
          }}>
            {images.map((_, i) => (
              <span key={i} style={{
                width: i === activeImg ? 16 : 6, height: 6, borderRadius: 999,
                background: i === activeImg
                  ? "var(--bone)"
                  : "color-mix(in srgb, var(--bone) 55%, transparent)",
                transition: "width .22s ease",
              }} />
            ))}
          </div>
        )}
      </div>

      <div style={{ paddingRight: 6 }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
          <h3 className="serif" style={{ fontSize: 17, fontWeight: 500, margin: 0, lineHeight: 1.2 }}>{product.name}</h3>
          <span className="mono" style={{ fontSize: 13, whiteSpace: "nowrap" }}>{formatMXN(product.price)}</span>
        </div>
        <p className="mono" style={{ fontSize: 10, color: "var(--ink-60)", letterSpacing: "0.1em", textTransform: "uppercase", marginTop: 4, marginBottom: 0 }}>
          {product.materials[0]}
        </p>
      </div>
    </article>
  );
};

// ----- Marquee -----
const Marquee = ({ items, speed = 32 }) => (
  <div aria-hidden="true" style={{
    overflow: "hidden", borderTop: "1px solid var(--hair)", borderBottom: "1px solid var(--hair)",
    padding: "14px 0", background: "var(--paper)",
  }}>
    <div style={{
      display: "flex", gap: 40, whiteSpace: "nowrap",
      animation: `marquee ${speed}s linear infinite`,
    }}>
      {[...items, ...items, ...items].map((t, i) => (
        <span key={i} className="mono" style={{
          fontSize: 12, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-80)",
        }}>{t} <span style={{ color: "var(--clay)", marginLeft: 40 }}>✦</span></span>
      ))}
    </div>
    <style>{`@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-33.333%); } }`}</style>
  </div>
);

window.formatMXN  = formatMXN;
window.Logo       = Logo;
window.TopBar     = TopBar;
window.DrawerMenu = DrawerMenu;
window.CartDrawer = CartDrawer;
window.Footer     = Footer;
window.SectionHead= SectionHead;
window.ProductCard= ProductCard;
window.Marquee    = Marquee;
