/* ============================================================
   NELSON — Shop / 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 [gender, setGender] = useState(p0.gender || 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); setGender(p.gender || null);
  }, [route]);

  let list = RB.PRODUCTS.filter((p) =>
    (!cat || p.cat === cat) &&
    (!gender || p.gender === gender) &&
    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); setGender(null); setMaxPrice(1000000); };
  const heading = cat ? cat + (cat.endsWith("s") ? "" : "s") : gender ? gender + "'s Edit" : "All Products";
  const activeCount = [cat, gender].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>}
              {gender && <button className="achip" onClick={() => setGender(null)}>{gender}swear <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="CRAFT · DETAIL" 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)" }}>Keep it clean and considered — a sharp oxford for the boardroom, a loafer for the in-between days, a sneaker for everything else.</p>
              <button className="link-arrow" style={{ marginTop: 18 }} onClick={() => onNav("shop", {})}>Browse all shoes</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 }) {
  const rows = [["39", "6", "7", "24.5"], ["40", "6.5", "7.5", "25"], ["41", "7.5", "8.5", "25.7"], ["42", "8", "9", "26.4"], ["43", "9", "10", "27.1"], ["44", "10", "11", "27.9"], ["45", "11", "12", "28.6"], ["46", "11.5", "12.5", "29.3"]];
  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>EU</th><th>UK</th><th>US</th><th>Foot length (cm)</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. If you're between sizes, we generally recommend sizing up.</p>
      </div>
    </div>
  );
}

/* ---------------- FIT FINDER ---------------- */
function FitFinder({ sizes, onPick }) {
  const [step, setStep] = useState(0);
  const [len, setLen] = useState("");
  const TABLE = [["39",24.5],["40",25],["41",25.7],["42",26.4],["43",27.1],["44",27.9],["45",28.6],["46",29.3]];
  const nearest = () => {
    const v = parseFloat(len) || 26.4;
    let best = TABLE[0];
    for (const t of TABLE) if (Math.abs(t[1] - v) < Math.abs(best[1] - v)) best = t;
    return sizes.includes(best[0]) ? best[0] : sizes[Math.floor(sizes.length / 2)];
  };
  const result = nearest();
  return (
    <div className="fitfinder">
      {step === 0 && (
        <div className="ff-step">
          <Icon name="ruler" size={24} />
          <div><strong>Find your perfect fit</strong><span>Measure your foot length 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>Foot length (cm)</label>
          <input className="input" type="number" placeholder="e.g. 26.5" value={len} onChange={(e) => setLen(e.target.value)} />
          <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 {len || "26.4"}cm foot length. 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 add = () => {
    if (!size) { setErr(true); return; }
    addToCart(p, { size, color: color.name, qty });
    openCart();
  };
  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-main-img zoomable">
            {p.badge && <span className="pcard-tag" style={{ top: 18, left: 18 }}>{p.badge}</span>}
            <Ph label={p.label} ratio="tall" />
          </div>
        </div>

        {/* info */}
        <div className="pdp-info">
          <Eyebrow>{p.cat}</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>}
            <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>

          <div className="pdp-assure">
            {[["truck", "Worldwide shipping"]].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>Designed for everyday comfort and wear</li><li>True to size — see size guide</li></ul>],
              ["fabric", "Materials & Care", <div><p style={{ marginBottom: 10 }}><strong>{p.fabric}</strong></p><p style={{ color: "var(--ink-soft)" }}>Wipe clean with a soft, dry cloth. Use a shoe tree to hold shape between wears and avoid prolonged direct sunlight.</p></div>],
              ["shipping", "Shipping & Returns", <div><p style={{ marginBottom: 8 }}>We ship within Nigeria and internationally, with tracked delivery.</p><p style={{ color: "var(--ink-soft)" }}>Unworn pairs in original packaging can be returned within 14 days of delivery.</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>

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

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

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