// src/category.jsx — Category deep-dive: filter + sort + bigger grid for a single aisle.

function Category({ storeId, category, onNav, cart, addToCart, tweaks }) {
  const isMobile = useMedia("(max-width: 720px)");
  const store = STORES.find(s => s.id === storeId) || STORES[0];
  const cat = CATEGORIES.find(c => c.id === category) || CATEGORIES[1];
  const [sort, setSort] = React.useState("popular");
  const [sub, setSub] = React.useState("all");

  const all = PRODUCTS.filter(p => p.category === cat.id);
  const subs = ["all", ...Array.from(new Set(all.map(p => p.subcategory).filter(Boolean)))];

  let list = sub === "all" ? all : all.filter(p => p.subcategory === sub);
  if (sort === "priceAsc")  list = [...list].sort((a,b) => a.price - b.price);
  if (sort === "priceDesc") list = [...list].sort((a,b) => b.price - a.price);
  if (sort === "popular")   list = [...list].sort((a,b) => (b.popular?1:0) - (a.popular?1:0));

  const cols = isMobile ? 2 : tweaks.density === "compact" ? 6 : tweaks.density === "comfy" ? 4 : 5;
  const getQty = (pid) => cart.items.find(i => i.productId === pid)?.qty || 0;

  const Icon = Icons[cat.icon];

  return (
    <div style={{ maxWidth: 1280, margin: "0 auto", padding: isMobile ? "14px 16px 120px" : "28px 28px 80px" }}>
      {/* breadcrumb */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--ink-3)", marginBottom: 16 }}>
        <button className="btn-reset" onClick={() => onNav({ screen: "home" })}>Home</button>
        <Icons.Chevron size={12} stroke={2} />
        <button className="btn-reset" onClick={() => onNav({ screen: "store", storeId })}>{store.name}</button>
        <Icons.Chevron size={12} stroke={2} />
        <span style={{ color: "var(--ink)" }}>{cat.label}</span>
      </div>

      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span style={{ width: 56, height: 56, borderRadius: 16, background: "var(--navy-tint)",
                         display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--navy)" }}>
            <Icon size={26} stroke={1.6} />
          </span>
          <div>
            <div className="uppercase-mono">{all.length} items</div>
            <h1 className="serif" style={{ fontSize: 36, margin: 0, letterSpacing: "-0.02em" }}>{cat.label}</h1>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <div style={{ display: "inline-flex", padding: 3, borderRadius: 999, background: "var(--surface-2)", border: "1px solid var(--line)" }}>
            {[
              { id: "popular", label: "Popular" },
              { id: "priceAsc", label: "Price ↑" },
              { id: "priceDesc", label: "Price ↓" },
            ].map(s => (
              <button key={s.id} className="btn-reset" onClick={() => setSort(s.id)}
                style={{ padding: "8px 14px", borderRadius: 999,
                         background: sort === s.id ? "var(--navy-fill)" : "transparent",
                         color: sort === s.id ? "#fff" : "var(--ink-2)",
                         fontSize: 12.5, fontWeight: 500 }}>{s.label}</button>
            ))}
          </div>
        </div>
      </div>

      {/* Subcategory chips */}
      {subs.length > 2 && (
        <div className="no-scrollbar" style={{ display: "flex", gap: 6, overflow: "auto", marginBottom: 20, paddingBottom: 4 }}>
          {subs.map(s => (
            <button key={s} className="btn-reset" onClick={() => setSub(s)}
              style={{ padding: "7px 14px", borderRadius: 999, whiteSpace: "nowrap",
                       background: sub === s ? "var(--navy-tint)" : "var(--surface)",
                       color: sub === s ? "var(--navy)" : "var(--ink-2)",
                       border: "1px solid " + (sub === s ? "transparent" : "var(--line)"),
                       fontSize: 12.5, fontWeight: 500 }}>
              {s === "all" ? "All" : s}
            </button>
          ))}
        </div>
      )}

      {list.length === 0 ? (
        <CategoryEmpty cat={cat} store={store} onNav={onNav} onClearFilter={() => setSub("all")} subActive={sub} />
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: "var(--grid-gap)" }}>
          {list.map(p => (
            <ProductCard key={p.id} p={p}
              qty={getQty(p.id)}
              onOpen={() => onNav({ screen: "product", storeId, productId: p.id })}
              onAdd={() => p.customizable
                ? onNav({ screen: "product", storeId, productId: p.id })
                : addToCart(storeId, p.id, 1)}
              onRemove={() => addToCart(storeId, p.id, -1)}
              pattern={tweaks.addPattern}
              density={tweaks.density} />
          ))}
        </div>
      )}
    </div>
  );
}

// Empty-state for a category aisle — either the store doesn't stock this
// category or the active sub-filter is too narrow. Offers three ways out:
// clear the filter, Ask Opa, or jump to a nearby store that does stock it.
function CategoryEmpty({ cat, store, onNav, onClearFilter, subActive }) {
  const alts = STORES.filter(s => s.id !== store.id).slice(0, 3);
  const Icon = Icons[cat.icon];
  const filtered = subActive !== "all";
  return (
    <div className="fade-in" style={{
      marginTop: 24, padding: "36px 32px",
      borderRadius: "var(--radius-xl)",
      background: "var(--surface)", border: "1px dashed var(--line)",
      display: "flex", gap: 24, alignItems: "center", flexWrap: "wrap",
    }}>
      <span style={{
        width: 64, height: 64, borderRadius: 20,
        background: "var(--navy-tint)", color: "var(--navy)",
        display: "grid", placeItems: "center", flexShrink: 0,
      }}>
        <Icon size={28} stroke={1.6} />
      </span>
      <div style={{ flex: "1 1 320px", minWidth: 240 }}>
        <h2 className="serif" style={{ fontSize: 24, margin: 0, letterSpacing: "-0.01em" }}>
          {filtered ? `Nothing matches "${subActive}" here.` : `${store.name} doesn't stock ${cat.label} today.`}
        </h2>
        <p style={{ fontSize: 13.5, color: "var(--ink-2)", margin: "8px 0 0", lineHeight: 1.5 }}>
          {filtered
            ? "Clear the filter to see everything in this aisle, or ask Opa to find it across stores."
            : `Three stores nearby carry ${cat.label.toLowerCase()}. One of them is probably 6 minutes closer than you think.`}
        </p>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {filtered && (
          <Btn variant="secondary" size="md" onClick={onClearFilter}>Clear filter</Btn>
        )}
        <Btn variant="primary" size="md" icon={<Icons.Sparkle size={13} stroke={2.2} />}
          onClick={() => onNav({ screen: "home" })}>
          Ask Opa
        </Btn>
      </div>
      {!filtered && alts.length > 0 && (
        <div style={{ flexBasis: "100%", marginTop: 12, display: "flex", gap: 8, flexWrap: "wrap" }}>
          <span className="uppercase-mono" style={{ marginRight: 4, alignSelf: "center" }}>Try nearby</span>
          {alts.map(s => (
            <button key={s.id} className="btn-reset"
              onClick={() => onNav({ screen: "store", storeId: s.id, category: cat.id })}
              style={{ padding: "7px 13px", borderRadius: 999,
                       background: "var(--surface-2)", border: "1px solid var(--line)",
                       fontSize: 12.5, fontWeight: 500, color: "var(--ink-2)",
                       display: "inline-flex", alignItems: "center", gap: 6 }}>
              <Icons.Store size={12} stroke={1.8} />
              {s.name}
              <span style={{ color: "var(--ink-4)" }}>· {s.eta}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

window.Category = Category;
