/* ============================================================
   FRUTA FRESCA — Catalog / Shop
   ============================================================ */
function FilterGroup({ title, children, defaultOpen = true }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ borderBottom: "1px solid var(--line)", paddingBlock: 16 }}>
      <button className="between" onClick={() => setOpen(!open)} style={{ width: "100%", background: "none",
        border: "none", padding: 0, fontWeight: 600, fontSize: 14.5, color: "var(--ink)" }}>
        {title}<Icon name="chevronD" size={17} style={{ transform: open ? "none" : "rotate(-90deg)", transition: ".2s" }} />
      </button>
      {open && <div style={{ marginTop: 14, display: "grid", gap: 10 }}>{children}</div>}
    </div>
  );
}
function CheckRow({ label, checked, onChange, count }) {
  return (
    <label className="row" style={{ gap: 10, cursor: "pointer", fontSize: 14 }}>
      <span onClick={(e) => { e.preventDefault(); onChange(!checked); }} style={{ width: 19, height: 19, borderRadius: 5,
        border: `1.5px solid ${checked ? "var(--green)" : "var(--border)"}`, background: checked ? "var(--green)" : "var(--paper)",
        display: "grid", placeItems: "center", flex: "none" }}>
        {checked && <Icon name="check" size={13} style={{ color: "#fff" }} stroke={3} />}
      </span>
      <span style={{ flex: 1 }}>{label}</span>
      {count != null && <span className="muted small">{count}</span>}
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} className="sr-only" />
    </label>
  );
}

