// Shop pages — RTW grid, Studio editorial, Product detail
const { useState: useStateS, useEffect: useEffectS, useMemo } = React;

function ProductCard({ p, onOpen, currency }) {
  const [hover, setHover] = useStateS(false);
  return (
    <article
      className={'pcard ' + (p.span === 'tall' ? 'tall' : '')}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onOpen(p)}
    >
      <div className="pcard-img-wrap">
        <div className="pcard-img" style={{backgroundImage: `url(${hover && p.alt ? p.alt : p.img})`}}/>
        {p.new && <span className="pcard-tag">New In</span>}
        <button className="pcard-quick" onClick={(e) => { e.stopPropagation(); onOpen(p); }}>
          Quick View
        </button>
      </div>
      <div className="pcard-info">
        <p className="pcard-collection">{p.collection}</p>
        <p className="pcard-name">{p.name}</p>
        <p className="pcard-price">{fmtPrice(convertPrice(p.price, p.currency, currency), currency)}</p>
      </div>
    </article>
  );
}

function ShopRTW({ filter, setFilter, currency, openProduct }) {
  const [sort, setSort] = useStateS('curated');
  const [filterOpen, setFilterOpen] = useStateS(true);

  const filtered = useMemo(() => {
    let list = [...PRODUCTS_RTW];
    if (filter.category) list = list.filter(p => p.category.toLowerCase().replace(/\s+/g,'-') === filter.category);
    if (filter.collection) list = list.filter(p => p.collection.toLowerCase().replace(/\s+/g,'-') === filter.collection);
    if (sort === 'price-asc') list.sort((a,b) => convertPrice(a.price,a.currency,'USD') - convertPrice(b.price,b.currency,'USD'));
    if (sort === 'price-desc') list.sort((a,b) => convertPrice(b.price,b.currency,'USD') - convertPrice(a.price,a.currency,'USD'));
    return list;
  }, [filter, sort]);

  return (
    <div className="page page-shop">
      <div className="page-head">
        <div className="page-head-inner">
          <p className="eyebrow">{filtered.length} pieces · live from the atelier</p>
          <h1 className="display xl">Ready to Wear</h1>
          <p className="lede">Pret-a-porter from the Mrs. Keepa house — eclectic, occasion-led silhouettes drawn from travel and vintage glamour, made in the Dubai workshop.</p>
        </div>
      </div>

      <div className="shop-toolbar">
        <button className="toolbar-toggle" onClick={() => setFilterOpen(v => !v)}>
          {filterOpen ? 'Hide' : 'Show'} Filters
        </button>
        <div className="toolbar-crumbs">
          {filter.category || filter.collection ? (
            <>
              <span>Filtered by</span>
              {filter.category && <button className="crumb" onClick={() => setFilter({...filter, category: null})}>
                {CATEGORIES_RTW.find(c => c.slug === filter.category)?.name} ✕
              </button>}
              {filter.collection && <button className="crumb" onClick={() => setFilter({...filter, collection: null})}>
                {COLLECTIONS.find(c => c.slug === filter.collection)?.name} ✕
              </button>}
            </>
          ) : <span className="muted">All pieces</span>}
        </div>
        <div className="toolbar-sort">
          <label>Sort</label>
          <select value={sort} onChange={e => setSort(e.target.value)}>
            <option value="curated">Curated</option>
            <option value="price-asc">Price · low to high</option>
            <option value="price-desc">Price · high to low</option>
          </select>
        </div>
      </div>

      <div className={'shop-layout ' + (filterOpen ? 'with-filters' : '')}>
        {filterOpen && (
          <aside className="shop-filters">
            <div className="filter-block">
              <h6>Category</h6>
              <ul>
                <li>
                  <button className={!filter.category ? 'on' : ''} onClick={() => setFilter({...filter, category: null})}>
                    All <span className="count">{PRODUCTS_RTW.length}</span>
                  </button>
                </li>
                {CATEGORIES_RTW.map(c => (
                  <li key={c.slug}>
                    <button
                      className={filter.category === c.slug ? 'on' : ''}
                      onClick={() => setFilter({...filter, category: c.slug})}
                    >
                      {c.name} <span className="count">{c.count}</span>
                    </button>
                  </li>
                ))}
              </ul>
            </div>
            <div className="filter-block">
              <h6>Collection</h6>
              <ul>
                {COLLECTIONS.filter(c => !c.studio).map(c => (
                  <li key={c.slug}>
                    <button
                      className={filter.collection === c.slug ? 'on' : ''}
                      onClick={() => setFilter({...filter, collection: c.slug})}
                    >
                      {c.name} <span className="count">{c.count}</span>
                    </button>
                  </li>
                ))}
              </ul>
            </div>
            <div className="filter-block">
              <h6>Price</h6>
              <ul>
                <li><button>Under $400</button></li>
                <li><button>$400 – $800</button></li>
                <li><button>$800 – $1,500</button></li>
                <li><button>Above $1,500</button></li>
              </ul>
            </div>
            <div className="filter-block">
              <h6>Size</h6>
              <div className="size-grid">
                {['XS','S','M','L','XL','One Size'].map(s =>
                  <button key={s} className="size-pill">{s}</button>
                )}
              </div>
            </div>
          </aside>
        )}
        <div className="shop-grid">
          {filtered.map(p => (
            <ProductCard key={p.id} p={p} onOpen={openProduct} currency={currency} />
          ))}
          {filtered.length === 0 && (
            <div className="empty-grid">
              <p className="display lg">Nothing matches just yet.</p>
              <p className="muted">Try fewer filters, or get in touch with the atelier directly.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function StudioPage({ currency, openProduct, openAppt }) {
  return (
    <div className="page page-studio">
      <div className="studio-hero">
        <div className="studio-hero-img" style={{backgroundImage: `url(media/studio-inhale-sea-queen-dress.webp)`}}/>
        <div className="studio-hero-text">
          <p className="eyebrow inverse">Studio · Couture · Inhale</p>
          <h1 className="display xxl inverse">A breath, held<br/>in fabric.</h1>
          <p className="lede inverse">Mrs. Keepa's couture line. First formalised for Sotheby's Dubai, made in the atelier, fitted by appointment.</p>
          <div className="row gap">
            <button onClick={openAppt} className="btn primary inverse">Book a Studio appointment</button>
            <a href="https://wa.me/971526933359" target="_blank" rel="noopener" className="btn ghost inverse">Enquire on WhatsApp</a>
          </div>
        </div>
      </div>

      <div className="studio-band">
        <div className="band-inner">
          <div className="band-line">
            <span className="band-num">01</span>
            <h3 className="display">Designed to be worn three ways.</h3>
            <p className="muted">Each Inhale piece is constructed so the wearer can decide how, and how much, of it is shown.</p>
          </div>
          <div className="band-line">
            <span className="band-num">02</span>
            <h3 className="display">Cut in Dubai, by hand.</h3>
            <p className="muted">Pieces are patterned and finished in Mariam's d3 workshop. Small-scale, attributed quote — see the materials notes.</p>
          </div>
          <div className="band-line">
            <span className="band-num">03</span>
            <h3 className="display">Made to measure.</h3>
            <p className="muted">Studio is appointment-led. Off-the-rack pieces exist; the closer the cut, the longer the conversation.</p>
          </div>
        </div>
      </div>

      <div className="studio-pieces">
        <div className="page-head-inner">
          <p className="eyebrow">Inhale · presented at Sotheby's Dubai</p>
          <h2 className="display xl">The collection.</h2>
        </div>
        <div className="studio-grid">
          {PRODUCTS_STUDIO.map(p => (
            <article key={p.id} className="studio-card" onClick={() => openProduct(p)}>
              <div className="studio-card-img" style={{backgroundImage: `url(${p.img})`}}/>
              <div className="studio-card-info">
                <p className="eyebrow">{p.category}</p>
                <h4 className="display">{p.name}</h4>
                <p className="muted">{p.description}</p>
                <div className="studio-card-foot">
                  <span>{fmtPrice(convertPrice(p.price, p.currency, currency), currency)}</span>
                  <span className="link-arrow">Enquire →</span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>

      <div className="studio-quote">
        <p className="eyebrow">Mariam, on the workshop</p>
        <blockquote className="display xl">
          <span className="quote-mark">"</span>The atelier is small-scale, zero-waste, local. Every off-cut becomes the next piece — or a cushion for the home.<span className="quote-mark">"</span>
        </blockquote>
        <p className="muted">Attributed to Mariam Yeya, in conversation with Sotheby's Dubai, Feb 2024.</p>
      </div>
    </div>
  );
}

function ProductOverlay({ product, onClose, currency, addToBag }) {
  const [size, setSize] = useStateS(null);
  const [color, setColor] = useStateS(null);
  const [tab, setTab] = useStateS('description');
  const [imgIdx, setImgIdx] = useStateS(0);
  useEffectS(() => {
    if (product) {
      setSize(null);
      setColor(product.colorways ? product.colorways[0] : null);
      setTab('description');
      setImgIdx(0);
    }
  }, [product]);

  if (!product) return null;
  const images = [product.img, product.alt].filter(Boolean);

  const addable = !product.enquireOnly && size;

  return (
    <>
      <div className="overlay on" onClick={onClose} />
      <div className="product-modal on" role="dialog">
        <button className="x modal-x" onClick={onClose}>✕</button>
        <div className="pm-body">
          <div className="pm-images">
            <div className="pm-main" style={{backgroundImage: `url(${images[imgIdx]})`}}/>
            {images.length > 1 && (
              <div className="pm-thumbs">
                {images.map((src, i) => (
                  <button key={i} className={imgIdx === i ? 'on' : ''} onClick={() => setImgIdx(i)}>
                    <div style={{backgroundImage: `url(${src})`}}/>
                  </button>
                ))}
              </div>
            )}
          </div>
          <div className="pm-info">
            <p className="eyebrow">{product.collection} · {product.category}</p>
            <h2 className="display lg">{product.name}</h2>
            <p className="pm-price">
              {fmtPrice(convertPrice(product.price, product.currency, currency), currency)}
              {product.currency !== currency && (
                <span className="muted small"> · {fmtPrice(product.price, product.currency)} at source</span>
              )}
            </p>
            <p className="lede">{product.description}</p>

            {product.colorways && product.colorways.length > 0 && (
              <div className="pm-block">
                <p className="eyebrow xs">Colourway · <em>{color}</em></p>
                <div className="pm-colorways">
                  {product.colorways.map(c => (
                    <button key={c} className={'pm-color ' + (color === c ? 'on' : '')} onClick={() => setColor(c)}>{c}</button>
                  ))}
                </div>
              </div>
            )}

            <div className="pm-block">
              <p className="eyebrow xs">{product.enquireOnly ? 'Sizing' : 'Size'}</p>
              <div className="pm-sizes">
                {product.sizes.map(s => (
                  <button key={s} className={'pm-size ' + (size === s ? 'on' : '')} onClick={() => setSize(s)}>{s}</button>
                ))}
              </div>
              {!product.enquireOnly && !size && <p className="muted small">Choose a size to add to bag.</p>}
            </div>

            <div className="pm-actions">
              {product.enquireOnly ? (
                <>
                  <a href="https://wa.me/971526933359" target="_blank" rel="noopener" className="btn primary block">Enquire about this piece</a>
                  <button className="btn ghost block">Book a Studio fitting</button>
                </>
              ) : (
                <>
                  <button
                    className={'btn primary block ' + (!addable ? 'disabled' : '')}
                    disabled={!addable}
                    onClick={() => { addToBag({ ...product, size, colorway: color || '—', qty: 1 }); onClose(); }}
                  >
                    {size ? `Add to Bag — ${fmtPrice(convertPrice(product.price, product.currency, currency), currency)}` : 'Select a size'}
                  </button>
                  <button className="btn ghost block">Save to wishlist</button>
                </>
              )}
            </div>

            <div className="pm-tabs">
              {['description','composition','shipping'].map(t => (
                <button key={t} className={tab === t ? 'on' : ''} onClick={() => setTab(t)}>
                  {t === 'description' ? 'Details' : t === 'composition' ? 'Composition & Care' : 'Shipping'}
                </button>
              ))}
            </div>
            <div className="pm-tab-body">
              {tab === 'description' && <p>{product.description} Cut and finished in the Mrs. Keepa atelier, Dubai Design District.</p>}
              {tab === 'composition' && <p>{product.composition || 'Composition details available on request — please contact the atelier.'}</p>}
              {tab === 'shipping' && <p>Complimentary worldwide express shipping on orders over $400. UAE orders ship same-day. Returns within 14 days of receipt for unworn Ready to Wear; Studio pieces are final sale.</p>}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function CollectionsPage({ setRoute, currency }) {
  return (
    <div className="page page-collections">
      <div className="page-head">
        <div className="page-head-inner">
          <p className="eyebrow">Seven worlds, one wardrobe</p>
          <h1 className="display xxl">The Collections.</h1>
          <p className="lede">Each Mrs. Keepa collection holds together by mood, not by season. Fabrics return; silhouettes refine. Pieces are designed to be restyled across collections, year after year.</p>
        </div>
      </div>
      <div className="collections-grid">
        {COLLECTIONS.map((c, i) => (
          <article key={c.slug} className={'coll-tile ' + (i % 5 === 0 ? 'wide' : '') + (c.studio ? ' studio' : '')}
            onClick={() => setRoute(c.studio ? {page:'studio'} : {page:'shop', filter:{collection: c.slug}})}>
            <div className="coll-tile-img" style={{backgroundImage: `url(${c.img})`}}/>
            <div className="coll-tile-info">
              <p className="eyebrow inverse">{c.studio ? 'Studio · Couture' : 'Ready to Wear'} · {c.count} pieces</p>
              <h2 className="display xl inverse">{c.name}</h2>
              <p className="lede inverse">{c.mood}</p>
              <p className="link-arrow inverse">Enter the collection →</p>
            </div>
          </article>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  ProductCard, ShopRTW, StudioPage, ProductOverlay, CollectionsPage,
});
