/* ============================================================
   UVD CLUB — componentes compartilhados
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---- helpers ---- */
const fmtBRL = (n) =>
  "R$ " + n.toFixed(2).replace(".", ",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");

/* ---- responsivo ---- */
function useIsMobile(bp = 760) {
  const [m, setM] = useState(typeof window !== "undefined" && window.innerWidth <= bp);
  useEffect(() => {
    const on = () => setM(window.innerWidth <= bp);
    window.addEventListener("resize", on);
    on();
    return () => window.removeEventListener("resize", on);
  }, [bp]);
  return m;
}

/* ---- placeholder de imagem ---- */
function Placeholder({ label, ratio, rounded, style, className }) {
  const st = { ...style };
  if (ratio) st.aspectRatio = ratio.replace("/", " / ");
  if (rounded) st.borderRadius = rounded;
  return (
    <div className={"ph " + (className || "")} style={st}>
      <span className="ph__tag">{label}</span>
    </div>
  );
}

/* ---- imagem real OU placeholder (decide pelo campo .src) ---- */
function Img({ src, label, ratio, rounded, pos, fit, bg, style, className }) {
  if (!src) return <Placeholder label={label} ratio={ratio} rounded={rounded} style={style} className={className} />;
  const st = { ...style };
  if (ratio) st.aspectRatio = ratio.replace("/", " / ");
  if (rounded) st.borderRadius = rounded;
  st.overflow = "hidden";
  if (bg) st.background = bg;
  return (
    <div className={className} style={st}>
      <img src={src} alt={label || ""} style={{ width: "100%", height: "100%", objectFit: fit || "cover", objectPosition: pos || "center", display: "block" }} />
    </div>
  );
}

/* ---- logo ---- */
function Logo({ height = 46, variant = "image" }) {
  if (variant === "text") {
    return (
      <span style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", lineHeight: 0.82, color: "var(--wine)" }}>
        <span style={{ fontFamily: "var(--serif-display)", fontWeight: 600, fontSize: height * 0.62, letterSpacing: "0.06em" }}>UVD</span>
        <span style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: height * 0.42, marginTop: 1 }}>Club</span>
      </span>
    );
  }
  const white = variant === "white";
  return <img src="assets/uvd-logo.png" alt="UVD Club" style={{ height, width: "auto", filter: white ? "brightness(0) invert(1)" : "none" }} />;
}

/* ---- color dot ---- */
function ColorDot({ hex, active, onClick, size = 26, title }) {
  return (
    <button
      title={title}
      onClick={onClick}
      style={{
        width: size, height: size, borderRadius: "50%", padding: 0,
        background: hex,
        border: "1px solid rgba(43,35,30,0.25)",
        outline: active ? "1.5px solid var(--wine)" : "1.5px solid transparent",
        outlineOffset: 2,
        boxShadow: hex.toLowerCase() === "#f2ecdf" || hex === "#EDE3CE" ? "inset 0 0 0 1px rgba(43,35,30,0.08)" : "none",
        transition: "outline-color .2s",
      }}
    />
  );
}

/* ---- announcement bar (marquee fininho) ---- */
function AnnouncementBar() {
  const items = ["Frete grátis acima de R$ 199", "✶", "Novidades toda semana", "✶", "Parcele em até 6x", "✶", "Reading is sexy", "✶"];
  const row = [...items, ...items];
  return (
    <div style={{ background: "var(--wine)", color: "var(--cream)", overflow: "hidden", whiteSpace: "nowrap" }}>
      <div style={{ display: "inline-flex", gap: 28, padding: "8px 0", animation: "uvd-marquee 26s linear infinite", fontFamily: "var(--sans-ui)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase" }}>
        {row.map((t, i) => (
          <span key={i} style={{ opacity: t === "✶" ? 0.5 : 0.92 }}>{t}</span>
        ))}
      </div>
    </div>
  );
}

