// ====================== TOP BAR ======================
function TopBar() {
  const [loc, setLoc] = React.useState("Recife - PE");
  const [locOpen, setLocOpen] = React.useState(false);
  const left = [
  { icon: IconCompany, label: "Sobre a JGF", href: "Sobre a JGF.html" },
  { icon: IconChat, label: "Atendimento", href: "https://wa.me/" + WHATSAPP_NUMBER, ext: true },
  { icon: IconPhone, label: "Fale conosco", href: "tel:+558131270069" }];

  const cities = ["Recife - PE", "Olinda - PE", "Jaboatão - PE", "Caruaru - PE"];
  const link = { display: "flex", alignItems: "center", gap: 7, color: "#dfe4ef", fontSize: 12.5, fontWeight: 500, padding: "0 2px", transition: "color .15s" };
  return (
    <div className="jgf-topbar" style={{ background: "var(--navy)", height: 40, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div style={{ width: "100%", maxWidth: 1320, padding: "0 26px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
          {left.map((it) =>
          <a key={it.label} href={it.href} {...(it.ext ? { target: "_blank", rel: "noopener noreferrer" } : {})} style={link}
          onMouseEnter={(e) => e.currentTarget.style.color = "#fff"}
          onMouseLeave={(e) => e.currentTarget.style.color = "#dfe4ef"}>
              <it.icon size={15} stroke={1.6} />{it.label}
            </a>
          )}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, color: "#dfe4ef", fontSize: 12.5, fontWeight: 500 }}>
            <IconPin size={15} stroke={1.6} />Recife - PE
          </div>
        </div>
      </div>
    </div>);

}

// ====================== SEARCH (input + category dropdown + suggestions) ======================
const SUGGESTIONS = ["Álcool 70% Audax 5L", "Copos descartáveis 200ml", "Café Santa Clara 250g", "Papel toalha interfolha", "Detergente neutro 5L", "Caneta esferográfica azul", "Sabonete líquido", "Pasta suspensa"];

function SearchBar({ onSearch, initialQuery = "" }) {
  const [q, setQ] = React.useState(initialQuery);
  const [cat, setCat] = React.useState("Todas as categorias");
  const [catOpen, setCatOpen] = React.useState(false);
  const [focus, setFocus] = React.useState(false);
  const [items, setItems] = React.useState([]); // {nome, secao} do catálogo real
  const wrap = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => {if (wrap.current && !wrap.current.contains(e.target)) {setCatOpen(false);setFocus(false);}};
    document.addEventListener("mousedown", h);return () => document.removeEventListener("mousedown", h);
  }, []);
  React.useEffect(() => {
    if (window.JGFCatalog && window.JGFCatalog.allItems) {
      window.JGFCatalog.allItems().then(setItems).catch(() => setItems([]));
    }
  }, []);
  const norm = (s) => (s || "").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  const nq = norm(q.trim());
  const catId = { "Produtos de Copa": "copa", "Produtos de Limpeza": "limpeza", "Materiais de Escritório": "escritorio" }[cat];
  const filtered = nq
    ? items.filter((it) => (!catId || it.secao === catId) && norm(it.nome).startsWith(nq)).slice(0, 8)
    : [];
  const PAGES = (window.JGFCatalog && window.JGFCatalog.PAGES) || {};
  const goItem = (it) => { const page = PAGES[it.secao]; if (page) window.location.href = page + "?q=" + encodeURIComponent(it.nome); else onSearch(it.nome, cat); };
  const go = (term) => {onSearch(term || q, cat);setFocus(false);};
  const catList = ["Todas as categorias", ...VISIBLE_CATEGORIES.map((c) => c.label)];
  return (
    <div ref={wrap} className="jgf-header-search" style={{ position: "relative", flex: 1, maxWidth: 660 }}>
      <form onSubmit={(e) => {e.preventDefault();go();}}
      style={{ display: "flex", alignItems: "stretch", height: 50, border: `2px solid ${focus ? "var(--navy)" : "var(--line)"}`, borderRadius: 10, overflow: "hidden", transition: "border-color .15s", background: "#fff" }}>
        <input value={q} onChange={(e) => setQ(e.target.value)} onFocus={() => setFocus(true)}
        placeholder="O que você procura?"
        style={{ flex: 1, border: "none", outline: "none", padding: "0 18px", fontSize: 14.5, fontWeight: 500, color: "var(--ink)" }} />
        <div className="jgf-search-cat" style={{ display: "none" }} />
        <button type="submit" aria-label="Buscar"
        style={{ width: 60, background: "var(--navy)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", transition: "background .15s" }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--navy-2)"}
        onMouseLeave={(e) => e.currentTarget.style.background = "var(--navy)"}>
          <IconSearch size={21} stroke={2} />
        </button>
      </form>
      {focus && filtered.length > 0 &&
      <div style={{ position: "absolute", top: 56, left: 0, right: 0, background: "#fff", borderRadius: 10, boxShadow: "var(--shadow-card)", padding: 6, zIndex: 65, maxHeight: 340, overflowY: "auto", animation: "slideDown .16s ease both" }}>
          {filtered.map((it) =>
        <button key={it.secao + it.nome} onClick={() => goItem(it)}
        style={{ display: "flex", width: "100%", alignItems: "center", gap: 10, padding: "11px 12px", borderRadius: 7, fontSize: 13.5, fontWeight: 500, color: "#3a4256", textAlign: "left" }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--soft)"}
        onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <span style={{ color: "#9aa3b5", flexShrink: 0 }}><IconSearch size={15} /></span>{it.nome}
            </button>
        )}
        </div>
      }
    </div>);

}

