// ==============================================
// Catalog page (Product list with filter/search/sort)
// ==============================================

function CatalogPage({ session, cart, addToCart, navigate, query, setQuery, initialCategory, initialSale, products: propProducts }) {
  const productList = (propProducts && propProducts.length) ? propProducts : PRODUCTS;
  const [category, setCategory] = useState(initialCategory || "all");
  const [brands, setBrands] = useState([]);
  const [priceRange, setPriceRange] = useState(20000);
  const [inStock, setInStock] = useState(false);
  const [saleOnly, setSaleOnly] = useState(!!initialSale);
  const [sort, setSort] = useState("relevance");
  const [view, setView] = useState("grid");

  useEffect(() => { if (initialCategory) setCategory(initialCategory); }, [initialCategory]);
  useEffect(() => { if (initialSale) setSaleOnly(true); }, [initialSale]);

  const isDealer = session?.role === "dealer";
  const inCartIds = new Set(cart.map(c => c.id));

  const filtered = useMemo(() => {
    let list = productList;
    if (category !== "all") list = list.filter(p => p.category === category || p.category_slug === category);
    if (brands.length) list = list.filter(p => brands.includes(p.brand));
    if (inStock) list = list.filter(p => p.stock > 0);
    if (saleOnly) list = list.filter(p => p.tag === "sale" || p.oldPrice);
    if (query) {
      const q = query.toLowerCase();
      list = list.filter(p =>
        p.th.toLowerCase().includes(q) ||
        p.en.toLowerCase().includes(q) ||
        p.sku.toLowerCase().includes(q) ||
        p.brand.toLowerCase().includes(q) ||
        p.desc.toLowerCase().includes(q)
      );
    }
    list = list.filter(p => (isDealer ? p.dealerPrice : p.price) <= priceRange);
    const sorted = [...list];
    if (sort === "priceLow") sorted.sort((a, b) => a.price - b.price);
    else if (sort === "priceHigh") sorted.sort((a, b) => b.price - a.price);
    else if (sort === "newest") sorted.sort((a, b) => (b.tag === "new" ? 1 : 0) - (a.tag === "new" ? 1 : 0));
    else if (sort === "popular") sorted.sort((a, b) => b.reviews - a.reviews);
    return sorted;
  }, [category, brands, inStock, saleOnly, query, sort, priceRange, isDealer]);

  const cats = [{ id: "all", th: "ทั้งหมด", en: "All", count: PRODUCTS.length }, ...CATEGORIES];

  const toggleBrand = (b) => setBrands(prev => prev.includes(b) ? prev.filter(x => x !== b) : [...prev, b]);

  return (
    <div className="container">
      <div className="page-head">
        <div>
          <div className="crumb"><a onClick={() => navigate("catalog")}>หน้าแรก</a> <Icon name="chevron-right" size={12}/> สินค้าทั้งหมด</div>
          <h1>สินค้าเครื่องมือช่าง <span style={{color: "var(--ink-500)", fontWeight: 500, fontSize: 16}}>· Tools & Hardware Catalog</span></h1>
        </div>
        <div className="flex gap-8">
          <button className="btn btn-outline" onClick={() => navigate("cart")}>
            <Icon name="file-text" size={15}/> ใบเสนอราคา ({cart.length})
          </button>
        </div>
      </div>

      <div className="catalog-layout">
        <aside className="card filter-card">
          <div className="filter-group">
            <h4><Icon name="filter" size={12} style={{display:"inline", marginRight:4}}/> หมวดหมู่</h4>
            {cats.map(c => (
              <label key={c.id} className="filter-item">
                <input type="radio" name="cat" checked={category === c.id} onChange={() => setCategory(c.id)} />
                <span>{c.th}</span>
                <span className="count">{c.count}</span>
              </label>
            ))}
          </div>
          <div className="filter-group">
            <h4>แบรนด์</h4>
            {BRANDS.map(b => (
              <label key={b} className="filter-item">
                <input type="checkbox" checked={brands.includes(b)} onChange={() => toggleBrand(b)} />
                <span>{b}</span>
              </label>
            ))}
          </div>
          <div className="filter-group">
            <h4>ราคา (สูงสุด)</h4>
            <input type="range" min="100" max="20000" step="100" value={priceRange} onChange={e => setPriceRange(parseInt(e.target.value))} style={{width:"100%", accentColor:"var(--navy-700)"}} />
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--ink-500)", fontFamily: "var(--font-en)" }}>
              <span>฿0</span>
              <span style={{fontWeight: 600, color: "var(--navy-700)"}}>฿{fmtInt(priceRange)}</span>
            </div>
          </div>
          <div className="filter-group">
            <h4>อื่นๆ</h4>
            <label className="filter-item">
              <input type="checkbox" checked={inStock} onChange={() => setInStock(!inStock)} />
              <span>มีสินค้าพร้อมส่ง</span>
            </label>
            <label className="filter-item">
              <input type="checkbox" checked={saleOnly} onChange={() => setSaleOnly(!saleOnly)} />
              <span>เฉพาะลดราคา</span>
            </label>
          </div>
        </aside>

        <div>
          <div className="toolbar">
            <span className="result-count">พบ <b>{filtered.length}</b> รายการ {query && <>สำหรับ "<b>{query}</b>"</>}</span>
            <div className="spacer"></div>
            {isDealer && (
              <span className="chip" style={{ background:"#fef3c7", color:"#b45309" }}>
                <Icon name="tag" size={12}/> Dealer · -15% Gold tier
              </span>
            )}
            <select value={sort} onChange={e => setSort(e.target.value)}>
              <option value="relevance">เรียง: ความเกี่ยวข้อง</option>
              <option value="priceLow">ราคา: ต่ำ → สูง</option>
              <option value="priceHigh">ราคา: สูง → ต่ำ</option>
              <option value="newest">ใหม่ล่าสุด</option>
              <option value="popular">ขายดี</option>
            </select>
            <div className="view-toggle">
              <button className={view === "grid" ? "active" : ""} onClick={() => setView("grid")}><Icon name="grid" size={14}/></button>
              <button className={view === "list" ? "active" : ""} onClick={() => setView("list")}><Icon name="list" size={14}/></button>
            </div>
          </div>

          {filtered.length === 0 ? (
            <div className="card empty-state">
              <Icon name="search" size={48} className="icon"/>
              <h3>ไม่พบสินค้าที่ค้นหา</h3>
              <p>ลองเปลี่ยนคำค้นหา หรือล้างตัวกรอง</p>
              <button className="btn btn-outline" onClick={() => { setQuery(""); setCategory("all"); setBrands([]); setSaleOnly(false); setInStock(false); setPriceRange(20000); }}>ล้างตัวกรอง</button>
            </div>
          ) : view === "grid" ? (
            <div className="product-grid">
              {filtered.map(p => (
                <ProductCard
                  key={p.id}
                  product={p}
                  onAdd={addToCart}
                  onView={(p) => navigate("product", { id: p.id })}
                  inCart={inCartIds.has(p.id)}
                  isDealer={isDealer}
                />
              ))}
            </div>
          ) : (
            <div className="card">
              {filtered.map((p, i) => (
                <div key={p.id} className="cart-line" style={{ borderBottom: i === filtered.length - 1 ? "none" : "1px solid var(--ink-200)", cursor: "pointer" }}
                  onClick={() => navigate("product", { id: p.id })}>
                  <div className="cart-line-img"><ProductImg product={p}/></div>
                  <div>
                    <div className="cart-line-sku">{p.sku} · {p.brand}</div>
                    <div className="cart-line-name">{p.th}</div>
                    <div className="muted small mt-8">{p.desc}</div>
                    <div className="cart-line-meta">
                      <span className={`product-stock ${p.stock > 20 ? "" : p.stock > 0 ? "low" : "out"}`}>
                        <Icon name={p.stock > 0 ? "check" : "x"} size={12}/>
                        {p.stock > 20 ? "พร้อมส่ง" : p.stock > 0 ? `เหลือ ${p.stock} ชิ้น` : "หมดชั่วคราว"}
                      </span>
                      <span className="muted small"><Icon name="star" size={11} style={{color:"#f59e0b"}}/> {p.rating} ({p.reviews})</span>
                    </div>
                  </div>
                  <div className="cart-line-right">
                    <span className="cart-line-price">฿{fmtMoney(isDealer ? p.dealerPrice : p.price)}</span>
                    {isDealer && <span className="tiny" style={{color: "var(--amber)"}}>Dealer -15%</span>}
                    <button className={"btn btn-sm " + (inCartIds.has(p.id) ? "btn-outline" : "btn-primary")} onClick={e => { e.stopPropagation(); addToCart(p); }}>
                      {inCartIds.has(p.id) ? <><Icon name="check" size={13}/> เพิ่มแล้ว</> : <><Icon name="plus" size={13}/> เพิ่ม</>}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CatalogPage });
