// Products.jsx, Product marketplace (catalog + category sidebar + filters)

const ProductsPage = ({ onNavigate, onRFQ }) => {
 const vp = useViewport();
 const [cat, setCat] = useState("all");
 const [origin, setOrigin] = useState("any");
 const [view, setView] = useState("grid");
 const [filtersOpen, setFiltersOpen] = useState(false);

 const filtered = PRODUCTS.filter(p =>
  (cat === "all" || p.category === cat) &&
  (origin === "any" || p.origin === origin)
 );

 const showSidebarInline = vp.isDesktop;

 const filterContent = (
  <>
   <FilterGroupP label="Categories">
    <button onClick={() => setCat("all")}
     style={catRowStyle(cat === "all")}>
     <span>All products</span>
     <Mono style={{ fontSize: 12, color: "var(--color-fg-muted)" }}>{PRODUCTS.length}</Mono>
    </button>
    {PRODUCT_CATEGORIES.map(c => (
     <button key={c.id} onClick={() => setCat(c.id)} style={catRowStyle(cat === c.id)}>
      <span>{c.label}</span>
      <Mono style={{ fontSize: 12, color: "var(--color-fg-muted)" }}>{c.count}</Mono>
     </button>
    ))}
   </FilterGroupP>

   <FilterGroupP label="Origin">
    {[
     { id: "any", label: "Any" },
     { id: "vn", label: "Vietnam" },
     { id: "jp", label: "Japan" },
    ].map(o => (
     <label key={o.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 0", fontSize: 14, cursor: "pointer" }}>
      <input type="radio" checked={origin === o.id} onChange={() => setOrigin(o.id)} style={{ accentColor: "var(--jv-navy-800)" }}/>
      {o.id !== "any" && <img src={`assets/flag-${o.id}.svg`} width="16" height="12"/>}
      <span style={{ color: origin === o.id ? "var(--jv-navy-800)" : "var(--color-fg-body)", fontWeight: origin === o.id ? 500 : 400 }}>{o.label}</span>
     </label>
    ))}
   </FilterGroupP>

   <FilterGroupP label="Certifications">
    {["HACCP", "FSSC 22000", "BRCGS", "ASC CoC", "MSC CoC", "JAS Organic", "Halal"].map(c => (
     <label key={c} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 0", fontSize: 14, cursor: "pointer" }}>
      <input type="checkbox" style={{ accentColor: "var(--jv-navy-800)" }}/>
      <CertTag>{c}</CertTag>
     </label>
    ))}
   </FilterGroupP>

   <FilterGroupP label="MOQ ceiling">
    {["≤ 500 kg", "≤ 1 t", "≤ 5 t", "Any"].map(c => (
     <label key={c} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 0", fontSize: 14, cursor: "pointer" }}>
      <input type="radio" name="moq-prod" style={{ accentColor: "var(--jv-navy-800)" }}/>
      {c}
     </label>
    ))}
   </FilterGroupP>
  </>
 );

 return (
  <div>
   {/* PAGE HEADER */}
   <section style={{ padding: "32px var(--pad-x) 24px", borderBottom: "1px solid var(--color-border)" }}>
    <div style={{ maxWidth: 1280, margin: "0 auto" }}>
     <div style={{ fontSize: 12, color: "var(--color-fg-muted)", display: "flex", gap: 6, marginBottom: 12 }}>
      <a href="#" onClick={e => { e.preventDefault(); onNavigate("home"); }} style={{ color: "var(--color-fg-muted)", border: 0 }}>Home</a>
      <span>/</span><span style={{ color: "var(--color-fg)" }}>Products</span>
     </div>
     <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
      <div>
       <h1 style={{ fontSize: vp.isMobile ? 26 : 32, lineHeight: 1.2, letterSpacing: "-0.015em", color: "var(--jv-navy-800)" }}>Products</h1>
       <div style={{ marginTop: 6, fontSize: 14, color: "var(--color-fg-muted)" }}>
        <Mono style={{ color: "var(--color-fg)" }}>{filtered.length}</Mono> of <Mono>{PRODUCTS.length}</Mono> products · 1,240 verified suppliers
       </div>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
       {!showSidebarInline && (
        <Button variant="secondary" size="sm" leading="filter" onClick={() => setFiltersOpen(true)}>Filters</Button>
       )}
       <Button variant={view === "grid" ? "secondary" : "ghost"} size="sm" onClick={() => setView("grid")}>Grid</Button>
       <Button variant={view === "table" ? "secondary" : "ghost"} size="sm" onClick={() => setView("table")}>Table</Button>
       <Button variant="primary" size="sm" onClick={onRFQ}>Post an RFQ</Button>
      </div>
     </div>
    </div>
   </section>

   <div style={{ maxWidth: 1280, margin: "0 auto", padding: "32px var(--pad-x)", display: "grid", gridTemplateColumns: showSidebarInline ? "240px 1fr" : "1fr", gap: 32 }}>
    {showSidebarInline && (
     <aside style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      {filterContent}
     </aside>
    )}

    <main style={{ minWidth: 0 }}>
     {view === "grid" ? (
      <div style={{ display: "grid", gridTemplateColumns: vp.isMobile ? "repeat(2, 1fr)" : "repeat(auto-fill, minmax(220px, 1fr))", gap: vp.isMobile ? 12 : 16 }}>
       {filtered.map(p => <ProductCard key={p.id} product={p} onNavigate={onNavigate} onRFQ={onRFQ}/>)}
      </div>
     ) : (
      <ProductsTable rows={filtered} onNavigate={onNavigate} onRFQ={onRFQ}/>
     )}
    </main>
   </div>

   {!showSidebarInline && (
    <>
     <div className="jv-drawer-scrim" data-open={filtersOpen ? "true" : "false"} onClick={() => setFiltersOpen(false)}/>
     <aside className="jv-drawer" data-open={filtersOpen ? "true" : "false"}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px", borderBottom: "1px solid var(--color-border)" }}>
       <div style={{ fontSize: 16, fontWeight: 600, color: "var(--jv-navy-800)" }}>Filters</div>
       <button onClick={() => setFiltersOpen(false)} aria-label="Close filters" style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--color-fg-muted)" }}>
        <Icon name="x" size={20}/>
       </button>
      </div>
      <div style={{ padding: "20px 22px", display: "flex", flexDirection: "column", gap: 28, overflowY: "auto", flex: 1 }}>
       {filterContent}
      </div>
      <div style={{ padding: "16px 22px", borderTop: "1px solid var(--color-border)" }}>
       <Button variant="primary" size="md" onClick={() => setFiltersOpen(false)} style={{ width: "100%", justifyContent: "center" }}>
        Show {filtered.length} products
       </Button>
      </div>
     </aside>
    </>
   )}
  </div>
 );
};