/* ---- header ---- */
function Header({ cartCount, onCart, onHome, onNav, transparent, menuVariant = "standard" }) {
  const [scrolled, setScrolled] = useState(false);
  const isMobile = useIsMobile();
  useEffect(() => {
    const root = document.querySelector("#scrollroot") || window;
    const onScroll = () => {
      const y = root === window ? window.scrollY : root.scrollTop;
      setScrolled(y > 24);
    };
    root.addEventListener("scroll", onScroll);
    return () => root.removeEventListener("scroll", onScroll);
  }, []);

  const cats = ["Moletons & Roupas", "Acessórios", "Papelaria", "Sobre"];

  const navLink = (c, extra) => (
    <a key={c} onClick={() => onNav && onNav(c)} className="ui-label"
       style={{ fontSize: 12, color: "var(--ink)", cursor: "pointer", paddingBottom: 2, borderBottom: "1px solid transparent", transition: "border-color .2s", ...extra }}
       onMouseEnter={(e) => (e.currentTarget.style.borderColor = "var(--wine)")}
       onMouseLeave={(e) => (e.currentTarget.style.borderColor = "transparent")}>
      {c}
    </a>
  );

  const actions = (
    <div style={{ display: "flex", gap: isMobile ? 0 : 22, justifyContent: "flex-end", alignItems: "center" }} className="ui-label">
      {!isMobile && <span style={{ fontSize: 12, cursor: "pointer", opacity: 0.85 }}>Buscar</span>}
      {!isMobile && <span style={{ fontSize: 12, cursor: "pointer", opacity: 0.85 }}>Conta</span>}
      <button onClick={onCart} aria-label="Sacola" style={{ background: "none", border: "none", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink)", display: "flex", alignItems: "center", gap: 7 }}>
        {!isMobile && "Sacola"}
        <span style={{ minWidth: 20, height: 20, borderRadius: 99, background: "var(--wine)", color: "var(--cream)", fontSize: 11, display: "inline-flex", alignItems: "center", justifyContent: "center", padding: "0 6px" }}>{cartCount}</span>
      </button>
    </div>
  );

  const headerBase = {
    position: "sticky", top: 0, zIndex: 40,
    background: scrolled ? "rgba(250,245,236,0.92)" : "var(--cream)",
    backdropFilter: scrolled ? "saturate(140%) blur(8px)" : "none",
    borderBottom: "1px solid var(--line)",
    transition: "background .3s",
  };

  /* ---- OPÇÃO 01 — cabeçalho editorial: logo à esquerda + nav ao lado ---- */
  if (menuVariant === "editorial" && !isMobile) {
    return (
      <header style={headerBase}>
        <div className="wrap" style={{ display: "flex", alignItems: "center", gap: 44, height: 84 }}>
          <a onClick={onHome} style={{ cursor: "pointer", display: "flex", alignItems: "center" }}>
            <Logo height={56} />
          </a>
          <nav style={{ display: "flex", gap: 32 }} className="ui-label">
            {cats.map((c) => navLink(c, { letterSpacing: "0.16em" }))}
          </nav>
          <div style={{ marginLeft: "auto" }}>
            {actions}
          </div>
        </div>
      </header>
    );
  }

  /* ---- OPÇÕES 02 & 03 / mobile — cabeçalho padrão em 3 colunas ---- */
  return (
    <header style={headerBase}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", height: isMobile ? 60 : 76, padding: isMobile ? "0 18px" : undefined }}>
        {/* esquerda: nav (desktop) / menu (mobile) */}
        {isMobile ? (
          <button aria-label="Menu" onClick={() => onNav && onNav("Moletons & Roupas")} style={{ background: "none", border: "none", display: "inline-flex", flexDirection: "column", gap: 5, padding: 4, justifySelf: "start" }}>
            {[0, 1, 2].map((k) => <span key={k} style={{ display: "block", width: 22, height: 1.5, background: "var(--ink)" }} />)}
          </button>
        ) : (
          <nav style={{ display: "flex", gap: 26 }} className="ui-label">
            {cats.map((c) => navLink(c))}
          </nav>
        )}
        {/* logo centro */}
        <a onClick={onHome} style={{ cursor: "pointer", display: "flex", justifyContent: "center" }}>
          <Logo height={isMobile ? 40 : 56} />
        </a>
        {/* ações direita */}
        {actions}
      </div>
    </header>
  );
}

/* ---- product card ---- */
function ProductCard({ p, onOpen, onAdd, variant = "editorial" }) {
  const [hover, setHover] = useState(false);
  const club = variant === "club";
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ cursor: "pointer", display: "flex", flexDirection: "column" }}
      onClick={() => onOpen(p.id)}
    >
      <div style={{ position: "relative" }}>
        <Img
          src={p.gallery[0].src}
          label={p.gallery[0].ph}
          pos={p.gallery[0].pos}
          ratio="3/4"
          rounded={club ? "6px" : "0"}
          style={{ transition: "filter .3s", filter: hover ? "brightness(0.97)" : "none" }}
        />
        {p.tag && (
          <span style={{
            position: "absolute", top: 12, left: 12,
            background: club ? "var(--wine)" : "var(--cream)",
            color: club ? "var(--cream)" : "var(--wine)",
            border: club ? "none" : "1px solid var(--wine)",
            fontFamily: "var(--sans-ui)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
            padding: "5px 10px", borderRadius: club ? 99 : 0,
          }}>{p.tag}</span>
        )}
        {/* quick add */}
        <button
          onClick={(e) => { e.stopPropagation(); onAdd(p); }}
          className="ui-label"
          style={{
            position: "absolute", left: 12, right: 12, bottom: 12,
            opacity: hover ? 1 : 0, transform: hover ? "translateY(0)" : "translateY(8px)",
            transition: "all .28s ease",
            background: "var(--cream)", color: "var(--ink)", border: "1px solid var(--ink)",
            fontSize: 11, padding: "11px", borderRadius: club ? 99 : 0,
          }}
        >+ Adição rápida</button>
      </div>
      <div style={{ paddingTop: 14, display: "flex", flexDirection: "column", gap: 4 }}>
        <span className="kicker" style={{ fontSize: 10 }}>{p.cat}</span>
        <h3 style={{ fontSize: 21, fontWeight: 500 }}>{p.name}</h3>
        <div style={{ display: "flex", alignItems: "baseline", gap: 9, marginTop: 2 }}>
          <span style={{ fontFamily: "var(--sans-ui)", fontSize: 14, color: "var(--wine)" }}>{fmtBRL(p.price)}</span>
          {p.compareAt && <span style={{ fontFamily: "var(--sans-ui)", fontSize: 12, color: "var(--muted)", textDecoration: "line-through" }}>{fmtBRL(p.compareAt)}</span>}
        </div>
        <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
          {p.colors.map((c) => (
            <span key={c.name} title={c.name} style={{ width: 13, height: 13, borderRadius: "50%", background: c.hex, border: "1px solid rgba(43,35,30,0.2)" }} />
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---- mini cart ---- */
function MiniCart({ open, items, onClose, onRemove, onOpenProduct }) {
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  return (
    <>
      <div onClick={onClose} style={{
        position: "fixed", inset: 0, background: "rgba(43,35,30,0.4)", zIndex: 90,
        opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity .3s",
      }} />
      <aside style={{
        position: "fixed", top: 0, right: 0, height: "100%", width: "min(420px, 92vw)", zIndex: 91,
        background: "var(--cream)", borderLeft: "1px solid var(--line)",
        transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform .35s cubic-bezier(.2,.7,.2,1)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "22px 26px", borderBottom: "1px solid var(--line)" }}>
          <h3 style={{ fontSize: 24 }}>Sua sacola <span style={{ fontFamily: "var(--sans-ui)", fontSize: 13, color: "var(--muted)" }}>({items.reduce((s, i) => s + i.qty, 0)})</span></h3>
          <button onClick={onClose} style={{ background: "none", border: "none", fontSize: 22, color: "var(--ink)", lineHeight: 1 }}>×</button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "8px 26px" }}>
          {items.length === 0 && (
            <div style={{ textAlign: "center", color: "var(--muted)", padding: "60px 0", fontStyle: "italic" }}>
              Sua sacola está vazia.<br />Bora encher de coisa fofa.
            </div>
          )}
          {items.map((it) => (
            <div key={it.key} style={{ display: "grid", gridTemplateColumns: "64px 1fr auto", gap: 14, padding: "18px 0", borderBottom: "1px solid var(--line)" }}>
              <Img src={it.img} label="FOTO" ratio="3/4" style={{ fontSize: 8 }} />
              <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
                <span onClick={() => { onOpenProduct(it.id); onClose(); }} style={{ fontFamily: "var(--serif-display)", fontSize: 18, cursor: "pointer" }}>{it.name}</span>
                <span style={{ fontFamily: "var(--sans-ui)", fontSize: 11, color: "var(--muted)", letterSpacing: "0.04em" }}>{it.color} · {it.size}</span>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 4 }}>
                  <span style={{ fontFamily: "var(--sans-ui)", fontSize: 12 }}>Qtd {it.qty}</span>
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", justifyContent: "space-between" }}>
                <span style={{ fontFamily: "var(--sans-ui)", fontSize: 13, color: "var(--wine)" }}>{fmtBRL(it.price * it.qty)}</span>
                <button onClick={() => onRemove(it.key)} style={{ background: "none", border: "none", fontFamily: "var(--sans-ui)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", textDecoration: "underline" }}>Remover</button>
              </div>
            </div>
          ))}
        </div>

        {items.length > 0 && (
          <div style={{ padding: "20px 26px", borderTop: "1px solid var(--line)", background: "var(--cream-2)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4, fontFamily: "var(--sans-ui)", fontSize: 14 }}>
              <span>Subtotal</span><span style={{ color: "var(--wine)" }}>{fmtBRL(subtotal)}</span>
            </div>
            <p style={{ fontFamily: "var(--sans-ui)", fontSize: 11, color: "var(--muted)", margin: "0 0 14px" }}>Frete e impostos calculados no checkout.</p>
            <button className="btn" style={{ width: "100%" }}>Finalizar compra</button>
            <button onClick={onClose} className="btn btn--ghost" style={{ width: "100%", marginTop: 8 }}>Continuar comprando</button>
          </div>
        )}
      </aside>
    </>
  );
}

/* ---- footer ---- */
function Footer() {
  const isMobile = useIsMobile();
  const cols = [
    { h: "Loja", items: ["Moletons & Roupas", "Acessórios", "Papelaria", "Novidades", "Promoções"] },
    { h: "Ajuda", items: ["Trocas e devoluções", "Tabela de medidas", "Envio e prazos", "Fale conosco"] },
    { h: "UVD Club", items: ["Sobre a marca", "Programa de embaixadoras", "Instagram", "Termos"] },
  ];
  return (
    <footer style={{ background: "var(--wine-deep)", color: "var(--cream)", marginTop: 0 }}>
      <div className="wrap" style={{ padding: isMobile ? "48px 22px 26px" : "64px 32px 30px" }}>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr 1fr 1fr", gap: isMobile ? 34 : 40 }}>
          <div>
            <Logo height={72} variant="white" />
            <p style={{ maxWidth: 260, marginTop: 18, fontSize: 16, opacity: 0.82, fontStyle: "italic" }}>
              Para garotas que estudam, leem e sabem que inteligência é o novo charme.
            </p>
            <form onSubmit={(e) => e.preventDefault()} style={{ display: "flex", marginTop: 22, maxWidth: 300, borderBottom: "1px solid rgba(250,245,236,0.4)" }}>
              <input placeholder="seu@email.com" style={{ flex: 1, background: "none", border: "none", color: "var(--cream)", fontFamily: "var(--sans-ui)", fontSize: 13, padding: "8px 0", outline: "none" }} />
              <button className="ui-label" style={{ background: "none", border: "none", color: "var(--cream)", fontSize: 12 }}>Assinar →</button>
            </form>
          </div>
          {cols.map((c) => (
            <div key={c.h}>
              <h4 className="ui-label" style={{ fontFamily: "var(--sans-ui)", fontSize: 12, opacity: 0.7, marginBottom: 16 }}>{c.h}</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 11 }}>
                {c.items.map((i) => <li key={i} style={{ fontSize: 16, opacity: 0.9, cursor: "pointer" }}>{i}</li>)}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", flexDirection: isMobile ? "column" : "row", gap: isMobile ? 8 : 0, justifyContent: "space-between", marginTop: isMobile ? 36 : 50, paddingTop: 22, borderTop: "1px solid rgba(250,245,236,0.18)", fontFamily: "var(--sans-ui)", fontSize: 11, letterSpacing: "0.06em", opacity: 0.7 }}>
          <span>© 2026 UVD Club — Protótipo de demonstração</span>
          <span>Feito com café e madrugadas ✶</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { fmtBRL, useIsMobile, Placeholder, Img, Logo, ColorDot, AnnouncementBar, Header, ProductCard, MiniCart, Footer });
