// Karavi Studio · Shop / PLP (motion-refreshed)
const Shop = ({ goto, initialCat = "All", initialSub = null }) => {
  const { useState } = React;
  const products = window.KARAVI_PRODUCTS;
  const cats = window.KARAVI_CATS;

  const [cat, setCat] = useState(initialCat);
  const [sort, setSort] = useState("Featured");
  const [activeSubs, setActiveSubs] = useState(initialSub ? [initialSub] : []);
  const [sizeFilter, setSizeFilter] = useState([]);
  const [filterOpen, setFilterOpen] = useState(false);

  React.useEffect(() => {
    setCat(initialCat);
    setActiveSubs(initialSub ? [initialSub] : []);
  }, [initialCat, initialSub]);

  const allSubs = [...new Set(
    products
      .filter(p => cat === "All" || p.category === cat)
      .map(p => p.subcat)
      .filter(Boolean)
  )];

  const allSizes = [...new Set(
    products
      .filter(p => cat === "All" || p.category === cat)
      .flatMap(p => p.sizes)
  )].slice(0, 8);

  const toggleSub = (s) => setActiveSubs(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]);
  const toggleSize = (s) => setSizeFilter(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]);

  let list = cat === "All" ? products : products.filter(p => p.category === cat);
  if (activeSubs.length > 0) list = list.filter(p => activeSubs.includes(p.subcat));
  if (sizeFilter.length > 0) list = list.filter(p => p.sizes.some(s => sizeFilter.includes(s)));
  if (sort === "Price ↑") list = [...list].sort((a, b) => a.price - b.price);
  if (sort === "Price ↓") list = [...list].sort((a, b) => b.price - a.price);
  if (sort === "New") list = [...list].sort((a, b) => Number(b.new) - Number(a.new));

  const filterKey = `${cat}|${activeSubs.join(",")}|${sizeFilter.join(",")}|${sort}`;

  const Sidebar = () => (
    <Stagger as="div" staggerChildren={0.04} delayChildren={0.05}>
      <StaggerItem as="div" style={{ marginBottom: 32 }}>
        <Eyebrow style={{ marginBottom: 14 }}>Category</Eyebrow>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {cats.map(c => (
            <motion.button
              key={c}
              onClick={() => { setCat(c); setActiveSubs([]); }}
              whileHover={{ x: 2 }}
              transition={{ duration: 0.15 }}
              style={{
                background: "none", border: 0, cursor: "pointer", textAlign: "left",
                padding: "9px 0", fontSize: 14,
                color: cat === c ? "var(--fg-display)" : "var(--fg-2)",
                fontWeight: cat === c ? 500 : 400,
                borderBottom: cat === c ? "1px solid var(--karavi-ebony)" : "1px solid transparent",
                minHeight: 44, letterSpacing: ".02em",
              }}
            >{c}</motion.button>
          ))}
        </div>
      </StaggerItem>

      {allSubs.length > 0 && (
        <StaggerItem as="div" style={{ marginBottom: 32 }}>
          <Eyebrow style={{ marginBottom: 14 }}>Type</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {allSubs.map(s => (
              <label key={s} style={{
                display: "flex", alignItems: "center", gap: 10,
                cursor: "pointer", fontSize: 14, color: "var(--fg-1)", minHeight: 36,
              }}>
                <input
                  type="checkbox"
                  checked={activeSubs.includes(s)}
                  onChange={() => toggleSub(s)}
                  style={{ accentColor: "var(--karavi-ebony)", width: 16, height: 16, cursor: "pointer" }}
                />
                {s}
              </label>
            ))}
          </div>
        </StaggerItem>
      )}

      {allSizes.length > 0 && (
        <StaggerItem as="div" style={{ marginBottom: 32 }}>
          <Eyebrow style={{ marginBottom: 14 }}>Size</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {allSizes.map(s => (
              <label key={s} style={{
                display: "flex", alignItems: "center", gap: 10,
                cursor: "pointer", fontSize: 13, color: "var(--fg-1)", minHeight: 36,
              }}>
                <input
                  type="checkbox"
                  checked={sizeFilter.includes(s)}
                  onChange={() => toggleSize(s)}
                  style={{ accentColor: "var(--karavi-ebony)", width: 16, height: 16, cursor: "pointer" }}
                />
                {s}
              </label>
            ))}
          </div>
        </StaggerItem>
      )}

      {(activeSubs.length > 0 || sizeFilter.length > 0 || cat !== "All") && (
        <StaggerItem as="div">
          <motion.button
            onClick={() => { setCat("All"); setActiveSubs([]); setSizeFilter([]); }}
            whileHover={{ x: 2 }}
            style={{
              background: "none", border: 0, cursor: "pointer", textAlign: "left",
              fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase",
              color: "var(--fg-3)", borderBottom: "1px solid var(--line-medium)",
              padding: "2px 0", minHeight: 36,
            }}
          >Clear all filters</motion.button>
        </StaggerItem>
      )}
    </Stagger>
  );

  return (
    <main>
      {/* ── PAGE HEADER ──────────────────────── */}
      <Section style={{ paddingTop: 56, paddingBottom: 28 }}>
        <Reveal>
          <Eyebrow>Shop · {list.length} {list.length === 1 ? "piece" : "pieces"}</Eyebrow>
        </Reveal>
        <Reveal delay={0.1}>
          <h1 style={{
            fontFamily: "var(--font-display)", fontWeight: 300,
            fontSize: "clamp(52px, 6.5vw, 88px)", lineHeight: 1,
            letterSpacing: "-0.015em", marginTop: 8,
          }}>
            {cat === "All" ? "Everything." : (
              <span>{cat} <em style={{ fontWeight: 400 }}>collection.</em></span>
            )}
          </h1>
        </Reveal>
        <Reveal delay={0.2}>
          <p style={{ maxWidth: 540, marginTop: 14, color: "var(--fg-2)", fontSize: 15, lineHeight: 1.6 }}>
            Small batches, named makers, natural fibres. Pieces ship in 5–7 days from our Jaipur studio.
          </p>
        </Reveal>
      </Section>

      {/* ── STICKY SORT BAR ──────────────────── */}
      <Section style={{
        borderTop: "1px solid var(--line-soft)", borderBottom: "1px solid var(--line-soft)",
        padding: "16px 40px", display: "flex", alignItems: "center", gap: 14,
        justifyContent: "space-between",
        position: "sticky", top: 64, zIndex: 20,
        background: "rgba(249,236,217,.92)", backdropFilter: "blur(10px)",
        WebkitBackdropFilter: "blur(10px)",
      }}>
        <button
          className="k-mobile-only k-filter-mobile-btn"
          onClick={() => setFilterOpen(true)}
          style={{
            display: "none", alignItems: "center", gap: 8,
            background: "none", border: "1px solid var(--line-medium)", borderRadius: 999,
            padding: "9px 18px", cursor: "pointer", fontSize: 13, minHeight: 44,
          }}
        >
          <Icon name="filter" size={14}/>
          Filters {(activeSubs.length + sizeFilter.length) > 0 && `(${activeSubs.length + sizeFilter.length})`}
        </button>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", flex: 1 }}>
          <AnimatePresence>
            {cat !== "All" && (
              <motion.div
                key={`cat-${cat}`}
                initial={{ opacity: 0, scale: 0.85 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.85 }}
                transition={springs.pop}
              >
                <Chip active onClick={() => setCat("All")}>{cat} ×</Chip>
              </motion.div>
            )}
            {activeSubs.map(s => (
              <motion.div
                key={`sub-${s}`}
                initial={{ opacity: 0, scale: 0.85 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.85 }}
                transition={springs.pop}
              >
                <Chip active onClick={() => toggleSub(s)}>{s} ×</Chip>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>

        <div style={{ display: "flex", gap: 12, alignItems: "center", flexShrink: 0 }}>
          <Eyebrow>Sort</Eyebrow>
          <select
            value={sort}
            onChange={e => setSort(e.target.value)}
            aria-label="Sort products"
            style={{
              background: "transparent", border: 0, fontFamily: "var(--font-body)",
              fontSize: 14, color: "var(--fg-1)", cursor: "pointer", outline: "none", minHeight: 44,
            }}
          >
            <option>Featured</option>
            <option>New</option>
            <option>Price ↑</option>
            <option>Price ↓</option>
          </select>
        </div>
      </Section>

      {/* ── LAYOUT ───────────────────────────── */}
      <Section style={{ marginTop: 40, marginBottom: 8 }}>
        <div className="k-shop-layout">
          <aside className="k-sidebar k-desktop-only" style={{ display: "block" }}>
            <Sidebar/>
          </aside>

          <div>
            <AnimatePresence mode="wait">
              {list.length > 0 ? (
                <Stagger key={filterKey} className="k-grid-3" style={{ rowGap: 56 }}>
                  {list.map(p => (
                    <StaggerItem key={p.id}>
                      <ProductCard p={p} onClick={() => goto(`product:${p.id}`)}/>
                    </StaggerItem>
                  ))}
                </Stagger>
              ) : (
                <motion.div
                  key="empty"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.4 }}
                  style={{ padding: "80px 0", textAlign: "center" }}
                >
                  <Eyebrow style={{ justifyContent: "center", display: "flex" }}>No results</Eyebrow>
                  <div style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 26, marginTop: 12, color: "var(--fg-display)" }}>
                    Try adjusting your filters.
                  </div>
                  <motion.button
                    onClick={() => { setCat("All"); setActiveSubs([]); setSizeFilter([]); }}
                    whileHover={{ y: -2 }}
                    style={{
                      marginTop: 24, background: "none", border: 0, cursor: "pointer",
                      fontSize: 12, letterSpacing: ".22em", textTransform: "uppercase",
                      color: "var(--fg-2)", borderBottom: "1px solid var(--fg-2)", padding: "2px 0",
                    }}
                  >Clear filters</motion.button>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
      </Section>

      {/* ── BRAND PULL-QUOTE ─────────────────── */}
      <Section style={{ marginTop: 96, textAlign: "center" }}>
        <KilimDivider/>
        <Reveal delay={0.1}>
          <div style={{
            fontFamily: "var(--font-display)", fontStyle: "italic", fontWeight: 400,
            fontSize: "clamp(22px, 3vw, 38px)", color: "var(--fg-display)",
            maxWidth: 760, margin: "48px auto 0", lineHeight: 1.3,
          }}>
            "We name every maker on the label, in the hope that the next room will know whose hands made it."
          </div>
        </Reveal>
        <Reveal delay={0.25}>
          <Eyebrow style={{ marginTop: 18, justifyContent: "center", display: "flex" }}>— from the studio journal</Eyebrow>
        </Reveal>
      </Section>

      {/* ── Mobile filter drawer (motion) ────── */}
      <AnimatePresence>
        {filterOpen && (
          <>
            <motion.div
              key="filter-scrim"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setFilterOpen(false)}
              style={{ position: "fixed", inset: 0, background: "rgba(45,40,30,.32)", zIndex: 140 }}
            />
            <motion.div
              key="filter-drawer"
              initial={{ y: "100%" }}
              animate={{ y: 0 }}
              exit={{ y: "100%" }}
              transition={springs.drawer}
              role="dialog"
              aria-label="Filters"
              style={{
                position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 150,
                background: "var(--karavi-cream)", borderRadius: "22px 22px 0 0",
                padding: 24, boxShadow: "var(--shadow-lg)",
                maxHeight: "82vh", overflowY: "auto",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--fg-display)" }}>Filters</div>
                <motion.button
                  onClick={() => setFilterOpen(false)}
                  whileHover={{ rotate: 90 }}
                  transition={{ duration: 0.25 }}
                  style={{ background: "none", border: 0, cursor: "pointer", minHeight: 44 }}
                >
                  <Icon name="close" size={20}/>
                </motion.button>
              </div>
              <Sidebar/>
              <Button full style={{ marginTop: 16 }} onClick={() => setFilterOpen(false)}>
                Show {list.length} {list.length === 1 ? "result" : "results"}
              </Button>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </main>
  );
};
window.Shop = Shop;
