// Componentes principales: Topbar, ProductCard, Hero, Tabbar, etc.

const { useState, useEffect, useRef } = React;

// ====================== TOPBAR ======================
function Topbar({ cartCount, wishCount, activeTab, onNavigate, onOpenSearch, onOpenCart, onOpenWish, transparent }) {
  const navItems = [
    { id: "home", label: "Inicio" },
    { id: "shop", label: "Tienda" },
    { id: "wish", label: "Deseos" },
    { id: "account", label: "Cuenta" },
  ];
  return (
    <header className={"topbar" + (transparent ? " transparent" : "")}>
      <div className="brand-mark">
        <img className="brand-logo-img" src="assets/brand/logo-principal.svg" alt="mima edit" />
      </div>
      <nav className="desktop-nav" aria-label="Navegacion principal">
        {navItems.map(item => (
          <button
            key={item.id}
            className={activeTab === item.id ? "active" : ""}
            aria-current={activeTab === item.id ? "page" : undefined}
            onClick={() => onNavigate(item.id)}
          >
            {item.label}
          </button>
        ))}
      </nav>
      <div className="icons">
        <button className="icon-btn" onClick={onOpenSearch} aria-label="Buscar"><I.Search /></button>
        <button className="icon-btn" onClick={onOpenWish} aria-label="Favoritos">
          <I.Heart />
          {wishCount > 0 && <span className="badge">{wishCount}</span>}
        </button>
        <button className="icon-btn" id="cart-anchor" onClick={onOpenCart} aria-label="Carrito">
          <I.Bag />
          {cartCount > 0 && <span className="badge">{cartCount}</span>}
        </button>
      </div>
    </header>
  );
}

