/* ============================================================
   RACK & BOX — Shop / Collections + Product Detail Page
   ============================================================ */

/* ---------------- SHOP ---------------- */
function FilterGroup({ title, children, open = true }) {
  const [o, setO] = useState(open);
  return (
    <div className="fgroup">
      <button className="fgroup-h" onClick={() => setO(!o)}>
        <span>{title}</span><Icon name={o ? "minus" : "plus"} size={16} />
      </button>
      {o && <div className="fgroup-body">{children}</div>}
    </div>
  );
}

function ShopPage({ route, onNav }) {
  const { addToCart, toggleWish, wishlist } = useContext(RBCtx);
  const p0 = route.params || {};
  const [cat, setCat] = useState(p0.cat || null);
  const [audience, setAudience] = useState(p0.audience || null);
  const [maxPrice, setMaxPrice] = useState(1000000);
  const [sort, setSort] = useState("featured");
  const [mobFilters, setMobFilters] = useState(false);

  useEffect(() => {
    const p = route.params || {};
    setCat(p.cat || null); setAudience(p.audience || null);
  }, [route]);

  let list = RB.PRODUCTS.filter((p) =>
    (!cat || p.cat === cat) &&
    (!audience || p.audience === audience) &&
    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 === "new") list = [...list].sort((a, b) => (b.badge === "New" ? 1 : 0) - (a.badge === "New" ? 1 : 0));

  const clearAll = () => { setCat(null); setAudience(null); setMaxPrice(1000000); };
  const heading = cat ? cat : audience === "Kids" ? "Kids Matching" : "All Products";
  const activeCount = [cat, audience].filter(Boolean).length;

  const Filters = () => (
    <>
      <FilterGroup title="Category">
        <button className={"fcheck" + (!cat ? " on" : "")} onClick={() => setCat(null)}>All categories</button>
        {RB.CATEGORIES.map((c) => (
          <button key={c} className={"fcheck" + (cat === c ? " on" : "")} onClick={() => setCat(c)}>{c}</button>
        ))}
      </FilterGroup>
      <FilterGroup title="Price">
        <div className="price-range">
          <input type="range" min="80000" max="1000000" step="10000" value={maxPrice} onChange={(e) => setMaxPrice(+e.target.value)} />
          <div className="spread" style={{ fontSize: 13, color: "var(--ink-soft)" }}>
            <span>Up to</span><Price ngn={maxPrice} />
          </div>
        </div>
      </FilterGroup>
    </>
  );

  return (
    <div className="fade-page shop-page">
      <div className="shop-hero">
        <div className="wrap-wide">
          <h1 className="serif shop-title">{heading}</h1>
          <p className="shop-sub">{list.length} pieces · Made between Lagos &amp; London · Worldwide shipping</p>
        </div>
      </div>

      <div className="wrap-wide shop-body">
        <aside className="shop-filters">
          <div className="spread" style={{ marginBottom: 8 }}>
            <span className="eyebrow muted">Refine</span>
            {activeCount > 0 && <button className="clear-btn" onClick={clearAll}>Clear all</button>}
          </div>
          <Filters />
          <div className="filter-help">
            <Icon name="ruler" size={20} />
            <div><strong>Not sure on size?</strong><span>Try our Fit Finder on any product.</span></div>
          </div>
        </aside>

        <div className="shop-main">
          <div className="shop-toolbar">
            <div className="active-chips">
              {cat && <button className="achip" onClick={() => setCat(null)}>{cat} <Icon name="close" size={13} /></button>}
              {audience && <button className="achip" onClick={() => setAudience(null)}>{audience} <Icon name="close" size={13} /></button>}
            </div>
            <div className="row" style={{ gap: 12 }}>
              <button className="mob-filter-btn" onClick={() => setMobFilters(true)}><Icon name="menu" size={16} /> Filters{activeCount ? ` (${activeCount})` : ""}</button>
              <div className="sort-wrap">
                <label>Sort</label>
                <select className="sort-select" value={sort} onChange={(e) => setSort(e.target.value)}>
                  <option value="featured">Featured</option>
                  <option value="new">Newest</option>
                  <option value="low">Price: Low to High</option>
                  <option value="high">Price: High to Low</option>
                </select>
              </div>
            </div>
          </div>

          {list.length === 0 ? (
            <div className="shop-empty">
              <p className="serif" style={{ fontSize: 28 }}>No pieces match those filters.</p>
              <Btn variant="ghost" arrow={false} onClick={clearAll}>Clear filters</Btn>
            </div>
          ) : (
            <div className="product-grid shop-grid">
              {list.map((p, i) => (
                <Reveal key={p.id} delay={(i % 4) + 1}>
                  <ProductCard p={p} onNav={onNav} onAdd={addToCart} wished={wishlist.includes(p.id)} onWish={toggleWish} />
                </Reveal>
              ))}
            </div>
          )}

          <div className="shop-editorial">
            <div className="zoomable" style={{ overflow: "hidden", borderRadius: "var(--radius)" }}><Ph label="EDIT · STYLED LOOK" ratio="wide" /></div>
            <div className="shop-editorial-body">
              <Eyebrow line>Styling note</Eyebrow>
              <h3 className="serif" style={{ fontSize: 30, fontWeight: 500, margin: "12px 0 14px" }}>How to wear it</h3>
              <p style={{ color: "var(--ink-soft)" }}>Pair an appliqué kaftan with gold accessories for daytime ease, or reach for an embellished occasion piece for evenings that call for more. Send us an enquiry and we can help you build the look.</p>
              <button className="link-arrow" style={{ marginTop: 18 }} onClick={() => onNav("shop", {})}>Browse the collection</button>
            </div>
          </div>
        </div>
      </div>

      {mobFilters && (
        <div className="filter-drawer-wrap">
          <div className="scrim show" onClick={() => setMobFilters(false)} />
          <div className="filter-drawer">
            <div className="spread" style={{ marginBottom: 20 }}>
              <span className="serif" style={{ fontSize: 24 }}>Filters</span>
              <button className="ic-btn" onClick={() => setMobFilters(false)}><Icon name="close" /></button>
            </div>
            <Filters />
            <Btn block style={{ marginTop: 20 }} arrow={false} onClick={() => setMobFilters(false)}>Show {list.length} results</Btn>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------------- SIZE GUIDE MODAL ---------------- */
function SizeGuide({ onClose, gender }) {
  const rows = gender === "Kids"
    ? [["2-3Y", "22\"", "20\"", "38\""], ["4-5Y", "23\"", "21\"", "42\""], ["6-7Y", "25\"", "22\"", "46\""], ["8-9Y", "27\"", "24\"", "50\""], ["10-11Y", "29\"", "26\"", "54\""]]
    : [["UK 6", "31\"", "24\"", "34\""], ["UK 8", "33\"", "26\"", "36\""], ["UK 10", "35\"", "28\"", "38\""], ["UK 12", "37\"", "30\"", "40\""], ["UK 14", "39\"", "32\"", "42\""]];
  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="spread" style={{ marginBottom: 18 }}>
          <div><Eyebrow>Size &amp; Fit</Eyebrow><h3 className="serif" style={{ fontSize: 28, marginTop: 6 }}>Size guide</h3></div>
          <button className="ic-btn" onClick={onClose}><Icon name="close" /></button>
        </div>
        <table className="size-table">
          <thead><tr><th>Size</th><th>Chest</th><th>Waist</th><th>Length</th></tr></thead>
          <tbody>{rows.map((r) => <tr key={r[0]}><td>{r[0]}</td><td>{r[1]}</td><td>{r[2]}</td><td>{r[3]}</td></tr>)}</tbody>
        </table>
        <p style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 16 }}>Measurements are a guide. For agbada and bespoke pieces we recommend a virtual fitting for an exact cut.</p>
      </div>
    </div>
  );
}

/* ---------------- FIT FINDER ---------------- */
function FitFinder({ sizes, onPick }) {
  const [step, setStep] = useState(0);
  const [h, setH] = useState(""); const [w, setW] = useState(""); const [fit, setFit] = useState("Regular");
  const result = sizes[Math.min(sizes.length - 1, Math.max(0, (fit === "Relaxed" ? 1 : 0) + (parseInt(w) > 85 ? 3 : parseInt(w) > 75 ? 2 : 1)))];
  return (
    <div className="fitfinder">
      {step === 0 && (
        <div className="ff-step">
          <Icon name="ruler" size={24} />
          <div><strong>Find your perfect fit</strong><span>Answer 3 quick questions for a size recommendation.</span></div>
          <button className="ff-go" onClick={() => setStep(1)}>Start <Icon name="arrow" size={15} /></button>
        </div>
      )}
      {step === 1 && (
        <div className="ff-q">
          <label>Your height (cm)</label>
          <input className="input" type="number" placeholder="e.g. 178" value={h} onChange={(e) => setH(e.target.value)} />
          <label style={{ marginTop: 12 }}>Your weight (kg)</label>
          <input className="input" type="number" placeholder="e.g. 78" value={w} onChange={(e) => setW(e.target.value)} />
          <div className="row" style={{ gap: 8, marginTop: 14, flexWrap: "wrap" }}>
            {["Slim", "Regular", "Relaxed"].map((f) => <button key={f} className={"chip" + (fit === f ? " active" : "")} onClick={() => setFit(f)}>{f}</button>)}
          </div>
          <Btn block arrow={false} style={{ marginTop: 16 }} onClick={() => setStep(2)}>See my size</Btn>
        </div>
      )}
      {step === 2 && (
        <div className="ff-result">
          <span className="mono">Recommended</span>
          <span className="serif" style={{ fontSize: 44 }}>{result}</span>
          <p>Based on a {fit.toLowerCase()} fit. You can adjust at checkout.</p>
          <div className="row" style={{ gap: 10 }}>
            <Btn arrow={false} onClick={() => onPick(result)}>Select {result}</Btn>
            <button className="link-arrow" onClick={() => setStep(1)}>Redo</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------------- PDP ---------------- */
function ProductPage({ route, onNav }) {
  const { addToCart, toggleWish, wishlist, openCart } = useContext(RBCtx);
  const p = RB.byId(route.params.id) || RB.PRODUCTS[0];
  const [size, setSize] = useState(null);
  const [color, setColor] = useState(p.colors[0]);
  const [qty, setQty] = useState(1);
  const [activeImg, setActiveImg] = useState(0);
  const [acc, setAcc] = useState("details");
  const [showSize, setShowSize] = useState(false);
  const [showFit, setShowFit] = useState(false);
  const [err, setErr] = useState(false);

  useEffect(() => {
    setSize(null); setColor(p.colors[0]); setQty(1); setActiveImg(0); setShowFit(false);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [route.params.id]);

  const imgs = [p.label, "DETAIL · FABRIC", "BACK · " + p.cat.toUpperCase(), "STYLED · LOOK"];
  const add = () => {
    if (!size) { setErr(true); return; }
    addToCart(p, { size, color: color.name, qty });
    openCart();
  };
  const look = RB.completeLook(p);
  const rel = RB.related(p, 4);
  return (
    <div className="fade-page pdp">
      <div className="wrap-wide pdp-grid">
        {/* gallery */}
        <div className="pdp-gallery">
          <div className="pdp-thumbs">
            {imgs.map((im, i) => (
              <button key={i} className={"pdp-thumb" + (activeImg === i ? " on" : "")} onClick={() => setActiveImg(i)}>
                <Ph label={im} ratio="portrait" />
              </button>
            ))}
          </div>
          <div className="pdp-main-img zoomable">
            {p.badge && <span className="pcard-tag" style={{ top: 18, left: 18 }}>{p.badge}</span>}
            <Ph label={imgs[activeImg]} ratio="tall" />
          </div>
        </div>

        {/* info */}
        <div className="pdp-info">
          <Eyebrow>{p.cat}{p.audience === "Kids" ? " · Kids" : ""}</Eyebrow>
          <h1 className="serif pdp-title">{p.name}</h1>
          <div className="row" style={{ gap: 14, marginBottom: 16 }}>
            <Stars value={5} size={15} />
          </div>
          <div className="pdp-price"><Price ngn={p.price} old={p.oldPrice} /></div>
          <p className="pdp-blurb">{p.blurb}</p>

          <div className="pdp-opt">
            <div className="spread"><span className="opt-label">Colour — {color.name}</span></div>
            <div className="row" style={{ gap: 10, marginTop: 10 }}>
              {p.colors.map((c) => (
                <button key={c.name} className={"color-dot" + (color.name === c.name ? " on" : "")} style={{ background: c.hex }} onClick={() => setColor(c)} title={c.name} />
              ))}
            </div>
          </div>

          <div className="pdp-opt">
            <div className="spread">
              <span className="opt-label">Size{size ? ` — ${size}` : ""}</span>
              <button className="opt-link" onClick={() => setShowSize(true)}>Size guide</button>
            </div>
            <div className={"size-row" + (err ? " err" : "")} style={{ marginTop: 10 }}>
              {p.sizes.map((s) => (
                <button key={s} className={"size-btn" + (size === s ? " on" : "")} onClick={() => { setSize(s); setErr(false); }}>{s}</button>
              ))}
            </div>
            {err && <span className="size-err">Please select a size</span>}
            {p.audience !== "Kids" && (
              <>
                <button className="opt-link fit-toggle" onClick={() => setShowFit(!showFit)}><Icon name="ruler" size={15} /> {showFit ? "Hide" : "Use"} Fit Finder</button>
                {showFit && <FitFinder sizes={p.sizes} onPick={(s) => { setSize(s); setShowFit(false); setErr(false); }} />}
              </>
            )}
          </div>

          <div className="pdp-buy">
            <div className="qty">
              <button onClick={() => setQty(Math.max(1, qty - 1))}><Icon name="minus" size={15} /></button>
              <span>{qty}</span>
              <button onClick={() => setQty(qty + 1)}><Icon name="plus" size={15} /></button>
            </div>
            <Btn block arrow={false} onClick={add}>Add to bag — <Price ngn={p.price * qty} /></Btn>
            <button className={"pdp-wish" + (wishlist.includes(p.id) ? " on" : "")} onClick={() => toggleWish(p.id)} aria-label="Wishlist">
              <Icon name={wishlist.includes(p.id) ? "star-f" : "heart"} size={20} />
            </button>
          </div>
          <button className="pdp-bespoke" onClick={() => onNav("custom", {})}>
            <Icon name="scissors" size={18} /> Want it customised? <strong>Send an enquiry →</strong>
          </button>

          <div className="pdp-assure">
            {[["truck", "Nationwide delivery"]].map(([ic, t]) => (
              <div key={t} className="assure-item"><Icon name={ic} size={18} /><span>{t}</span></div>
            ))}
          </div>

          {/* accordions */}
          <div className="pdp-acc">
            {[
              ["details", "Details", <ul className="acc-list"><li>{p.blurb}</li><li>Made to order and finished by hand</li></ul>],
              ["fabric", "Fabric & Care", <div><p style={{ marginBottom: 10 }}><strong>{p.fabric}</strong></p><p style={{ color: "var(--ink-soft)" }}>Dry clean only. Store on a padded hanger away from direct sunlight. Steam lightly to refresh between wears.</p></div>],
              ["shipping", "Shipping & Returns", <div><p style={{ marginBottom: 8 }}>Delivery rates confirmed at checkout.</p><p style={{ color: "var(--ink-soft)" }}>Made-to-order pieces are final sale; please reach out via Contact for any issues with your order.</p></div>],
            ].map(([k, label, body]) => (
              <div className={"acc-item" + (acc === k ? " open" : "")} key={k}>
                <button className="acc-h" onClick={() => setAcc(acc === k ? "" : k)}>{label}<Icon name={acc === k ? "minus" : "plus"} size={18} /></button>
                <div className="acc-body"><div className="acc-inner">{body}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* complete the look */}
      {look.length > 0 && (
        <section className="section-pad ctl-sec">
          <div className="wrap-wide">
            <div className="section-head" style={{ marginBottom: 40 }}>
              <div><Eyebrow>Styled together</Eyebrow><h2 className="serif" style={{ marginTop: 12 }}>Complete the look</h2></div>
            </div>
            <div className="ctl-grid">
              <div className="ctl-hero zoomable"><Ph label="THE FULL LOOK · STYLED" ratio="portrait" /></div>
              <div className="ctl-items">
                {[p, ...look].map((item, i) => (
                  <button key={item.id + i} className="ctl-item" onClick={() => i === 0 ? null : onNav("product", { id: item.id })}>
                    <Ph label="" ratio="square" style={{ width: 78, height: 78 }} />
                    <div className="ctl-item-body">
                      <span className="pcard-cat">{i === 0 ? "This piece" : item.cat}</span>
                      <span className="serif" style={{ fontSize: 19 }}>{item.name}</span>
                      <Price ngn={item.price} style={{ fontSize: 14, color: "var(--ink-soft)" }} />
                    </div>
                    {i !== 0 && <span className="ctl-add" onClick={(e) => { e.stopPropagation(); addToCart(item, { size: item.sizes[1] || item.sizes[0], color: item.colors[0].name }); }}>Add</span>}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </section>
      )}

      {/* related */}
      <FeaturedRow eyebrow="You may also like" title="More from the atelier" products={rel} onNav={onNav} link={{ cat: p.cat }} />

      {showSize && <SizeGuide gender={p.audience} onClose={() => setShowSize(false)} />}
    </div>
  );
}

Object.assign(window, { ShopPage, ProductPage, SizeGuide, FitFinder });
