/* ============================================================
   UVD CLUB — Home (3 direções: Atelier · Club · Library)
   ============================================================ */

/* ---- slides do hero ---- */
const HERO_SLIDES = [
  { kicker: "Bem-vinda ao clube", title: "Hot Girls\nStudy ", emph: "Hard.", sub: "Moda, papelaria e acessórios para a sua era mais inteligente.", cta: "Explorar a coleção", src: "assets/hero-welcome.jpg", pos: "right center", mpos: "74% 14%", panel: "cream", target: "Moletons & Roupas" },
  { kicker: "Acessórios", title: "Reading\nis sexy.", sub: "A tote que virou ícone. Cabe livro, notebook e personalidade.", cta: "Ver a tote bag", src: "assets/tote-reading.jpg", pos: "center top", mpos: "58% 12%", panel: "cream", target: "Acessórios" },
  { kicker: "Best-seller", title: "Aconchego\npra estudar", sub: "O moletom-hino do clube, em bordado vinho.", cta: "Comprar moletom", src: "assets/moletom-hoodie.jpg", pos: "center top", mpos: "center 8%", panel: "cream", target: "Moletons & Roupas" },
];

/* ---- carrossel hero ---- */
function HeroCarousel({ framed, onNav }) {
  const isMobile = useIsMobile();
  const [i, setI] = useState(0);
  const n = HERO_SLIDES.length;
  const timer = useRef(null);
  const start = () => { stop(); timer.current = setInterval(() => setI((x) => (x + 1) % n), 6000); };
  const stop = () => timer.current && clearInterval(timer.current);
  useEffect(() => { start(); return stop; }, []);
  const go = (x) => { setI((x + n) % n); start(); };

  /* swipe (mobile) */
  const touch = useRef(null);
  const onTouchStart = (e) => { touch.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touch.current == null) return;
    const dx = e.changedTouches[0].clientX - touch.current;
    if (Math.abs(dx) > 44) go(dx < 0 ? i + 1 : i - 1);
    touch.current = null;
  };

  return (
    <section
      style={{ padding: framed ? (isMobile ? "14px 14px 0" : "26px 26px 0") : 0 }}
      onMouseEnter={stop} onMouseLeave={start}
    >
      <div
        style={{ position: "relative", overflow: "hidden", borderRadius: framed ? "4px" : 0, border: framed ? "1px solid var(--line)" : "none" }}
        onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}
      >
        <div style={{ position: "relative", height: isMobile ? "86vh" : (framed ? "72vh" : "80vh"), minHeight: isMobile ? 540 : 500 }}>
          {HERO_SLIDES.map((sl, idx) => {
            const active = idx === i;
            return (
              <div key={idx} style={{ position: "absolute", inset: 0, opacity: active ? 1 : 0, transition: "opacity .9s ease", pointerEvents: active ? "auto" : "none" }}>
                {isMobile ? (
                  /* MOBILE — foto contida no topo (menos zoom = nítida) + painel creme com o texto embaixo */
                  <div style={{ position: "absolute", inset: 0, background: "var(--cream)", display: "flex", flexDirection: "column" }}>
                    <div style={{ position: "relative", flex: "0 0 48%", overflow: "hidden" }}>
                      <img src={sl.src} alt={sl.kicker} style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: sl.mpos || "center top" }} />
                      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: "32%", pointerEvents: "none", background: "linear-gradient(to top, var(--cream) 0%, rgba(250,245,236,0.6) 45%, transparent 100%)" }} />
                    </div>
                    {active && (
                      <div className="fade-in" style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", padding: "4px 24px 40px" }}>
                        <span className="kicker" style={{ color: "var(--wine)" }}>{sl.kicker}</span>
                        <h1 style={{ fontSize: "clamp(38px,11vw,54px)", whiteSpace: "pre-line", margin: "8px 0 0", fontWeight: 500, color: "var(--wine)", lineHeight: 1.0 }}>{sl.title}{sl.emph && <em style={{ fontStyle: "italic" }}>{sl.emph}</em>}</h1>
                        <p style={{ fontSize: 15.5, margin: "12px 0 18px", color: "var(--ink)", opacity: 0.9, maxWidth: "33ch", lineHeight: 1.45 }}>{sl.sub}</p>
                        <button className="btn" style={{ display: "inline-flex", alignSelf: "flex-start", alignItems: "center", gap: 9 }} onClick={() => onNav(sl.target)}>{sl.cta}<span aria-hidden="true" style={{ fontSize: 15, lineHeight: 1 }}>→</span></button>
                      </div>
                    )}
                  </div>
                ) : (
                  /* DESKTOP — split editorial, modelo 100% visível */
                  <div style={{ position: "absolute", inset: 0, display: "grid", gridTemplateColumns: "1fr 1fr", background: "var(--cream)" }}>
                    <div style={{ background: "var(--cream)", color: "var(--ink)", display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 clamp(36px,5vw,92px)", position: "relative", zIndex: 2 }}>
                      {active && (
                        <div className="fade-in" style={{ maxWidth: 460 }}>
                          <span className="kicker" style={{ color: "var(--wine)" }}>{sl.kicker}</span>
                          <h1 style={{ fontSize: "clamp(44px,5.6vw,82px)", whiteSpace: "pre-line", margin: "16px 0 0", fontWeight: 500, color: "var(--wine)" }}>{sl.title}{sl.emph && <em style={{ fontStyle: "italic" }}>{sl.emph}</em>}</h1>
                          <p style={{ fontSize: 18, maxWidth: 380, margin: "20px 0 28px", opacity: 0.85 }}>{sl.sub}</p>
                          <button className="btn" style={{ display: "inline-flex", alignItems: "center", gap: 10 }} onClick={() => onNav(sl.target)}>{sl.cta}<span aria-hidden="true" style={{ fontSize: 15, lineHeight: 1, transform: "translateY(0.5px)" }}>→</span></button>
                        </div>
                      )}
                    </div>
                    <div style={{ position: "relative", overflow: "hidden" }}>
                      <img src={sl.src} alt={sl.kicker} style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: sl.pos || "center top" }} />
                      <div style={{ position: "absolute", inset: 0, pointerEvents: "none", background: "linear-gradient(to right, var(--cream) 0%, rgba(250,245,236,0.9) 9%, rgba(250,245,236,0.45) 26%, rgba(250,245,236,0.14) 42%, transparent 56%)" }} />
                    </div>
                  </div>
                )}
              </div>
            );
          })}

          {/* setas — só desktop */}
          {!isMobile && <button onClick={() => go(i - 1)} style={navArrow("left")}>‹</button>}
          {!isMobile && <button onClick={() => go(i + 1)} style={navArrow("right")}>›</button>}
          {/* dots */}
          <div style={{ position: "absolute", bottom: isMobile ? "auto" : 20, top: isMobile ? 18 : "auto", left: "50%", transform: "translateX(-50%)", display: "flex", gap: 10, zIndex: 5 }}>
            {HERO_SLIDES.map((_, idx) => (
              <button key={idx} onClick={() => go(idx)} style={{ width: idx === i ? 28 : 9, height: 9, borderRadius: 99, background: idx === i ? "var(--wine)" : "rgba(124,29,43,0.32)", border: "none", transition: "width .3s, background .3s" }} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
const navArrow = (side) => ({
  position: "absolute", top: "50%", [side]: 18, transform: "translateY(-50%)", zIndex: 6,
  width: 48, height: 48, borderRadius: "50%", background: "rgba(250,245,236,0.9)",
  border: "none", color: "var(--wine)", fontSize: 26, lineHeight: 1, display: "flex", alignItems: "center", justifyContent: "center",
  boxShadow: "0 4px 16px rgba(43,35,30,0.15)",
});

/* ---- grid de produtos ---- */
function ProductGrid({ products, onOpen, onAdd, variant, title, kicker, cols = 4, limit }) {
  const isMobile = useIsMobile();
  const list = limit ? products.slice(0, limit) : products;
  const effCols = isMobile ? 2 : cols;
  return (
    <section className="wrap" style={{ padding: isMobile ? "52px 20px" : "84px 32px" }}>
      {title && (
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: isMobile ? 24 : 38, gap: 16 }}>
          <div>
            {kicker && <span className="kicker">{kicker}</span>}
            <h2 style={{ fontSize: isMobile ? "clamp(28px,8vw,38px)" : "clamp(32px,4vw,52px)", marginTop: 8 }}>{title}</h2>
          </div>
          <a className="ui-label" style={{ fontSize: isMobile ? 11 : 12, borderBottom: "1px solid var(--wine)", paddingBottom: 3, color: "var(--wine)", whiteSpace: "nowrap" }}>Ver tudo →</a>
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${effCols}, 1fr)`, gap: isMobile ? 14 : 28, rowGap: isMobile ? 30 : 28 }}>
        {list.map((p) => <ProductCard key={p.id} p={p} onOpen={onOpen} onAdd={onAdd} variant={variant} />)}
      </div>
    </section>
  );
}

/* ---- trio de categorias ---- */
function CategoryTrio({ onNav }) {
  const isMobile = useIsMobile();
  const cats = [
    { name: "Moletons & Roupas", ph: "FOTO — peça vestida", src: "assets/moletom-hoodie.jpg", pos: "center 18%" },
    { name: "Acessórios", ph: "FOTO — bolsa / óculos", src: "assets/tote-reading.jpg", pos: "75% center" },
    { name: "Papelaria", ph: "FOTO — cadernos / agenda", src: "assets/caderno-smart-girl.jpg", pos: "center" },
  ];
  return (
    <section className="wrap" style={{ padding: isMobile ? "8px 20px 52px" : "20px 32px 84px" }}>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3,1fr)", gap: isMobile ? 14 : 22 }}>
        {cats.map((c) => (
          <div key={c.name} onClick={() => onNav && onNav(c.name)} style={{ position: "relative", cursor: "pointer", overflow: "hidden" }}>
            <Img src={c.src} label={c.ph} pos={c.pos} ratio={isMobile ? "16/10" : "4/5"} />
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(43,35,30,0.45), transparent 55%)", display: "flex", alignItems: "flex-end", padding: isMobile ? 20 : 24 }}>
              <span style={{ color: "var(--cream)", fontFamily: "var(--serif-display)", fontSize: isMobile ? 23 : 28, letterSpacing: isMobile ? "-0.01em" : 0 }}>{c.name} <span style={{ fontSize: 18 }}>→</span></span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---- marquee grande (club) ---- */
function BigMarquee({ phrases }) {
  const isMobile = useIsMobile();
  const row = [...phrases, ...phrases];
  return (
    <div style={{ background: "var(--wine)", color: "var(--cream)", overflow: "hidden", padding: isMobile ? "14px 0" : "20px 0", whiteSpace: "nowrap" }}>
      <div style={{ display: "inline-flex", gap: isMobile ? 26 : 40, animation: "uvd-marquee 30s linear infinite" }}>
        {row.map((p, i) => (
          <span key={i} style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: isMobile ? 26 : 40, opacity: 0.95 }}>
            {p} <span style={{ fontStyle: "normal", margin: "0 6px", opacity: 0.5 }}>✶</span>
          </span>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   DIREÇÃO A — ATELIER (editorial elegante)
   ============================================================ */
function HomeAtelier({ products, phrases, onOpen, onAdd, onNav }) {
  const isMobile = useIsMobile();
  const featured = products.find((p) => p.id === "moletom-hot-girls");
  return (
    <div>
      <HeroCarousel onNav={onNav} />

      {/* manifesto linha */}
      <section className="wrap" style={{ padding: isMobile ? "56px 22px" : "90px 32px", textAlign: "center", maxWidth: 900 }}>
        <span className="kicker">O clube</span>
        <p style={{ fontSize: isMobile ? "clamp(23px,6.4vw,30px)" : "clamp(26px,3.2vw,40px)", lineHeight: 1.28, marginTop: 18, fontFamily: "var(--serif-display)" }}>
          Peças pensadas para garotas que transformam a rotina de estudos em estilo de vida. <span style={{ color: "var(--wine)", fontStyle: "italic" }}>Inteligência é o novo charme.</span>
        </p>
      </section>

      {/* feature editorial assimétrico */}
      {featured && (
        <section className="wrap" style={{ padding: isMobile ? "0 22px 56px" : "0 32px 90px", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.15fr 0.85fr", gap: isMobile ? 26 : 48, alignItems: "center" }}>
          <Img src={featured.gallery[0].src} label={featured.gallery[0].ph} pos={featured.gallery[0].pos} ratio={isMobile ? "4/3" : "4/5"} />
          <div>
            <span className="kicker">Destaque</span>
            <h2 style={{ fontSize: isMobile ? "clamp(30px,8vw,40px)" : "clamp(38px,4.5vw,62px)", margin: "12px 0 18px" }}>{featured.name}</h2>
            <p style={{ fontSize: isMobile ? 16 : 19, color: "var(--ink)", maxWidth: 380, marginBottom: 22 }}>{featured.blurb}</p>
            <div style={{ display: "flex", alignItems: "center", gap: 20, marginBottom: 28 }}>
              <span style={{ fontFamily: "var(--sans-ui)", fontSize: 18, color: "var(--wine)" }}>{fmtBRL(featured.price)}</span>
              <div style={{ display: "flex", gap: 7 }}>
                {featured.colors.map((c) => <span key={c.name} title={c.name} style={{ width: 16, height: 16, borderRadius: "50%", background: c.hex, border: "1px solid rgba(43,35,30,0.2)" }} />)}
              </div>
            </div>
            <button className="btn" onClick={() => onOpen(featured.id)}>Ver produto</button>
          </div>
        </section>
      )}

      <hr className="rule" style={{ margin: isMobile ? "0 20px" : "0 32px" }} />
      <ProductGrid products={products} onOpen={onOpen} onAdd={onAdd} variant="editorial" title="Mais desejados" kicker="Seleção da semana" cols={4} limit={8} />
      <CategoryTrio onNav={onNav} />
    </div>
  );
}

/* ============================================================
   DIREÇÃO B — CLUB (jovem, comunidade, frases)
   ============================================================ */
function HomeClub({ products, phrases, onOpen, onAdd, onNav }) {
  const isMobile = useIsMobile();
  return (
    <div>
      {/* hero = mesmo carrossel do Atelier (pedido do cliente) */}
      <HeroCarousel onNav={onNav} />

      <BigMarquee phrases={phrases} />

      <ProductGrid products={products} onOpen={onOpen} onAdd={onAdd} variant="club" title="O drop da semana" kicker="Acabou de chegar" cols={4} limit={8} />

      {/* faixa frases-chips */}
      <section className="wrap" style={{ padding: isMobile ? "0 22px 52px" : "0 32px 80px", display: "flex", flexWrap: "wrap", gap: isMobile ? 9 : 12, justifyContent: "center" }}>
        {phrases.map((p) => (
          <span key={p} style={{ border: "1px solid var(--wine)", color: "var(--wine)", borderRadius: 99, padding: isMobile ? "8px 15px" : "10px 20px", fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: isMobile ? 17 : 22 }}>{p}</span>
        ))}
      </section>

      {/* trio de categorias (igual ao fim do Atelier) */}
      <CategoryTrio onNav={onNav} />

      {/* comunidade / instagram */}
      <section style={{ background: "var(--cream-2)", padding: isMobile ? "56px 0" : "80px 0" }}>
        <div className="wrap" style={{ textAlign: "center" }}>
          <span className="kicker">Comunidade</span>
          <h2 style={{ fontSize: isMobile ? "clamp(30px,9vw,40px)" : "clamp(34px,4.5vw,56px)", margin: "10px 0 6px" }}>@uvdclub</h2>
          <p style={{ color: "var(--muted)", marginBottom: 36 }}>Marque suas fotos e apareça aqui ✶</p>
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(3,1fr)" : "repeat(5,1fr)", gap: isMobile ? 8 : 12 }}>
            {Array.from({ length: isMobile ? 9 : 10 }).map((_, i) => (
              <a key={i} href="https://www.instagram.com/uvdclub" target="_blank" rel="noreferrer" style={{ position: "relative", display: "block", overflow: "hidden", borderRadius: 6 }} className="ig-tile">
                <Img src={`assets/ig/post-${i + 1}.jpg`} label={`POST IG #${i + 1}`} ratio="3/4" rounded="6px" />
              </a>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ============================================================
   DIREÇÃO C — LIBRARY (híbrido aconchegante / editorial cozy)
   ============================================================ */
function HomeLibrary({ products, phrases, onOpen, onAdd, onNav }) {
  const isMobile = useIsMobile();
  return (
    <div>
      {/* título acima do carrossel emoldurado */}
      <section className="wrap" style={{ padding: isMobile ? "26px 22px 4px" : "40px 32px 6px", textAlign: "center" }}>
        <span className="kicker">UVD Club · Coleção 2026</span>
        <h1 style={{ fontSize: isMobile ? "clamp(34px,9.5vw,52px)" : "clamp(40px,5.5vw,80px)", margin: "12px 0 0" }}>Horas de biblioteca,<br /><span style={{ fontStyle: "italic", color: "var(--wine)" }}>vestidas com carinho.</span></h1>
      </section>
      <HeroCarousel framed onNav={onNav} />

      {/* manifesto com capitular */}
      <section className="wrap" style={{ padding: isMobile ? "56px 22px" : "90px 32px", maxWidth: 820 }}>
        <p style={{ fontSize: isMobile ? 18 : 23, lineHeight: 1.6 }}>
          <span style={{ float: "left", fontFamily: "var(--serif-display)", fontSize: isMobile ? 64 : 88, lineHeight: 0.72, color: "var(--wine)", marginRight: 14, marginTop: 8 }}>O</span>
          UVD Club nasceu da ideia de que estudar pode ser bonito. Cada peça — do moletom aconchegante ao caderno de capa dura — é feita para acompanhar suas madrugadas, manhãs de café e tardes de leitura. Coisas simples, bem-feitas, em tons quentes de creme e vinho.
        </p>
      </section>

      <hr className="rule" style={{ margin: isMobile ? "0 20px" : "0 32px" }} />

      {/* categorias editoriais empilhadas */}
      <section className="wrap" style={{ padding: isMobile ? "48px 0 8px" : "84px 32px 30px" }}>
        <CategoryTrio onNav={onNav} />
      </section>

      <ProductGrid products={products} onOpen={onOpen} onAdd={onAdd} variant="editorial" title="Favoritos da estação" kicker="Curadoria" cols={4} limit={8} />

      {/* lifestyle row */}
      <section style={{ background: "var(--cream-2)", padding: isMobile ? "0" : "84px 0" }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 0, alignItems: "stretch", padding: isMobile ? 0 : undefined }}>
          <Img src="assets/caderno-smart-girl.jpg" label="LIFESTYLE — mesa de estudos completa (flat lay)" style={{ minHeight: isMobile ? 280 : 460 }} />
          <div style={{ background: "var(--wine)", color: "var(--cream)", padding: isMobile ? "44px 24px" : "64px 56px", display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <span className="kicker" style={{ color: "var(--cream)", opacity: 0.8 }}>O ritual</span>
            <h2 style={{ fontSize: isMobile ? "clamp(28px,8vw,38px)" : "clamp(30px,3.6vw,46px)", margin: "14px 0 16px", color: "var(--cream)" }}>Monte sua mesa perfeita</h2>
            <p style={{ fontSize: isMobile ? 16 : 18, opacity: 0.92, maxWidth: 380, marginBottom: 26 }}>Caderno, caneca, moletom favorito e foco. A combinação que faz a diferença na sua era de estudos.</p>
            <button className="btn" style={{ background: "var(--cream)", color: "var(--wine)", borderColor: "var(--cream)", alignSelf: "flex-start" }} onClick={() => onNav("Papelaria")}>Ver papelaria</button>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ---- wrapper que escolhe a direção ---- */
function Home({ dir, ...props }) {
  if (dir === "club") return <HomeClub {...props} />;
  if (dir === "library") return <HomeLibrary {...props} />;
  return <HomeAtelier {...props} />;
}

Object.assign(window, { Home, HomeAtelier, HomeClub, HomeLibrary, HeroCarousel, ProductGrid, CategoryTrio, BigMarquee });