const catRowStyle = (active) => ({
 display: "flex", justifyContent: "space-between", alignItems: "center",
 padding: "8px 10px", border: 0, background: active ? "var(--jv-navy-50)" : "transparent",
 borderRadius: 4, fontSize: 14, fontFamily: "var(--font-sans)",
 color: active ? "var(--jv-navy-800)" : "var(--color-fg-body)",
 fontWeight: active ? 500 : 400, cursor: "pointer", textAlign: "left", width: "100%",
});

const FilterGroupP = ({ label, children }) => (
 <div>
  <Eyebrow style={{ paddingBottom: 8, borderBottom: "1px solid var(--color-border)", marginBottom: 4 }}>{label}</Eyebrow>
  {children}
 </div>
);

const ProductCard = ({ product: p, onNavigate, onRFQ }) => {
 const supplier = SUPPLIERS.find(s => s.id === p.supplier);
 const [hover, setHover] = useState(false);
 return (
  <div
   onMouseEnter={() => setHover(true)}
   onMouseLeave={() => setHover(false)}
   onClick={() => onNavigate("product-detail", p.id)}
   style={{
    background: "#fff",
    border: `1px solid ${hover ? "var(--color-border-strong)" : "var(--color-border)"}`,
    borderRadius: 6,
    overflow: "hidden",
    display: "flex",
    flexDirection: "column",
    boxShadow: hover ? "var(--shadow-1)" : "none",
    transition: "border-color 120ms var(--ease-standard), box-shadow 120ms var(--ease-standard)",
    cursor: "pointer",
   }}>
   {/* Image: aspect-ratio keeps consistent shape regardless of card width */}
   <div style={{ position: "relative", aspectRatio: "4 / 3", flexShrink: 0, background: "var(--jv-ink-100)", overflow: "hidden" }}>
    <img
     src={p.img} alt={p.name}
     style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", display: "block" }}
     onError={e => { e.currentTarget.style.opacity = 0; }}
    />
    <div style={{ position: "absolute", top: 8, left: 8 }}>
     <span style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 7px", background: "rgba(255,255,255,0.92)", borderRadius: 4, fontSize: 11, fontWeight: 500, color: "var(--jv-navy-800)", backdropFilter: "blur(4px)" }}>
      <img src={`assets/flag-${p.origin}.svg`} width="12" height="9" alt={p.origin}/>
      {p.origin.toUpperCase()}
     </span>
    </div>
   </div>

   <div style={{ padding: "12px 14px 14px", display: "flex", flexDirection: "column", gap: 6 }}>
    <div style={{
     fontSize: 13, fontWeight: 600, color: "var(--jv-navy-800)", lineHeight: 1.4,
     height: "calc(13px * 1.4 * 2)",
     display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden",
    }}>{p.name}</div>

    <a
     href="#"
     onClick={e => { e.preventDefault(); e.stopPropagation(); onNavigate("profile", p.supplier); }}
     style={{ fontSize: 12, color: "var(--color-fg-muted)", border: 0, display: "block",
      whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", height: 16 }}>
     {supplier ? supplier.name : p.supplier}
    </a>

    <div style={{ display: "flex", gap: 4, height: 20, overflow: "hidden", alignItems: "center", flexShrink: 0 }}>
     {p.certs.slice(0, 2).map(c => <CertTag key={c}>{c}</CertTag>)}
    </div>

    <div style={{ paddingTop: 10, marginTop: 2, borderTop: "1px solid var(--color-divider)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
     <div>
      <div style={{ fontSize: 10, color: "var(--color-fg-muted)", textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600, marginBottom: 1 }}>MOQ</div>
      <Mono style={{ fontSize: 12, color: "var(--color-fg)" }}>{p.moq}</Mono>
     </div>
     <Mono style={{ fontSize: 13, fontWeight: 600, color: "var(--jv-navy-800)" }}>{p.price}</Mono>
    </div>
   </div>
  </div>
 );
};

const ProductsTable = ({ rows, onNavigate, onRFQ }) => (
 <div style={{ border: "1px solid var(--color-border)", borderRadius: 6, overflow: "hidden" }}>
  <div className="jv-x-scroll">
   <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, minWidth: 760 }}>
    <thead style={{ background: "var(--jv-ink-50)" }}>
     <tr style={{ textAlign: "left", color: "var(--color-fg-muted)", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase", fontWeight: 500 }}>
      <th style={{ padding: "10px 14px" }}>Product</th>
      <th style={{ padding: "10px 14px" }}>Origin</th>
      <th style={{ padding: "10px 14px" }}>Supplier</th>
      <th style={{ padding: "10px 14px" }}>Certs</th>
      <th style={{ padding: "10px 14px", textAlign: "right" }}>MOQ</th>
      <th style={{ padding: "10px 14px", textAlign: "right" }}>FOB / Unit</th>
      <th style={{ padding: "10px 14px" }}/>
     </tr>
    </thead>
    <tbody>
     {rows.map((p, i) => {
      const sup = SUPPLIERS.find(s => s.id === p.supplier);
      return (
       <tr key={p.id}
        onClick={() => onNavigate("product-detail", p.id)}
        style={{ borderTop: "1px solid var(--color-divider)", background: i % 2 ? "var(--jv-ink-50)" : "#fff", cursor: "pointer" }}>
        <td style={{ padding: "12px 14px", color: "var(--jv-navy-800)", fontWeight: 500 }}>{p.name}</td>
        <td style={{ padding: "12px 14px" }}><CountryChip country={p.origin}/></td>
        <td style={{ padding: "12px 14px", color: "var(--color-fg-body)" }}>
         <a href="#" onClick={e => { e.preventDefault(); e.stopPropagation(); onNavigate("profile", p.supplier); }}
          style={{ color: "var(--color-fg-body)", border: 0 }}>
          {sup ? sup.name : p.supplier}
         </a>
        </td>
        <td style={{ padding: "12px 14px" }}>{p.certs.map(c => <CertTag key={c}>{c}</CertTag>)}</td>
        <td style={{ padding: "12px 14px", textAlign: "right" }}><Mono>{p.moq}</Mono></td>
        <td style={{ padding: "12px 14px", textAlign: "right" }}><Mono style={{ color: "var(--jv-navy-800)" }}>{p.price}</Mono></td>
        <td style={{ padding: "12px 14px", textAlign: "right" }}><Button variant="ghost" size="sm" onClick={e => { e.stopPropagation(); onRFQ(); }}>Quote</Button></td>
       </tr>
      );
     })}
    </tbody>
   </table>
  </div>
 </div>
);

Object.assign(window, { ProductsPage });
