// Common.jsx — Allen Web Ecommerce shared bits.
// Exports: AllenHeader, AllenFooter, AllenIcon, ProductCard, RatingStars,
// Breadcrumb, EmptyState, plus a useToast hook.
const { useState, useEffect, useRef, createContext, useContext } = React;

// ---------------------------------------------------------------
// Icon helper — material symbols outlined (CDN).
const AllenIcon = ({ name, size = 20, weight = 400, fill = 0, color = "currentColor", style }) => (
  <span
    className="material-symbols-outlined"
    style={{
      fontSize: size,
      color,
      fontVariationSettings: `"FILL" ${fill}, "wght" ${weight}, "GRAD" 0, "opsz" ${size}`,
      verticalAlign: "middle",
      ...style,
    }}
  >
    {name}
  </span>
);

// ---------------------------------------------------------------
// Toast context (lightweight)
const ToastCtx = createContext(() => {});
const useToast = () => useContext(ToastCtx);
const ToastHost = ({ children }) => {
  const [msg, setMsg] = useState(null);
  const timer = useRef();
  const show = (m) => {
    clearTimeout(timer.current);
    setMsg(m);
    timer.current = setTimeout(() => setMsg(null), 2200);
  };
  return (
    <ToastCtx.Provider value={show}>
      {children}
      <div style={{
        position: "fixed", bottom: 24, left: "50%", transform: `translateX(-50%) translateY(${msg ? "0" : "12px"})`,
        background: "var(--hub-black)", color: "#fff", padding: "12px 20px", borderRadius: "9999px",
        font: "600 13px var(--font-sans)", boxShadow: "var(--elev-3)",
        opacity: msg ? 1 : 0, transition: "all .25s var(--ease-out-quart)", pointerEvents: "none",
        zIndex: 999, whiteSpace: "nowrap"
      }}>{msg}</div>
    </ToastCtx.Provider>
  );
};

// ---------------------------------------------------------------
// Rating stars
const RatingStars = ({ value = 4.6, count, size = 14 }) => {
  const full = Math.floor(value);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, font: "600 12px var(--font-sans)", color: "var(--fg-strong)" }}>
      <span style={{ display: "inline-flex", gap: 1, color: "var(--star)" }}>
        {[0,1,2,3,4].map(i => (
          <AllenIcon key={i} name={i < full ? "star" : "star_border"} size={size} fill={i < full ? 1 : 0} />
        ))}
      </span>
      <span>{value.toFixed(1)}</span>
      {count != null && <span style={{ color: "var(--fg-subtle)", fontWeight: 500 }}>({count.toLocaleString("es-MX")})</span>}
    </span>
  );
};