// ====================== MAIN HEADER ======================
function MainHeader({ cartCount, onCart, onSearch, initialQuery = "" }) {
  const action = (icon, l1, l2, onClick, badge) =>
  <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 8px", borderRadius: 9, transition: "background .15s" }}
  onMouseEnter={(e) => e.currentTarget.style.background = "var(--soft)"}
  onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
      <div style={{ position: "relative", color: "var(--navy)" }}>
        {icon}
        {badge != null &&
      <span key={badge} style={{ position: "absolute", top: -7, right: -9, minWidth: 19, height: 19, padding: "0 4px", borderRadius: 11, background: "var(--yellow)", color: "var(--navy)", fontSize: 11, fontWeight: 800, display: "flex", alignItems: "center", justifyContent: "center", animation: "pop .3s ease both", border: "2px solid #fff" }}>{badge}</span>
      }
      </div>
      <div className="jgf-action-text" style={{ textAlign: "left", lineHeight: 1.25 }}>
        <div style={{ fontSize: 11, color: "#8a93a6", fontWeight: 500 }}>{l1}</div>
        <div style={{ fontSize: 13.5, color: "var(--navy)", fontWeight: 700 }}>{l2}</div>
      </div>
    </button>;

  return (
    <div style={{ background: "#fff", display: "flex", justifyContent: "center" }}>
      <div className="jgf-header" style={{ width: "100%", maxWidth: 1320, padding: "20px 26px", display: "flex", alignItems: "center", gap: 32 }}>
        <a href="JGF Distribuidora.html" aria-label="JGF Distribuidora — Página inicial" style={{ display: "flex", alignItems: "center", flexShrink: 0 }}>
          <Logo scale={0.92} />
        </a>
        <SearchBar onSearch={onSearch} initialQuery={initialQuery} />
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginLeft: "auto" }}>
          {action(<IconCart size={26} stroke={1.6} />, "Carrinho", "Meu carrinho", onCart, cartCount)}
        </div>
      </div>
    </div>);

}