function ShopScreen() {
  const rp = useApp().routeParams || {};
  const [cats, setCats] = useState(rp.cat ? [rp.cat] : []);
  const [origins, setOrigins] = useState([]);
  const [seasons, setSeasons] = useState([]);
  const [organic, setOrganic] = useState(false);
  const [maxPrice, setMaxPrice] = useState(1200);
  const [sort, setSort] = useState("relevance");
  const [sheet, setSheet] = useState(false);

  const allOrigins = [...new Set(FF.products.map((p) => p.origins[0]))];
  const allSeasons = ["In season", "Fresh stock", "Limited", "Pre-order"];

  let list = FF.products.filter((p) =>
    (!cats.length || cats.includes(p.cat)) &&
    (!origins.length || origins.includes(p.origins[0])) &&
    (!seasons.length || seasons.includes(p.season)) &&
    (!organic || p.organic) &&
    p.price <= maxPrice);
  if (sort === "low") list = [...list].sort((a, b) => a.price - b.price);
  if (sort === "high") list = [...list].sort((a, b) => b.price - a.price);
  if (sort === "rating") list = [...list].sort((a, b) => b.rating - a.rating);

  const toggle = (arr, set, v) => set(arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v]);
  const activeCount = cats.length + origins.length + seasons.length + (organic ? 1 : 0) + (maxPrice < 1200 ? 1 : 0);
  const clearAll = () => { setCats([]); setOrigins([]); setSeasons([]); setOrganic(false); setMaxPrice(1200); };

  const Rail = () => (
    <div>
      <div className="between" style={{ marginBottom: 4 }}>
        <span style={{ fontWeight: 600 }}>Filters</span>
        {activeCount > 0 && <button onClick={clearAll} className="small" style={{ background: "none", border: "none",
          color: "var(--green)", fontWeight: 600 }}>Clear all</button>}
      </div>
      <FilterGroup title="Category">
        {FF.categories.map((c) => <CheckRow key={c.key} label={c.label} checked={cats.includes(c.key)}
          onChange={() => toggle(cats, setCats, c.key)} count={FF.products.filter((p) => p.cat === c.key).length} />)}
      </FilterGroup>
      <FilterGroup title="Price range">
        <input type="range" min="100" max="1200" step="20" value={maxPrice}
          onChange={(e) => setMaxPrice(+e.target.value)} style={{ width: "100%", accentColor: "var(--green)" }} />
        <div className="between small muted"><span>₹100</span><span style={{ color: "var(--ink)", fontWeight: 600 }}>Up to {FF.rupee(maxPrice)}</span></div>
      </FilterGroup>
      <FilterGroup title="Origin">
        {allOrigins.map((o) => <CheckRow key={o} label={o} checked={origins.includes(o)}
          onChange={() => toggle(origins, setOrigins, o)} />)}
      </FilterGroup>
      <FilterGroup title="Season">
        {allSeasons.map((s) => <CheckRow key={s} label={s} checked={seasons.includes(s)}
          onChange={() => toggle(seasons, setSeasons, s)} />)}
      </FilterGroup>
      <FilterGroup title="More">
        <CheckRow label="Certified organic only" checked={organic} onChange={setOrganic} />
      </FilterGroup>
    </div>
  );

  return (
    <div data-screen-label="Shop" className="container" style={{ paddingBlock: 24 }}>
      <nav className="small muted" style={{ marginBottom: 12 }}>Home <span className="divider-dot"></span> Shop all</nav>
      <div className="between wrap" style={{ marginBottom: 20, alignItems: "flex-end" }}>
        <div>
          <h1 className="h2">{cats.length === 1 ? cats[0] : "Shop all fruit"}</h1>
          <p className="muted small" style={{ marginTop: 4 }}>{list.length} fresh picks · graded Class 1</p>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <button className="chip hide-desktop" onClick={() => setSheet(true)}>
            <Icon name="filter" size={15} /> Filters{activeCount > 0 ? ` · ${activeCount}` : ""}</button>
          <label className="row hide-mobile" style={{ gap: 8 }}>
            <span className="small muted">Sort</span>
            <select className="select" style={{ width: "auto", padding: "9px 12px" }} value={sort} onChange={(e) => setSort(e.target.value)}>
              <option value="relevance">Relevance</option>
              <option value="low">Price: low to high</option>
              <option value="high">Price: high to low</option>
              <option value="rating">Top rated</option>
            </select>
          </label>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 28 }} className="shop-layout">
        <aside className="hide-mobile" style={{ alignSelf: "start", position: "sticky", top: 88 }}><Rail /></aside>
        <div>
          {list.length === 0
            ? <div className="surface-card text-center" style={{ padding: 48 }}>
                <p className="muted">No fruit matches those filters.</p>
                <button className="btn btn--ghost btn--sm" onClick={clearAll} style={{ marginTop: 12 }}>Clear filters</button>
              </div>
            : <div className="pgrid">{list.map((p) => <ProductCard key={p.id} p={p} />)}</div>}
        </div>
      </div>

      {sheet && (
        <div onClick={() => setSheet(false)} style={{ position: "fixed", inset: 0, background: "rgba(28,42,33,.45)", zIndex: 200 }}>
          <div onClick={(e) => e.stopPropagation()} style={{ position: "absolute", bottom: 0, left: 0, right: 0,
            background: "var(--canvas)", borderRadius: "20px 20px 0 0", padding: 22, maxHeight: "85vh", overflowY: "auto",
            animation: "sheetUp .3s ease" }}>
            <div className="between" style={{ marginBottom: 8 }}>
              <h3 className="h3">Filters</h3>
              <button style={iconBtn} onClick={() => setSheet(false)} aria-label="Close"><Icon name="close" /></button>
            </div>
            <label className="field" style={{ marginBottom: 8 }}>
              <span className="label">Sort by</span>
              <select className="select" value={sort} onChange={(e) => setSort(e.target.value)}>
                <option value="relevance">Relevance</option><option value="low">Price: low to high</option>
                <option value="high">Price: high to low</option><option value="rating">Top rated</option>
              </select>
            </label>
            <Rail />
            <button className="btn btn--ink btn--block btn--lg" style={{ marginTop: 18 }} onClick={() => setSheet(false)}>
              Show {list.length} results</button>
          </div>
        </div>
      )}
    </div>
  );
}
Object.assign(window, { ShopScreen });