// ---------------------------------------------------------------
// Product card (PLP / carousel)
const ProductCard = ({ p, onOpen, onAdd, onFav, fav }) => (
  <div
    className="allen-card"
    onClick={() => onOpen?.(p)}
    style={{
      background: "var(--bg-elev-1)", borderRadius: "var(--radius-card)", padding: 14,
      display: "flex", flexDirection: "column", gap: 8,
      boxShadow: "var(--elev-1)", cursor: "pointer",
      transition: "transform var(--dur-base) var(--ease-out-quart), box-shadow var(--dur-base) var(--ease-out-quart)",
    }}
    onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--elev-2)"; }}
    onMouseLeave={e => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "var(--elev-1)"; }}
  >
    <div style={{
      position: "relative", aspectRatio: 1, borderRadius: "var(--radius-image)",
      background: p.imgBg || "var(--bg-section)", display: "grid", placeItems: "center",
      overflow: "hidden",
    }}>
      {p.img ? (
        <img src={p.img} alt={p.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
      ) : (
        <span style={{ fontSize: 64 }}>{p.emoji}</span>
      )}
      {p.discount && (
        <span style={{
          position: "absolute", top: 10, left: 10, padding: "4px 10px", borderRadius: 10,
          background: "var(--discount)", color: "#fff", font: "700 11px var(--font-sans)",
          letterSpacing: ".02em",
        }}>−{p.discount}%</span>
      )}
      <button
        onClick={e => { e.stopPropagation(); onFav?.(p); }}
        style={{
          position: "absolute", top: 10, right: 10, width: 34, height: 34, borderRadius: 17,
          background: "rgba(255,255,255,.94)", border: 0, cursor: "pointer", display: "grid", placeItems: "center",
          boxShadow: "var(--elev-1)", color: fav ? "#B691FF" : "var(--fg-muted)",
        }}
        aria-label="Favoritos"
      >
        <AllenIcon name="favorite" size={18} fill={fav ? 1 : 0} weight={500} />
      </button>
    </div>
    <div style={{ font: "500 11px var(--font-sans)", color: "var(--fg-subtle)", textTransform: "uppercase", letterSpacing: ".05em" }}>{p.brand}</div>
    <div style={{ font: "600 14px/1.3 var(--font-sans)", color: "var(--fg-strong)", minHeight: 36 }}>{p.name}</div>
    <RatingStars value={p.rating} count={p.reviews} size={13} />
    <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 2 }}>
      <span className="price">${p.price.toLocaleString("es-MX")}</span>
      {p.was && <span style={{ font: "500 13px var(--font-sans)", color: "var(--fg-hint)", textDecoration: "line-through" }}>${p.was.toLocaleString("es-MX")}</span>}
    </div>
    {p.shipping && (
      <div style={{ font: "600 12px var(--font-sans)", color: "var(--success)", display: "flex", alignItems: "center", gap: 4 }}>
        <AllenIcon name="local_shipping" size={14} /> {p.shipping}
      </div>
    )}
    <button
      onClick={e => { e.stopPropagation(); onAdd?.(p); }}
      style={{
        marginTop: 4, background: "var(--primary)", color: "#fff", border: 0, borderRadius: "9999px",
        padding: "10px 16px", font: "600 13px var(--font-sans)", cursor: "pointer",
        boxShadow: "var(--elev-cta-blue)", transition: "background var(--dur-fast) var(--ease-out-quart)",
      }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--primary-hover)"}
      onMouseLeave={e => e.currentTarget.style.background = "var(--primary)"}
    >Agregar al carrito</button>
  </div>
);

// ---------------------------------------------------------------
// Viewport hook — used across pages to swap grid configs at mobile/tablet/desktop.
// Buckets: 'mobile' < 768 | 'tablet' < 1100 | 'desktop' >= 1100
const useViewport = () => {
  const [w, setW] = useState(() => typeof window === "undefined" ? 1280 : window.innerWidth);
  useEffect(() => {
    const onR = () => setW(window.innerWidth);
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, []);
  return {
    w,
    isMobile: w < 768,
    isTablet: w >= 768 && w < 1100,
    isDesktop: w >= 1100,
  };
};

// ---------------------------------------------------------------
// Theme toggle — light <-> dark, persisted in localStorage.
// PRODUCT.md mandates dark mode day-one; this is the web counterpart.
const useTheme = () => {
  const [theme, setTheme] = useState(() => {
    if (typeof window === "undefined") return "light";
    return localStorage.getItem("allen-theme") || "light";
  });
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("allen-theme", theme);
  }, [theme]);
  return [theme, () => setTheme(t => t === "light" ? "dark" : "light")];
};

const ThemeToggle = () => {
  const [theme, toggle] = useTheme();
  const isDark = theme === "dark";
  return (
    <button onClick={toggle} aria-label={isDark ? "Cambiar a modo claro" : "Cambiar a modo oscuro"}
      style={{
        width: 40, height: 40, borderRadius: 20, background: "transparent",
        border: 0, cursor: "pointer", display: "grid", placeItems: "center",
        color: "var(--fg-strong)",
        transition: "background var(--dur-fast) var(--ease-out-quart)",
      }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--bg-elev-2)"}
      onMouseLeave={e => e.currentTarget.style.background = "transparent"}
    >
      {isDark ? (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="4"/>
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
        </svg>
      ) : (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"/>
        </svg>
      )}
    </button>
  );
};