// ====================== TABBAR ======================
function Tabbar({ active, onChange }) {
  const tabs = [
    { id: "home", label: "Inicio", icon: I.Home },
    { id: "shop", label: "Tienda", icon: I.Compass },
    { id: "wish", label: "Deseos", icon: I.Heart },
    { id: "account", label: "Cuenta", icon: I.User },
  ];
  return (
    <nav className="tabbar">
      {tabs.map(t => {
        const Icon = t.icon;
        return (
          <button
            key={t.id}
            className={"tab" + (active === t.id ? " active" : "")}
            onClick={() => onChange(t.id)}
          >
            <Icon size={20} />
            <span>{t.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ====================== PRODUCT CARD ======================
function ProductCard({ product, currency, rates, onOpen, onAdd, onFav, isFav }) {
  const cardRef = useRef(null);
  const handleAdd = (e) => {
    e.stopPropagation();
    if (product.stock === 0) return;
    onAdd(product, cardRef.current);
  };
  const out = product.stock === 0;
  const low = product.stock > 0 && product.stock < 10;
  return (
    <div className="product-card" onClick={() => onOpen(product)} ref={cardRef}>
      <div className="pc-img">
        <div className="pc-img-inner" style={productTones(product)} />
        {product.isNew && <span className="pc-flag new">Nuevo</span>}
        {out && <span className="pc-flag out">Sin stock</span>}
        {!product.isNew && !out && product.compareAt && <span className="pc-flag">Oferta</span>}
        <button className={"pc-fav" + (isFav ? " active" : "")} onClick={(e) => { e.stopPropagation(); onFav(product.id); }} aria-label="Favorito">
          <I.Heart size={15} fill={isFav ? "currentColor" : "none"} />
        </button>
        <button className="pc-add" disabled={out} onClick={handleAdd} aria-label="Agregar"><I.Plus /></button>
      </div>
      <div className="pc-meta">
        <div className="pc-name">{product.name}</div>
        <div className="pc-tagline">{product.tagline}</div>
        <div className="pc-price-row">
          <span className="pc-price">{formatPrice(product.price, currency, rates)}</span>
          {product.compareAt && <span className="pc-compare">{formatPrice(product.compareAt, currency, rates)}</span>}
        </div>
      </div>
    </div>
  );
}

// ====================== HERO ======================
function Hero({ variant, onCta, brand }) {
  const heroRef = useRef(null);
  // parallax
  useEffect(() => {
    const scrollEl = heroRef.current?.closest(".body-scroll");
    if (!scrollEl) return;
    const onScroll = () => {
      const bg = heroRef.current?.querySelector(".hero-bg");
      if (bg) bg.style.transform = `translateY(${scrollEl.scrollTop * 0.3}px) scale(1.05)`;
    };
    scrollEl.addEventListener("scroll", onScroll, { passive: true });
    return () => scrollEl.removeEventListener("scroll", onScroll);
  }, []);

  if (variant === "editorial") {
    return (
      <div className="hero variant-editorial" ref={heroRef}>
        <div className="hero-content" style={{ gap: 8 }}>
          <span className="eyebrow">Belleza elegida con cuidado</span>
          <h1>El ritual<br /><em>vuelve</em> a casa.</h1>
          <p className="hero-sub">Seleccion cuidada de belleza para rutinas simples, calidas y confiables.</p>
        </div>
        <div className="hero-img" />
        <div className="hero-cta" style={{ marginTop: 0 }}>
          <button className="btn btn-sage btn-lg" onClick={onCta}>Descubrir colección</button>
        </div>
      </div>
    );
  }
  if (variant === "mono") {
    return (
      <div className="hero variant-mono" ref={heroRef}>
        <div className="hero-content">
          <img src="assets/brand/isotipo.svg" alt="" style={{ width: 96, height: 96, marginBottom: 16 }} />
          <span className="eyebrow" style={{ color: "var(--ink-3)" }}>mima edit</span>
          <h1>Pequeños rituales,<br />grandes cambios.</h1>
          <p className="hero-sub">Una boutique digital con productos seleccionados a mano.</p>
          <div className="hero-cta">
            <button className="btn btn-primary btn-lg" onClick={onCta}>Ver tienda</button>
          </div>
        </div>
      </div>
    );
  }
  // default: warm gradient hero
  return (
    <div className="hero" ref={heroRef}>
      <div className="hero-bg" />
      <Leaf size={120} rot={-20} style={{ position: "absolute", top: -20, right: -20, opacity: 0.18 }} color="var(--cream)" />
      <Leaf size={90} rot={140} style={{ position: "absolute", bottom: 100, left: -10, opacity: 0.14 }} color="var(--cream)" />
      <div className="hero-content">
        <span className="eyebrow">Belleza elegida con cuidado</span>
        <h1>Aromas que<br /><em>te abrazan</em>.</h1>
        <p className="hero-sub">Perfumeria y cuidado personal con productos seleccionados de Natura, Avon y marcas elegidas.</p>
        <div className="hero-cta">
          <button className="btn btn-cream btn-lg" onClick={onCta}>Explorar tienda</button>
        </div>
      </div>
    </div>
  );
}

// ====================== CATEGORÍAS RAIL ======================
function CategoryRail({ cats, active, onChange }) {
  return (
    <div className="cat-rail">
      <button className={"cat-chip" + (active === "all" ? " active" : "")} onClick={() => onChange("all")}>
        <span className="dot" /> Todo
      </button>
      {cats.map(c => (
        <button key={c.id} className={"cat-chip" + (active === c.id ? " active" : "")} onClick={() => onChange(c.id)}>
          <span className="dot" /> {c.label}
        </button>
      ))}
    </div>
  );
}

// ====================== BANNER CARRUSEL ======================
function BannerRail() {
  const banners = [
    { cls: "b1", eyebrow: "Hasta 30% off", title: "Liquidación de invierno" },
    { cls: "b2", eyebrow: "Edición limitada", title: "Sérum Vit. C, ahora con niacinamida" },
    { cls: "b3", eyebrow: "Envío gratis", title: "En compras desde $ 35.000" },
  ];
  return (
    <div className="banner-rail">
      {banners.map((b, i) => (
        <div className={"banner-card " + b.cls} key={i}>
          <span className="eyebrow">{b.eyebrow}</span>
          <h3>{b.title}</h3>
        </div>
      ))}
    </div>
  );
}

// ====================== LOYALTY CARD ======================
function LoyaltyCard({ points, target = 1000 }) {
  const pct = Math.min(100, Math.round((points / target) * 100));
  return (
    <div className="loyalty">
      <div className="l-eyebrow">mima edit - beneficios</div>
      <div className="points">{points}<small>/ {target} puntos</small></div>
      <div className="progress"><div className="bar" style={{ width: pct + "%" }} /></div>
      <div className="l-foot">Te faltan {target - points} puntos para tu próxima recompensa.</div>
    </div>
  );
}

// ====================== TOAST ======================
function Toast({ message, onClose }) {
  useEffect(() => {
    const t = setTimeout(onClose, 2200);
    return () => clearTimeout(t);
  }, [message, onClose]);
  if (!message) return null;
  return (
    <div className="toast">
      <I.Check size={14} />
      <span>{message}</span>
    </div>
  );
}

Object.assign(window, { Topbar, Tabbar, ProductCard, Hero, CategoryRail, BannerRail, LoyaltyCard, Toast });