// ====================== CATEGORY NAVBAR + MEGA MENU ======================
function CategoryNav({ onNav, onOffers }) {
  const [mega, setMega] = React.useState(false);
  const [equip, setEquip] = React.useState(false);
  const navRef = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => {if (navRef.current && !navRef.current.contains(e.target)) setMega(false);};
    document.addEventListener("mousedown", h);return () => document.removeEventListener("mousedown", h);
  }, []);
  const links = [
  { label: "Produtos de Copa", id: "copa" },
  { label: "Produtos de Limpeza", id: "limpeza" },
  { label: "Materiais de Escritório", id: "escritorio" }];

  const linkStyle = { color: "#eef1f8", fontSize: 14, fontWeight: 600, padding: "0 4px", display: "flex", alignItems: "center", gap: 5, height: 54, transition: "color .15s" };
  return (
    <div ref={navRef} style={{ background: "var(--navy)", display: "flex", justifyContent: "center", position: "relative", zIndex: 50 }}>
      <div className="jgf-catnav" style={{ width: "100%", maxWidth: 1320, padding: "0 26px", display: "flex", alignItems: "center", gap: 26, height: 54 }}>
        {/* TODAS AS CATEGORIAS */}
        <button onClick={() => setMega((o) => !o)}
        style={{ display: "flex", alignItems: "center", gap: 11, color: "var(--yellow)", fontWeight: 800, fontSize: 14, letterSpacing: ".02em", height: 54, paddingRight: 6 }}>
          <IconMenu size={20} stroke={2} />TODAS AS CATEGORIAS
        </button>
        <div className="jgf-catnav-div" style={{ width: 1, height: 22, background: "rgba(255,255,255,.16)" }} />
        {links.map((l) =>
        <div key={l.id} className="jgf-catnav-link" style={{ position: "relative" }}
        onMouseEnter={() => l.id === "equipamentos" && setEquip(true)}
        onMouseLeave={() => l.id === "equipamentos" && setEquip(false)}>
            <button onClick={() => PAGE_URLS[l.id] ? (window.location.href = PAGE_URLS[l.id]) : onNav(l.id)} style={linkStyle}
          onMouseEnter={(e) => e.currentTarget.style.color = "var(--yellow)"}
          onMouseLeave={(e) => e.currentTarget.style.color = "#eef1f8"}>
              {l.label}{l.caret && <IconChevron size={13} stroke={2.2} />}
            </button>
            {l.id === "equipamentos" && equip &&
          <div style={{ position: "absolute", top: 52, left: -10, width: 244, background: "#fff", borderRadius: "0 0 10px 10px", boxShadow: "var(--shadow-card)", padding: 8, animation: "slideDown .16s ease both" }}>
                {EQUIP_SUB.map((s) =>
            <button key={s} onClick={() => onNav("equipamentos")}
            style={{ display: "flex", width: "100%", alignItems: "center", gap: 9, padding: "11px 12px", borderRadius: 7, fontSize: 13.5, fontWeight: 600, color: "#3a4256", textAlign: "left" }}
            onMouseEnter={(e) => {e.currentTarget.style.background = "var(--soft)";e.currentTarget.style.color = "var(--navy)";}}
            onMouseLeave={(e) => {e.currentTarget.style.background = "transparent";e.currentTarget.style.color = "#3a4256";}}>
                    <IconChevronR size={13} stroke={2.2} style={{ color: "var(--yellow)" }} />{s}
                  </button>
            )}
              </div>
          }
          </div>
        )}
        {/* Ação à direita: contato / WhatsApp (substitui o antigo OFERTAS) */}
        <a href={"https://wa.me/" + WHATSAPP_NUMBER} target="_blank" rel="noopener noreferrer"
          className="jgf-catnav-cta"
          style={{ marginLeft: "auto", alignSelf: "stretch", position: "relative", display: "flex", alignItems: "center", textDecoration: "none" }}
          aria-label="Peça pelo WhatsApp">
          <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 9, background: "var(--yellow)", color: "var(--navy)", fontWeight: 800, fontSize: 14, letterSpacing: ".02em", padding: "0 30px 0 38px", height: 54, clipPath: "polygon(22px 0, 100% 0, 100% 100%, 0 100%)" }}>
            <IconHeadset size={18} stroke={2} /><span className="jgf-cta-full">PEÇA PELO WHATSAPP</span><span className="jgf-cta-mini" style={{ display: "none" }}>WHATSAPP</span>
          </div>
        </a>
      </div>

      {/* MEGA MENU */}
      {mega &&
      <div style={{ position: "absolute", top: 54, left: 0, right: 0, display: "flex", justifyContent: "center", animation: "slideDown .18s ease both" }}>
          <div className="jgf-grid-3" style={{ width: "100%", maxWidth: 1320, margin: "0 26px", background: "#fff", borderRadius: "0 0 14px 14px", boxShadow: "var(--shadow-card)", padding: 22, display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8 }}>
            {VISIBLE_CATEGORIES.map((c) =>
          <button key={c.id} onClick={() => {if(PAGE_URLS[c.id]){window.location.href=PAGE_URLS[c.id];return;}onNav(c.id);setMega(false);}}
          style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 14px", borderRadius: 10, textAlign: "left", transition: "background .15s" }}
          onMouseEnter={(e) => e.currentTarget.style.background = "var(--soft)"}
          onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                <div style={{ width: 48, height: 48, flexShrink: 0, background: "#fff", border: "1px solid var(--line)", borderRadius: 9, display: "flex", alignItems: "center", justifyContent: "center", padding: 5 }}>
                  <img src={`assets/categorias/${c.id}_prod.png`} alt={c.label} style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }} />
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14, color: "var(--navy)" }}>{c.label}</div>
                  <div style={{ fontSize: 12, color: "#8a93a6", marginTop: 2 }}>Ver todos os produtos</div>
                </div>
              </button>
          )}
          </div>
        </div>
      }
    </div>);

}

Object.assign(window, { TopBar, MainHeader, CategoryNav, SUGGESTIONS });