// ---------------------------------------------------------------
// Header (utility bar + main nav)
const AllenHeader = ({ cartCount, user, onNav, onLogout, currentPath = "/", onReview }) => {
  const toast = useToast();
  const [q, setQ] = useState("");
  const [mobileMenu, setMobileMenu] = useState(false);
  const [mobileSearch, setMobileSearch] = useState(false);
  const { isMobile, isTablet } = useViewport();
  const navItems = [
    { id: "home",       label: "Inicio" },
    { id: "ofertas",    label: "Ofertas" },
    { id: "novedades",  label: "Lo más nuevo" },
    { id: "marcas",     label: "Marcas" },
    { id: "vende",      label: "Vende en Allen" },
  ];
  const handleNav = (id) => {
    setMobileMenu(false);
    if (id === "home")     return onNav("home");
    if (id === "ofertas")  return onNav("plp", { onlyDiscount: true });
    if (id === "novedades")return onNav("plp", { sort: "newest" });
    if (id === "marcas")   return onNav("plp");
    if (id === "vende")    return onNav("vende");
  };
  const submitSearch = (e) => {
    e?.preventDefault?.();
    const v = q.trim();
    if (!v) return;
    setMobileSearch(false);
    onNav("plp", { q: v });
  };
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 50, background: "var(--bg-elev-1)" }}>
      {/* Utility bar (desktop/tablet only) */}
      {!isMobile && (
        <div style={{
          background: "var(--hub-black)", color: "var(--fg-on-dark-muted)",
          padding: "8px 32px", display: "flex", alignItems: "center", gap: 24,
          font: "500 12px var(--font-sans)",
        }}>
          <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <AllenIcon name="location_on" size={14} color="#fff" />
            <span style={{ color: "#fff", fontWeight: 600 }}>Enviar a</span> Puerto Vallarta · 48330
          </span>
          <span style={{ flex: 1 }} />
          <a onClick={() => onNav("seller-onboarding")} style={{ cursor: "pointer" }}>Vende en Allen</a>
          <a onClick={() => onNav("ops")} style={{ cursor: "pointer" }}>Allen Ops</a>
          <a onClick={() => toast("Allen Food · Travel · Experts")} style={{ cursor: "pointer" }}>Otras verticales</a>
          <a onClick={() => toast("Centro de ayuda")} style={{ cursor: "pointer" }}>Ayuda</a>
        </div>
      )}

      {/* Main header */}
      <div style={{
        padding: isMobile ? "12px 16px" : "18px 32px",
        display: "flex", alignItems: "center", gap: isMobile ? 8 : 28,
        borderBottom: "1px solid var(--border)",
      }}>
        {isMobile && (
          <button onClick={() => setMobileMenu(true)} aria-label="Menú" style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--fg-strong)", display: "grid", placeItems: "center" }}>
            <AllenIcon name="menu" size={24} />
          </button>
        )}
        <a onClick={() => onNav("home")} style={{ cursor: "pointer", display: "flex", alignItems: "center" }}>
          <img src="../../assets/allen_black_letter_logo.svg" alt="Allen" style={{ height: isMobile ? 22 : 28 }} />
        </a>
        {!isMobile && (
          <form onSubmit={submitSearch} style={{
            flex: 1, maxWidth: 640, display: "flex", alignItems: "center", gap: 10,
            background: "var(--bg-search)", border: "1px solid var(--border-strong)",
            borderRadius: "9999px", padding: "12px 18px",
          }}>
            <AllenIcon name="search" size={20} color="var(--fg-soft)" />
            <input
              value={q}
              onChange={e => setQ(e.target.value)}
              placeholder={isTablet ? "Busca productos…" : "Busca productos, marcas o categorías…"}
              style={{ flex: 1, border: 0, outline: 0, background: "transparent", font: "400 14px var(--font-sans)", color: "var(--fg-strong)" }}
            />
            {q && (
              <button type="button" onClick={() => setQ("")} aria-label="Limpiar"
                style={{ background: "transparent", border: 0, padding: 4, cursor: "pointer", color: "var(--fg-muted)", display: "grid", placeItems: "center" }}>
                <AllenIcon name="close" size={16} />
              </button>
            )}
            {!isTablet && <span style={{ font: "500 11px var(--font-mono)", color: "var(--fg-hint)" }}>⌘ K</span>}
          </form>
        )}
        <div style={{ flex: isMobile ? 1 : "none" }} />
        {isMobile && (
          <button onClick={() => setMobileSearch(true)} aria-label="Buscar" style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--fg-strong)", display: "grid", placeItems: "center" }}>
            <AllenIcon name="search" size={22} />
          </button>
        )}
        {!isMobile && !isTablet && (
          <>
            <button onClick={() => user ? onNav("account") : onNav("login")} style={headerBtn}>
              <AllenIcon name="person" size={20} /> {user ? user.name.split(/\s+/)[0] : "Inicia sesión"}
            </button>
            <button onClick={() => user ? onNav("account", { tab: "favoritos" }) : onNav("login")} style={headerBtn}>
              <AllenIcon name="favorite" size={20} /> Favoritos
            </button>
          </>
        )}
        {isTablet && (
          <button onClick={() => user ? onNav("account") : onNav("login")} style={{ ...headerBtn, padding: 8 }} aria-label="Cuenta">
            <AllenIcon name="person" size={22} />
          </button>
        )}
        <ThemeToggle />
        {!isMobile && typeof window.NotificationBell !== "undefined" && (
          <NotificationBell onNav={onNav} onReview={onReview} />
        )}
        <button onClick={() => onNav("cart")} style={{ ...headerBtn, position: "relative", padding: isMobile ? 8 : headerBtn.padding }}>
          <AllenIcon name="shopping_cart" size={isMobile ? 22 : 20} />
          {!isMobile && !isTablet && " Carrito"}
          {cartCount > 0 && (
            <span style={{
              position: "absolute", top: isMobile ? -2 : 4, right: isMobile ? -2 : 4,
              minWidth: 18, height: 18, padding: "0 5px",
              borderRadius: 9, background: "var(--primary)", color: "#fff",
              font: "700 10px/18px var(--font-sans)", textAlign: "center",
              border: "2px solid var(--bg-elev-1)",
            }}>{cartCount}</span>
          )}
        </button>
      </div>

      {/* Sub-nav (desktop only) */}
      {!isMobile && (
        <nav style={{
          display: "flex", gap: 6, padding: "10px 32px", borderBottom: "1px solid var(--border-soft)",
          background: "var(--bg-elev-1)", overflowX: "auto",
        }}>
          {navItems.map(n => (
            <button key={n.id} onClick={() => handleNav(n.id)}
              style={{
                background: "transparent", border: 0, padding: "8px 14px", borderRadius: "9999px", flexShrink: 0,
                font: currentPath === n.id ? "700 13px var(--font-sans)" : "500 13px var(--font-sans)",
                color: currentPath === n.id ? "var(--fg-strong)" : "var(--fg-muted)", cursor: "pointer",
                transition: "background var(--dur-fast)",
              }}>{n.label}</button>
          ))}
        </nav>
      )}

      {/* Mobile drawer */}
      {isMobile && mobileMenu && (
        <div onClick={() => setMobileMenu(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.55)", zIndex: 100 }}>
          <div onClick={e => e.stopPropagation()} style={{
            position: "absolute", top: 0, left: 0, bottom: 0, width: 300, background: "var(--bg-elev-1)",
            padding: "24px 20px", display: "flex", flexDirection: "column", gap: 6,
            animation: "slideIn .2s var(--ease-out-quart)",
          }}>
            <style>{`@keyframes slideIn { from { transform: translateX(-100%) } to { transform: translateX(0) } }`}</style>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
              <img src="../../assets/allen_black_letter_logo.svg" alt="Allen" style={{ height: 24 }} />
              <button onClick={() => setMobileMenu(false)} style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--fg-strong)" }}>
                <AllenIcon name="close" size={22} />
              </button>
            </div>
            <button onClick={() => { setMobileMenu(false); user ? onNav("account") : onNav("login"); }} style={drawerBtn}>
              <AllenIcon name="person" size={20} /> {user ? user.name.split(/\s+/)[0] : "Inicia sesión"}
            </button>
            <button onClick={() => { setMobileMenu(false); user ? onNav("account", { tab: "favoritos" }) : onNav("login"); }} style={drawerBtn}>
              <AllenIcon name="favorite" size={20} /> Favoritos
            </button>
            <div style={{ height: 1, background: "var(--border-soft)", margin: "8px 0" }} />
            {navItems.map(n => (
              <button key={n.id} onClick={() => handleNav(n.id)} style={drawerBtn}>{n.label}</button>
            ))}
            <div style={{ height: 1, background: "var(--border-soft)", margin: "8px 0" }} />
            <button onClick={() => { setMobileMenu(false); onNav("seller-onboarding"); }} style={drawerBtn}>Vende en Allen</button>
            <button onClick={() => { setMobileMenu(false); onNav("ops"); }} style={drawerBtn}>Allen Ops</button>
            <button onClick={() => { setMobileMenu(false); toast("Centro de ayuda"); }} style={drawerBtn}>Ayuda</button>
          </div>
        </div>
      )}

      {/* Mobile search drawer */}
      {isMobile && mobileSearch && (
        <div style={{ position: "fixed", inset: 0, background: "var(--bg-elev-1)", zIndex: 100, padding: 16 }}>
          <form onSubmit={submitSearch} style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <button type="button" onClick={() => setMobileSearch(false)} style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--fg-strong)" }}>
              <AllenIcon name="chevron_right" size={22} style={{ transform: "rotate(180deg)" }} />
            </button>
            <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 10, background: "var(--bg-search)", border: "1px solid var(--border-strong)", borderRadius: "9999px", padding: "12px 16px" }}>
              <AllenIcon name="search" size={18} color="var(--fg-soft)" />
              <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Busca productos…"
                style={{ flex: 1, border: 0, outline: 0, background: "transparent", font: "400 14px var(--font-sans)", color: "var(--fg-strong)" }} />
            </div>
          </form>
        </div>
      )}
    </header>
  );
};
const headerBtn = {
  background: "transparent", border: 0, padding: "10px 14px", borderRadius: "9999px",
  display: "flex", alignItems: "center", gap: 8, font: "600 13px var(--font-sans)",
  color: "var(--fg-strong)", cursor: "pointer", transition: "background var(--dur-fast)",
};
const drawerBtn = {
  background: "transparent", border: 0, padding: "12px 14px", borderRadius: "var(--radius-md)",
  display: "flex", alignItems: "center", gap: 12, font: "600 14px var(--font-sans)",
  color: "var(--fg-strong)", cursor: "pointer", textAlign: "left", width: "100%",
};

