// shell.jsx — hostbar, intro animation, header, footer, drawers

const { useState: useShellState, useEffect: useShellEffect, useRef: useShellRef } = React;

/* ============================ HOSTBAR ============================ */
function Hostbar({ viewport, setViewport, theme, setTheme, onReplayIntro }) {
  const [tweaksOpen, setTweaksOpen] = useShellState(false);
  const toggleTweaks = () => {
    const next = !tweaksOpen;
    setTweaksOpen(next);
    window.postMessage({ type: next ? "__activate_edit_mode" : "__deactivate_edit_mode" }, "*");
  };
  useShellEffect(() => {
    const onMsg = (e) => {
      if (e?.data?.type === "__edit_mode_dismissed") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, []);
  return (
    <div className="hostbar">
      <div className="hb-group hb-brand-group">
        <span className="dot"></span>
        <span style={{ marginLeft: 8, fontWeight: 700, color: "var(--orah-cream-50)" }}>ORAH CULTURE</span>
        <span style={{ opacity: 0.45, marginLeft: 8 }}>· e-commerce mockup</span>
      </div>
      <div className="hb-group">
        <button onClick={onReplayIntro} title="Replay intro">↻ intro</button>
        <span className="hb-sep" style={{ width: 12 }}></span>
        <button onClick={() => setTheme(theme === "light" ? "dark" : "light")} title="Toggle theme">
          {theme === "light" ? "◐ light" : "◑ dark"}
        </button>
        <span className="hb-sep" style={{ width: 12 }}></span>
        <button className={tweaksOpen ? "active" : ""} onClick={toggleTweaks} title="Toggle tweaks">⚙ tweaks</button>
        <span className="hb-sep hb-viewport-only" style={{ width: 12 }}></span>
        <button className={"hb-viewport-only " + (viewport === "desktop" ? "active" : "")} onClick={() => setViewport("desktop")}>◻ desktop</button>
        <button className={"hb-viewport-only " + (viewport === "mobile" ? "active" : "")} onClick={() => setViewport("mobile")}>▯ mobile</button>
      </div>
    </div>
  );
}

/* ============================ INTRO ============================ */
function Intro({ onDone, replayKey }) {
  const [phase, setPhase] = useShellState("in"); // in -> hold -> out -> done

  useShellEffect(() => {
    setPhase("in");
    document.body.classList.add("intro-active");
    const t1 = setTimeout(() => setPhase("out"), 3000);
    const t2 = setTimeout(() => {
      setPhase("done");
      document.body.classList.remove("intro-active");
      onDone && onDone();
    }, 3900);
    return () => {
      clearTimeout(t1); clearTimeout(t2);
      document.body.classList.remove("intro-active");
    };
  }, [replayKey]);

  if (phase === "done") return null;

  return (
    <div className={"intro-screen " + (phase === "out" ? "intro-exit" : "")}>
      <div className="ripple"></div>
      <div className="ripple r2"></div>
      <div className="ripple r3"></div>
      <div className="intro-stack">
        <div className="ring">
          <img src="assets/orah-logo.png" alt="ORAH" />
        </div>
        <div className="tag">uma <b>marca</b>, um <b>propósito</b>.</div>
        <div className="wordmark-line">
          ORAH
          <span className="culture">CULTURE</span>
        </div>
      </div>
    </div>
  );
}

/* ============================ HEADER ============================ */
function Header() {
  const { goto, push, cart, wish, drawer, setDrawer, page } = useShop();
  const [mega, setMega] = useShellState(null);
  const cartCount = cart.reduce((a, b) => a + b.qty, 0);

  return (
    <header className="site-header" onMouseLeave={() => setMega(null)}>
      <div className="wrap inner">
        {/* mobile menu */}
        <button className="icon-btn only-mobile" onClick={() => setDrawer("menu")}>
          <Icon name="menu" />
        </button>

        <div className="logo" onClick={() => goto("home")}>
          <span className="ico"><img src="assets/orah-logo.png" alt="" /></span>
          <span className="only-desktop">ORAH<span style={{ fontSize: 12, marginLeft: 6, letterSpacing: "0.18em", opacity: 0.6 }}>CULTURE</span></span>
        </div>

        <nav className="only-desktop">
          <a onMouseEnter={() => setMega("loja")} onClick={() => goto("shop")}>Loja</a>
          <a onMouseEnter={() => setMega("colecoes")} onClick={() => goto("shop")}>Coleções</a>
          <a onMouseEnter={() => setMega("marca")} onClick={() => goto("manifesto")}>Marca</a>
          <a onMouseEnter={() => setMega(null)} onClick={() => goto("about")}>Quem Somos</a>
          <a onMouseEnter={() => setMega(null)} onClick={() => goto("admin")} style={{ color: "var(--accent)" }}>ADM</a>
        </nav>

        <div className="actions">
          <button className="icon-btn only-desktop" onClick={() => setDrawer("search")} title="Buscar"><Icon name="search" /></button>
          <button className="icon-btn only-desktop" onClick={() => goto("account")} title="Minha conta"><Icon name="user" /></button>
          <button className="icon-btn" onClick={() => goto("wishlist")} title="Lista de desejos">
            <Icon name="heart" />
            {wish.length > 0 && <span className="count">{wish.length}</span>}
          </button>
          <button className="icon-btn" onClick={() => setDrawer("cart")} title="Sacola">
            <Icon name="bag" />
            {cartCount > 0 && <span className="count">{cartCount}</span>}
          </button>
        </div>
      </div>

      {/* mega menu */}
      <div className={"mega " + (mega ? "open" : "")} onMouseEnter={() => mega && setMega(mega)}>
        <div className="wrap mega-grid">
          <div className="mega-feature">
            <span className="mono" style={{ opacity: 0.7 }}>Drop 01 · Manifesto</span>
            <div style={{ fontFamily: "var(--f-display)", fontSize: 44, lineHeight: 0.95, textTransform: "uppercase", marginTop: 8 }}>
              uma marca,<br/><span style={{ color: "var(--accent-warm)" }}>um propósito</span>
            </div>
            <button className="btn ghost" style={{ alignSelf: "start", color: "inherit", borderColor: "currentColor" }} onClick={() => goto("shop")}>
              Ver coleção <Icon name="arrowR" size={14} />
            </button>
          </div>

          {mega === "loja" && (<>
            <div><h4>Categorias</h4><ul>
              <li onClick={() => goto("shop")}>Oversized</li>
              <li onClick={() => goto("shop")}>Camisetas</li>
              <li onClick={() => goto("shop")}>Drops</li>
              <li onClick={() => goto("shop")}>Acessórios</li>
            </ul></div>
            <div><h4>Por estampa</h4><ul>
              <li onClick={() => goto("shop")}>Manifesto</li>
              <li onClick={() => goto("shop")}>Eterno</li>
              <li onClick={() => goto("shop")}>Edição limitada</li>
            </ul></div>
            <div><h4>Atalhos</h4><ul style={{ fontFamily: "var(--f-body)", fontSize: 14, textTransform: "none" }}>
              <li onClick={() => goto("shop")}><span className="badge fire dot">novo</span> Águas Vivas</li>
              <li onClick={() => goto("shop")}>Tabela de medidas</li>
              <li onClick={() => goto("shop")}>Política de troca</li>
            </ul></div>
          </>)}

          {mega === "colecoes" && (<>
            <div><h4>Drop 01</h4><ul>
              <li onClick={() => goto("shop")}>Águas Vivas</li>
              <li onClick={() => goto("shop")}>Fogo Puro</li>
              <li onClick={() => goto("shop")}>O Reino Vem</li>
            </ul></div>
            <div><h4>Drop 02</h4><ul>
              <li onClick={() => goto("shop")}>Em breve</li>
              <li onClick={() => goto("shop")}>Pré-venda</li>
            </ul></div>
            <div><h4>Arquivo</h4><ul>
              <li onClick={() => goto("shop")}>2025</li>
              <li onClick={() => goto("shop")}>Bastidores</li>
            </ul></div>
          </>)}

          {mega === "marca" && (<>
            <div><h4>História</h4><ul>
              <li onClick={() => goto("manifesto")}>Manifesto</li>
              <li onClick={() => goto("about")}>Quem somos</li>
              <li onClick={() => goto("about")}>Propósito</li>
            </ul></div>
            <div><h4>Comunidade</h4><ul style={{ fontFamily: "var(--f-body)", fontSize: 14, textTransform: "none" }}>
              <li>Instagram @orahculture</li>
              <li>Lookbook</li>
              <li>Embaixadores</li>
            </ul></div>
            <div><h4>Suporte</h4><ul style={{ fontFamily: "var(--f-body)", fontSize: 14, textTransform: "none" }}>
              <li onClick={() => goto("contact")}>Contato</li>
              <li>FAQ</li>
              <li>Trocas e devoluções</li>
            </ul></div>
          </>)}
        </div>
      </div>
    </header>
  );
}

/* ============================ FOOTER ============================ */
function Footer() {
  const { goto } = useShop();
  return (
    <footer className="site-footer">
      <div className="wrap">
        <div className="row" style={{ justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
          <div style={{ maxWidth: 420 }}>
            <div className="row gap-3">
              <span style={{
                width: 56, height: 56, borderRadius: "50%", overflow: "hidden",
                border: "2px solid currentColor", display: "grid", placeItems: "center",
              }}>
                <img src="assets/orah-logo.png" alt="ORAH" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </span>
              <div>
                <div style={{ fontFamily: "var(--f-display)", fontSize: 28, lineHeight: 1 }}>ORAH CULTURE</div>
                <div style={{ fontFamily: "var(--f-hand)", fontSize: 18, opacity: 0.85 }}>uma marca, um propósito.</div>
              </div>
            </div>
            <p style={{ marginTop: 18, fontSize: 14, lineHeight: 1.6, opacity: 0.85 }}>
              Camisetas cristãs oversized, masculinas e femininas, com estampas modernas e cheias de significado. Pra levar um pouco de Jesus e do Reino por onde passar.
            </p>

            <div style={{ marginTop: 18 }}>
              <div className="mono" style={{ opacity: 0.7, marginBottom: 8 }}>Receba os próximos drops</div>
              <div className="row gap-2" style={{ background: "rgba(255,255,255,0.1)", padding: 4, borderRadius: 999 }}>
                <input
                  type="email"
                  placeholder="seu melhor email"
                  style={{ border: "none", background: "transparent", color: "inherit", padding: "10px 14px" }}
                />
                <button className="btn" style={{ background: "var(--orah-cream-50)", color: "var(--orah-blue-800)", border: "none" }}>
                  Quero
                </button>
              </div>
            </div>
          </div>

          <div className="links" style={{ flex: 1, minWidth: 280 }}>
            <div>
              <h5>Loja</h5>
              <ul>
                <li><a onClick={() => goto("shop")} style={{ cursor: "pointer" }}>Todos os produtos</a></li>
                <li><a onClick={() => goto("shop")} style={{ cursor: "pointer" }}>Manifesto</a></li>
                <li><a onClick={() => goto("shop")} style={{ cursor: "pointer" }}>Eterno</a></li>
                <li><a onClick={() => goto("shop")} style={{ cursor: "pointer" }}>Drops</a></li>
              </ul>
            </div>
            <div>
              <h5>Marca</h5>
              <ul>
                <li><a onClick={() => goto("manifesto")} style={{ cursor: "pointer" }}>Manifesto</a></li>
                <li><a onClick={() => goto("about")} style={{ cursor: "pointer" }}>Quem somos</a></li>
                <li><a onClick={() => goto("contact")} style={{ cursor: "pointer" }}>Contato</a></li>
              </ul>
            </div>
            <div>
              <h5>Ajuda</h5>
              <ul>
                <li><a style={{ cursor: "pointer" }}>FAQ</a></li>
                <li><a style={{ cursor: "pointer" }}>Tabela de medidas</a></li>
                <li><a style={{ cursor: "pointer" }}>Trocas</a></li>
                <li><a style={{ cursor: "pointer" }}>Frete e entrega</a></li>
              </ul>
            </div>
            <div>
              <h5>Conta</h5>
              <ul>
                <li><a onClick={() => goto("account")} style={{ cursor: "pointer" }}>Minha conta</a></li>
                <li><a onClick={() => goto("account")} style={{ cursor: "pointer" }}>Meus pedidos</a></li>
                <li><a onClick={() => goto("wishlist")} style={{ cursor: "pointer" }}>Lista de desejos</a></li>
                <li><a onClick={() => goto("admin")} style={{ cursor: "pointer", color: "var(--accent-warm)" }}>ADM</a></li>
              </ul>
            </div>
          </div>
        </div>

        <div className="wordmark">ORAH·CULTURE·ORAH·CULTURE</div>

        <div className="meta">
          <span>© 2026 ORAH CULTURE · CNPJ 00.000.000/0001-00 · Ponta Grossa/PR</span>
          <span className="row gap-3">
            <Icon name="instagram" size={16} /> @orahculture
            <span style={{ opacity: 0.4 }}>·</span>
            <Icon name="spotify" size={16} /> Playlist do Reino
          </span>
        </div>
      </div>
    </footer>
  );
}

/* ============================ DRAWERS ============================ */
function Drawer({ open, side = "right", onClose, children, title }) {
  return (
    <>
      <div className={"drawer-bg " + (open ? "open" : "")} onClick={onClose}></div>
      <div className={"drawer " + (open ? "open" : "")}
        style={side === "left" ? { right: "auto", left: 0, transform: open ? "translateX(0)" : "translateX(-100%)", borderLeft: "none", borderRight: "1px solid var(--ink-line)" } : null}>
        <div className="drawer-head">
          <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase" }}>{title}</div>
          <button className="icon-btn" onClick={onClose}><Icon name="close" /></button>
        </div>
        {children}
      </div>
    </>
  );
}

function MobileMenu() {
  const { drawer, setDrawer, goto, push } = useShop();
  const [openSec, setOpenSec] = useShellState(null);
  const open = drawer === "menu";

  const sections = [
    { id: "loja", label: "Loja", items: [
      { label: "Todos os produtos", to: "shop" },
      { label: "Manifesto", to: "shop" },
      { label: "Eterno", to: "shop" },
      { label: "Drops", to: "shop" },
    ]},
    { id: "colecoes", label: "Coleções", items: [
      { label: "Drop 01 — Águas Vivas", to: "shop" },
      { label: "Drop 02 — Em breve", to: "shop" },
    ]},
    { id: "marca", label: "Marca", items: [
      { label: "Manifesto", to: "manifesto" },
      { label: "Quem somos", to: "about" },
      { label: "Contato", to: "contact" },
    ]},
    { id: "conta", label: "Conta", items: [
      { label: "Minha conta", to: "account" },
      { label: "Meus pedidos", to: "account" },
      { label: "Lista de desejos", to: "wishlist" },
    ]},
  ];

  return (
    <Drawer open={open} side="left" onClose={() => setDrawer(null)} title={<span><span style={{ color: "var(--brand)" }}>ORAH</span> · Menu</span>}>
      <div className="mob-menu">
        {sections.map((s) => (
          <React.Fragment key={s.id}>
            <a className={"item " + (openSec === s.id ? "open" : "")} onClick={() => setOpenSec(openSec === s.id ? null : s.id)}>
              <span>{s.label}</span>
              <Icon name={openSec === s.id ? "minus" : "plus"} size={20} />
            </a>
            <div className="sub">
              {s.items.map((it, i) => <a key={i} onClick={() => goto(it.to)}>{it.label}</a>)}
            </div>
          </React.Fragment>
        ))}
        <a
          className="item"
          onClick={() => goto("admin")}
          style={{ color: "var(--accent)", borderTop: "2px solid var(--accent)", marginTop: 4 }}
        >
          <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <Icon name="cog" size={18} /> ADM
          </span>
          <Icon name="arrowR" size={18} />
        </a>
        <div style={{ padding: "32px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="mono muted">Acompanhe</div>
          <div className="row gap-3">
            <Icon name="instagram" size={20} />
            <span style={{ fontFamily: "var(--f-display)", fontSize: 20 }}>@orahculture</span>
          </div>
          <div style={{ fontFamily: "var(--f-hand)", fontSize: 24, color: "var(--brand)" }}>
            uma marca, um propósito.
          </div>
        </div>
      </div>
    </Drawer>
  );
}

function CartDrawer() {
  const { drawer, setDrawer, cart, updateCart, goto } = useShop();
  const open = drawer === "cart";
  const items = cart.map((c) => ({ ...c, product: ORAH_PRODUCTS.find((p) => p.id === c.productId) })).filter((x) => x.product);
  const subtotal = items.reduce((a, b) => a + b.product.price * b.qty, 0);

  return (
    <Drawer open={open} onClose={() => setDrawer(null)} title="Sacola">
      <div style={{ flex: 1, overflowY: "auto", padding: "16px 20px" }}>
        {items.length === 0 && (
          <div style={{ textAlign: "center", padding: "40px 20px", color: "var(--ink-soft)" }}>
            <div style={{ fontFamily: "var(--f-display)", fontSize: 32, color: "var(--ink)" }}>Sacola vazia</div>
            <div style={{ marginTop: 8, fontFamily: "var(--f-hand)", fontSize: 22, color: "var(--brand)" }}>aproveita um drop ;)</div>
            <button className="btn brand" style={{ marginTop: 24 }} onClick={() => { setDrawer(null); goto("shop"); }}>
              Ver coleção
            </button>
          </div>
        )}
        {items.map((it, idx) => (
          <div key={idx} className="row gap-3" style={{ padding: "14px 0", borderBottom: "1px solid var(--ink-line)", alignItems: "flex-start" }}>
            <div style={{ width: 88, height: 110, borderRadius: 8, overflow: "hidden", flexShrink: 0 }}>
              <ProductVisual product={it.product} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 20, textTransform: "uppercase", lineHeight: 1 }}>{it.product.name}</div>
              <div className="mono muted" style={{ marginTop: 4 }}>Tam. {it.size} · {it.product.line}</div>
              <div className="row" style={{ justifyContent: "space-between", marginTop: 10 }}>
                <div className="row" style={{ border: "1px solid var(--ink-line)", borderRadius: 999 }}>
                  <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={() => updateCart(idx, it.qty - 1)}><Icon name="minus" size={14} /></button>
                  <span style={{ minWidth: 24, textAlign: "center", fontWeight: 700 }}>{it.qty}</span>
                  <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={() => updateCart(idx, it.qty + 1)}><Icon name="plus" size={14} /></button>
                </div>
                <div style={{ fontWeight: 700 }}>R$ {(it.product.price * it.qty).toFixed(2).replace(".", ",")}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
      {items.length > 0 && (
        <div style={{ borderTop: "1px solid var(--ink-line)", padding: 20, background: "var(--bg-card)" }}>
          <div className="row" style={{ justifyContent: "space-between" }}>
            <span className="mono">Subtotal</span>
            <span style={{ fontFamily: "var(--f-display)", fontSize: 28 }}>R$ {subtotal.toFixed(2).replace(".", ",")}</span>
          </div>
          <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>Frete e impostos calculados no checkout.</div>
          <button className="btn brand block lg" style={{ marginTop: 16 }} onClick={() => { setDrawer(null); goto("checkout"); }}>
            Finalizar compra <Icon name="arrowR" size={14} />
          </button>
          <button className="btn ghost block" style={{ marginTop: 8 }} onClick={() => { setDrawer(null); goto("cart"); }}>
            Ver sacola completa
          </button>
        </div>
      )}
    </Drawer>
  );
}

function SearchDrawer() {
  const { drawer, setDrawer, goto } = useShop();
  const open = drawer === "search";
  const [q, setQ] = useShellState("");
  const results = ORAH_PRODUCTS.filter((p) => !q || p.name.toLowerCase().includes(q.toLowerCase()) || p.line.toLowerCase().includes(q.toLowerCase()));

  return (
    <Drawer open={open} side="left" onClose={() => setDrawer(null)} title="Buscar">
      <div style={{ padding: 20 }}>
        <input autoFocus placeholder="buscar por estampa, versículo, coleção…" value={q} onChange={(e) => setQ(e.target.value)} style={{ fontSize: 18 }} />
        <div className="mono muted" style={{ marginTop: 18, marginBottom: 8 }}>Sugestões</div>
        <div className="row gap-2" style={{ flexWrap: "wrap" }}>
          {["Águas Vivas", "Fogo", "Drop 01", "Versículo", "Oversized"].map((t) => (
            <button key={t} className="badge" style={{ cursor: "pointer" }} onClick={() => setQ(t)}>{t}</button>
          ))}
        </div>
        <div className="mono muted" style={{ marginTop: 20, marginBottom: 10 }}>{results.length} resultados</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {results.slice(0, 4).map((p) => (
            <div key={p.id} onClick={() => { setDrawer(null); goto({ name: "product", params: { id: p.id } }); }} style={{ cursor: "pointer" }}>
              <div style={{ aspectRatio: "4/5", borderRadius: 8, overflow: "hidden" }}><ProductVisual product={p} /></div>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 16, textTransform: "uppercase", marginTop: 6 }}>{p.name}</div>
              <div className="mono muted" style={{ fontSize: 10 }}>R$ {p.price.toFixed(2).replace(".", ",")}</div>
            </div>
          ))}
        </div>
      </div>
    </Drawer>
  );
}

/* expose */
Object.assign(window, { Hostbar, Intro, Header, Footer, Drawer, MobileMenu, CartDrawer, SearchDrawer });
