// ====================== MOBILE CHROME (header + search + catnav + location) ======================
// Renderizado SÓ no mobile (≤860px). Não altera a estrutura desktop.

function useIsMobile(bp = 860) {
  const q = `(max-width:${bp}px)`;
  const [m, setM] = React.useState(() =>
    typeof window !== "undefined" && window.matchMedia ? window.matchMedia(q).matches : false
  );
  React.useEffect(() => {
    const mq = window.matchMedia(q);
    const h = (e) => setM(e.matches);
    mq.addEventListener ? mq.addEventListener("change", h) : mq.addListener(h);
    return () => (mq.removeEventListener ? mq.removeEventListener("change", h) : mq.removeListener(h));
  }, [q]);
  return m;
}

// pequeno coração (favoritos) — ícone genérico inline
const IconHeartM = (p) => (
  <Ico {...p}><path d="M12 20s-7-4.6-9.3-9A5 5 0 0 1 12 6a5 5 0 0 1 9.3 5C19 15.4 12 20 12 20Z" /></Ico>
);

function MobileChrome({ cartCount = 0, onCart, onSearch, onNav, onOffers }) {
  const [q, setQ] = React.useState("");
  const [drawer, setDrawer] = React.useState(false);
  const [focus, setFocus] = React.useState(false);
  const [items, setItems] = React.useState([]);
  const searchWrap = React.useRef(null);

  React.useEffect(() => {
    if (window.JGFCatalog && window.JGFCatalog.allItems) {
      window.JGFCatalog.allItems().then(setItems).catch(() => setItems([]));
    }
  }, []);

  React.useEffect(() => {
    const h = (e) => { if (searchWrap.current && !searchWrap.current.contains(e.target)) setFocus(false); };
    document.addEventListener("mousedown", h);
    document.addEventListener("touchstart", h);
    return () => { document.removeEventListener("mousedown", h); document.removeEventListener("touchstart", h); };
  }, []);

  const norm = (s) => (s || "").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  const nq = norm(q.trim());
  const filtered = nq ? items.filter((it) => norm(it.nome).startsWith(nq)).slice(0, 10) : [];
  const PAGES = (window.JGFCatalog && window.JGFCatalog.PAGES) || {};
  const goItem = (it) => { const page = PAGES[it.secao]; setFocus(false); if (page) window.location.href = page + "?q=" + encodeURIComponent(it.nome); else onSearch(it.nome, "Todas as categorias"); };

  React.useEffect(() => {
    document.body.style.overflow = drawer ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [drawer]);

  const navLinks = VISIBLE_CATEGORIES.map((c) => ({ id: c.id, label: c.label }));

  const iconBtn = {
    display: "flex", alignItems: "center", justifyContent: "center",
    width: 36, height: 40, borderRadius: 9, color: "#fff", position: "relative", flexShrink: 0,
  };

  return (
    <div className="jgf-mobile-chrome">
      {/* ---- barra principal (navy) ---- */}
      <div style={{ background: "var(--navy)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 2, padding: "10px 10px" }}>
          <button aria-label="Menu" onClick={() => setDrawer(true)} style={{ ...iconBtn, width: 38 }}>
            <IconMenu size={26} stroke={2} />
          </button>
          <a href="JGF Distribuidora.html" aria-label="JGF — Início"
            style={{ display: "flex", alignItems: "center", marginRight: "auto", padding: "0 6px", minWidth: 0 }}>
            <img src="assets/brand/logo_white.png" alt="JGF Distribuidora"
              style={{ height: "auto", maxHeight: 34, maxWidth: 118, width: "auto", display: "block" }} />
          </a>
          <button aria-label="Carrinho" onClick={onCart} style={iconBtn}>
            <IconCart size={24} stroke={1.8} />
            {cartCount > 0 && (
              <span style={{
                position: "absolute", top: 2, right: 0, minWidth: 18, height: 18, padding: "0 4px",
                borderRadius: 10, background: "var(--yellow)", color: "var(--navy)", fontSize: 11,
                fontWeight: 800, display: "flex", alignItems: "center", justifyContent: "center",
                border: "2px solid var(--navy)",
              }}>{cartCount}</span>
            )}
          </button>
        </div>

        {/* ---- busca ---- */}
        <div style={{ padding: "0 12px 12px" }}>
          <div ref={searchWrap} style={{ position: "relative" }}>
            <form onSubmit={(e) => { e.preventDefault(); setFocus(false); onSearch(q, "Todas as categorias"); }}
              style={{ display: "flex", alignItems: "stretch", height: 46, borderRadius: 9, overflow: "hidden", background: "#fff" }}>
              <input value={q} onChange={(e) => setQ(e.target.value)} onFocus={() => setFocus(true)}
                placeholder="Digite aqui o que você procura"
                style={{ flex: 1, minWidth: 0, border: "none", outline: "none", padding: "0 15px", fontSize: 14.5, fontWeight: 500, color: "var(--ink)" }} />
              <button type="submit" aria-label="Buscar"
                style={{ width: 54, background: "var(--yellow)", color: "var(--navy)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <IconSearch size={22} stroke={2.2} />
              </button>
            </form>
            {focus && filtered.length > 0 && (
              <div style={{ position: "absolute", top: 52, left: 0, right: 0, background: "#fff", borderRadius: 10, boxShadow: "var(--shadow-card)", padding: 6, zIndex: 80, animation: "slideDown .16s ease both", maxHeight: 320, overflowY: "auto" }}>
                {filtered.map((it) => (
                  <button key={it.secao + it.nome} type="button" onClick={() => goItem(it)}
                    style={{ display: "flex", width: "100%", alignItems: "center", gap: 11, padding: "12px 12px", borderRadius: 7, fontSize: 14, fontWeight: 500, color: "#3a4256", textAlign: "left" }}>
                    <span style={{ color: "#9aa3b5", display: "flex", flexShrink: 0 }}><IconSearch size={16} /></span>{it.nome}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ---- nav de categorias (rolagem horizontal) ---- */}
      <div style={{ background: "#fff", borderBottom: "1px solid var(--line)" }}>
        <div className="jgf-mcatnav" style={{ display: "flex", alignItems: "center", gap: 0, overflowX: "auto", padding: "0 4px" }}>
          {navLinks.map((l, idx) => (
            <button key={l.id}
              onClick={() => PAGE_URLS[l.id] ? (window.location.href = PAGE_URLS[l.id]) : onNav(l.id)}
              style={{
                whiteSpace: "nowrap", padding: "13px 12px", fontSize: 13.5, fontWeight: 600,
                color: PAGE_URLS[l.id] ? "var(--yellow-dk)" : "var(--ink)",
                borderRight: idx < navLinks.length - 1 ? "1px solid var(--line)" : "none",
              }}>
              {l.label}
            </button>
          ))}
        </div>
      </div>

      {/* ---- drawer de categorias ---- */}
      {drawer && (
        <div onClick={() => setDrawer(false)}
          style={{ position: "fixed", inset: 0, background: "rgba(15,29,57,.5)", zIndex: 900, animation: "fadeUp .2s ease both" }}>
          <div onClick={(e) => e.stopPropagation()}
            style={{ position: "absolute", top: 0, left: 0, bottom: 0, width: "82%", maxWidth: 320, background: "#fff", boxShadow: "0 0 40px rgba(0,0,0,.3)", display: "flex", flexDirection: "column", animation: "slideInLeft .26s cubic-bezier(.2,.9,.3,1) both" }}>
            <div style={{ background: "var(--navy)", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 16px" }}>
              <img src="assets/brand/logo_white.png" alt="JGF" style={{ height: 34, width: "auto" }} />
              <button aria-label="Fechar" onClick={() => setDrawer(false)} style={{ color: "#fff", display: "flex" }}>
                <IconClose size={24} stroke={2} />
              </button>
            </div>
            <div style={{ padding: "8px 0", overflowY: "auto", flex: 1 }}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".08em", color: "#8a93a6", textTransform: "uppercase", padding: "12px 18px 6px" }}>Categorias</div>
              {navLinks.map((l) => (
                <button key={l.id}
                  onClick={() => { setDrawer(false); PAGE_URLS[l.id] ? (window.location.href = PAGE_URLS[l.id]) : onNav(l.id); }}
                  style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%", padding: "14px 18px", fontSize: 14.5, fontWeight: 600, color: "var(--ink)", textAlign: "left", borderBottom: "1px solid var(--soft)" }}>
                  {l.label}<IconChevronR size={16} stroke={2} style={{ color: "var(--yellow-dk)" }} />
                </button>
              ))}
            </div>
            <a href="Sobre a JGF.html"
              style={{ display: "flex", alignItems: "center", gap: 9, padding: "16px 18px", fontSize: 14, fontWeight: 600, color: "var(--navy)", borderTop: "1px solid var(--line)" }}>
              <IconCompany size={18} stroke={1.8} />Sobre a JGF
            </a>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MobileChrome, useIsMobile });