// ---------------------------------------------------------------
// Footer
const AllenFooter = () => (
  <footer style={{ background: "var(--hub-black)", color: "var(--fg-on-dark)", padding: "64px 32px 24px", marginTop: 72 }}>
    <div style={{ maxWidth: "var(--container)", margin: "0 auto" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 48 }}>
        <div>
          <img src="../../assets/allen_single_white_logo.svg" alt="Allen" style={{ height: 36, marginBottom: 16 }} />
          <p style={{ color: "var(--fg-on-dark-muted)", font: "400 14px/1.6 var(--font-sans)", marginTop: 0 }}>
            Allen es el super-app mexicano. Ecommerce, food, travel y experts en una sola cuenta. <br/>Hecho en México, para México.
          </p>
        </div>
        {[
          { title: "Comprar", items: ["Lo más nuevo", "Ofertas", "Marcas destacadas", "Categorías", "Allen Prime"] },
          { title: "Soporte", items: ["Centro de ayuda", "Estado del pedido", "Devoluciones", "Métodos de pago", "Envíos y entregas"] },
          { title: "Allen", items: ["Vende en Allen", "Allen Food", "Allen Travel", "Allen Experts", "Trabaja con nosotros"] },
        ].map(col => (
          <div key={col.title}>
            <div style={{ font: "700 13px var(--font-sans)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 16 }}>{col.title}</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
              {col.items.map(i => (
                <li key={i}><a style={{ color: "var(--fg-on-dark-muted)", font: "400 14px var(--font-sans)", cursor: "pointer" }}>{i}</a></li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 48, paddingTop: 24, borderTop: "1px solid rgba(255,255,255,.12)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ color: "var(--fg-on-dark-muted)", font: "400 12px var(--font-sans)" }}>© 2026 Boreal Network · Allen Marketplace</span>
        <div style={{ display: "flex", gap: 24, color: "var(--fg-on-dark-muted)", font: "400 12px var(--font-sans)" }}>
          <a>Términos</a><a>Privacidad</a><a>Cookies</a><a>Avisos legales</a>
        </div>
      </div>
    </div>
  </footer>
);

// ---------------------------------------------------------------
// Breadcrumb
const Breadcrumb = ({ items = [] }) => (
  <nav style={{ display: "flex", alignItems: "center", gap: 6, padding: "20px 0", font: "500 13px var(--font-sans)", color: "var(--fg-muted)" }}>
    {items.map((it, i) => (
      <React.Fragment key={i}>
        <a style={{ color: i === items.length - 1 ? "var(--fg-strong)" : "var(--fg-muted)", cursor: i === items.length - 1 ? "default" : "pointer", fontWeight: i === items.length - 1 ? 600 : 500 }}>{it}</a>
        {i < items.length - 1 && <AllenIcon name="chevron_right" size={16} color="var(--fg-hint)" />}
      </React.Fragment>
    ))}
  </nav>
);

Object.assign(window, { AllenIcon, ToastHost, useToast, useTheme, useViewport, ThemeToggle, RatingStars, ProductCard, AllenHeader, AllenFooter, Breadcrumb });
