/* global React */
const { useState: useStateShop, useEffect: useEffectShop, useMemo: useMemoShop } = React;

// Fallback dataset used if /api/products is unreachable (e.g. local dev).
const PRESS_ON_DESIGNS = [
{ id: 1, name: 'Aurora Chrome', price: 999, cat: 'Chrome', shape: 'Almond', tone: 1, tags: ['Bestseller'] },
{ id: 2, name: 'Vintage Rose', price: 1199, cat: 'Florals', shape: 'Coffin', tone: 2, tags: ['Hand-painted'] },
{ id: 3, name: 'Micro French', price: 899, cat: 'French', shape: 'Stiletto', tone: 3, tags: [] },
{ id: 4, name: 'Pearl Drop', price: 1499, cat: '3D Charms', shape: 'Square', tone: 4, tags: ['Bridal'] },
{ id: 5, name: 'Cat Eye Galaxy', price: 1099, cat: 'Glitter', shape: 'Almond', tone: 1, tags: ['New'] },
{ id: 6, name: 'Butter Nude', price: 799, cat: 'Minimal', shape: 'Short Square', tone: 2, tags: [] },
{ id: 7, name: 'Cherry Blossom', price: 1199, cat: 'Florals', shape: 'Oval', tone: 3, tags: ['Hand-painted'] },
{ id: 8, name: 'Mirror Chrome', price: 999, cat: 'Chrome', shape: 'Stiletto', tone: 4, tags: ['Bestseller'] },
{ id: 9, name: 'Lavender French', price: 949, cat: 'French', shape: 'Ballerina', tone: 1, tags: [] },
{ id: 10, name: 'Bow Charms', price: 1399, cat: '3D Charms', shape: 'Short Oval', tone: 2, tags: ['New'] },
{ id: 11, name: 'Gilded Tips', price: 1099, cat: 'French', shape: 'Almond', tone: 3, tags: [] },
{ id: 12, name: 'Marble Mocha', price: 1099, cat: 'Minimal', shape: 'Coffin', tone: 4, tags: [] },
{ id: 13, name: 'Holo Drift', price: 999, cat: 'Glitter', shape: 'Square', tone: 1, tags: [] },
{ id: 14, name: 'Wildflower', price: 1299, cat: 'Florals', shape: 'Almond', tone: 2, tags: ['Hand-painted'] },
{ id: 15, name: 'Star Dust', price: 949, cat: 'Glitter', shape: 'Stiletto', tone: 3, tags: [] },
{ id: 16, name: 'Plum Velvet', price: 899, cat: 'Minimal', shape: 'Oval', tone: 4, tags: [] },
{ id: 17, name: 'Crystal Ombré', price: 1299, cat: 'Chrome', shape: 'Coffin', tone: 1, tags: ['Bridal'] },
{ id: 18, name: 'Polka Pearl', price: 1199, cat: '3D Charms', shape: 'Almond', tone: 2, tags: ['New'] },
{ id: 19, name: 'Cinnamon Sugar', price: 849, cat: 'Minimal', shape: 'Short Square', tone: 3, tags: [] },
{ id: 20, name: 'Dahlia Noir', price: 1399, cat: 'Florals', shape: 'Stiletto', tone: 4, tags: ['Hand-painted'] }];


const SHOP_CATS = ['All', 'Chrome', 'Florals', 'French', 'Glitter', '3D Charms', 'Minimal'];

window.ShopHero = function ShopHero() {
  return (
    <section className="shop-hero">
      <div className="shell shop-hero-inner">
        <div className="shop-hero-copy">
          <div className="eyebrow">The Press-On Atelier</div>
          <h1 className="display shop-hero-title" style={{ color: "rgb(2, 0, 73)" }}>
            Reusable. Reapplied.<br />
            <span className="script-inline">Reimagined.</span>
          </h1>
          <p>20 hand-crafted designs to choose from — or send your inspiration on WhatsApp and we'll make a one-of-one set, sized to your nail beds.</p>
          <div className="shop-hero-rail">
            <div className="shop-hero-rail-item">
              <span className="shop-hero-rail-num">02</span>
              <span>Lasts up to <strong>2 weeks</strong> per wear</span>
            </div>
            <div className="shop-hero-rail-item">
              <span className="shop-hero-rail-num">10</span>
              <span><strong>10 sizes</strong> per set</span>
            </div>
            <div className="shop-hero-rail-item">
              <span className="shop-hero-rail-num">48</span>
              <span>Custom orders ship in <strong>48h</strong></span>
            </div>
          </div>
        </div>
      </div>
    </section>);

};

const PRESS_ON_SIZES = ['S', 'M', 'L'];
const SIZE_LABELS = {
  S: 'Small (slim, shorter beds)',
  M: 'Medium (most common fit)',
  L: 'Large (wider beds)'
};

window.Shop = function Shop() {
  const [cat, setCat] = useStateShop('All');
  const [sort, setSort] = useStateShop('featured');
  const [quickView, setQuickView] = useStateShop(null);
  const [products, setProducts] = useStateShop(null); // null = loading
  const [selectedSize, setSelectedSize] = useStateShop({}); // { [productId]: 'S'|'M'|'L' }

  useEffectShop(() => {
    if (!window.LQ_PUB) { setProducts([]); return; }
    window.LQ_PUB.fetchProducts().then((rows) => {
      setProducts((rows || []).map((p) => ({
        id: p.id,
        name: p.name,
        price: p.price,
        cat: p.category,
        tone: ((p.id || 0) % 4) + 1,
        tags: p.tags || [],
        photo: p.photo_path || null,
      })));
    }).catch(() => {});
  }, []);

  const filtered = useMemoShop(() => {
    let r = products || [];
    if (cat !== 'All') r = r.filter((d) => d.cat === cat);
    if (sort === 'low') r = [...r].sort((a, b) => a.price - b.price);else
    if (sort === 'high') r = [...r].sort((a, b) => b.price - a.price);
    return r;
  }, [products, cat, sort]);

  const sizeFor = (d) => selectedSize[d.id] || 'M';

  const waLink = (design) => {
    const sz = design ? sizeFor(design) : 'M';
    const msg = design ?
    `Hi Lacquery! I'd like to order the *${design.name}* press-on set (size ${sz}). Could you confirm fit details and shipping?` :
    `Hi Lacquery! I'd like to design a custom press-on set. Here's what I'm thinking:`;
    return window.LQ_PUB ? window.LQ_PUB.waLink(msg) : ('https://wa.me/918317451779?text=' + encodeURIComponent(msg));
  };

  if (products === null) return (
    <section className="shop"><div className="shell" style={{ padding: '80px 0', textAlign: 'center', color: '#aaa', letterSpacing: '0.1em', textTransform: 'uppercase', fontSize: 13 }}>Loading…</div></section>
  );

  if (products.length === 0) return (
    <section className="shop"><div className="shell" style={{ padding: '80px 0', textAlign: 'center' }}>
      <p style={{ color: '#999', fontSize: 15, marginBottom: 24 }}>No press-on sets listed yet — check back soon.</p>
      <a href="book.html" className="btn btn-primary">Book an appointment instead</a>
    </div></section>
  );

  return (
    <section className="shop">
      <div className="shell">
        <div className="shop-toolbar">
          <div className="shop-filters">
            <div className="shop-filter-group">
              <label>Style</label>
              <div className="shop-chips">
                {SHOP_CATS.map((c) =>
                <button key={c} className={`shop-chip ${cat === c ? 'active' : ''}`} onClick={() => setCat(c)}>{c}</button>
                )}
              </div>
            </div>
          </div>
          <div className="shop-filter-group">
            <label>Sort</label>
            <select className="shop-select" value={sort} onChange={(e) => setSort(e.target.value)}>
              <option value="featured">Featured</option>
              <option value="low">Price · Low to High</option>
              <option value="high">Price · High to Low</option>
            </select>
          </div>
        </div>

        <div className="shop-count">
          <span>{filtered.length}{cat !== 'All' ? ` of ${products.length}` : ''} designs</span>
        </div>

        <div className="shop-grid">
          {filtered.map((d) =>
          <article key={d.id} className="shop-card">
              <div className="shop-card-media">
                <div className="gold-frame shop-card-frame">
                  <div className={`ph shop-card-photo tone-${d.tone}`} data-label={d.name} style={d.photo ? { backgroundImage: `url(${d.photo})`, backgroundSize: 'cover', backgroundPosition: 'center' } : null}></div>
                </div>
                {d.tags.length > 0 &&
              <div className="shop-card-tags">
                    {d.tags.map((t) => <span key={t} className={`shop-card-tag tag-${t.toLowerCase().replace(/[^a-z]/g, '')}`}>{t}</span>)}
                  </div>
              }
                <button className="shop-card-quick" onClick={() => setQuickView(d)}>Quick view</button>
              </div>
              <div className="shop-card-info">
                <div className="shop-card-meta">
                  <span className="shop-card-cat">{d.cat}</span>
                </div>
                <h3 className="display shop-card-name">{d.name}</h3>
                <div className="shop-card-sizes">
                  <span className="shop-card-sizes-lbl">Size</span>
                  <div className="shop-card-size-row">
                    {PRESS_ON_SIZES.map((sz) => (
                      <button
                        key={sz}
                        type="button"
                        className={`shop-card-size ${sizeFor(d) === sz ? 'active' : ''}`}
                        onClick={() => setSelectedSize({ ...selectedSize, [d.id]: sz })}
                        aria-label={SIZE_LABELS[sz]}
                      >{sz}</button>
                    ))}
                  </div>
                </div>
                <div className="shop-card-foot">
                  <span className="shop-card-price">₹{d.price.toLocaleString('en-IN')}</span>
                  <a href={waLink(d)} className="shop-card-buy">
                    Order
                    <svg width="12" height="10" viewBox="0 0 12 10" fill="none"><path d="M1 5h10m0 0L7 1m4 4L7 9" stroke="currentColor" strokeWidth="1.4" /></svg>
                  </a>
                </div>
              </div>
            </article>
          )}
        </div>

        {/* CUSTOMISE BANNER */}
        <div className="shop-custom">
          <div className="shop-custom-frame" style={{ backgroundColor: "rgb(2, 0, 73)" }}>
            <div className="shop-custom-inner">
              <div className="shop-custom-script">customise</div>
              <h2 className="display shop-custom-title">
                Don't see <em>the one</em>?<br />
                Make it yours.
              </h2>
              <p>Send us your inspiration a Pinterest pin, a Reel, a hand-drawn idea and we'll hand-craft a custom set tailored to your nail size and shape. Ships in 48 hours.</p>
              <div className="shop-custom-actions">
                <a href={waLink(null)} className="btn btn-whatsapp">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" /></svg>
                  Start customising on WhatsApp
                </a>
                <span className="shop-custom-note">Or DM us @lacquerynails</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* QUICK VIEW MODAL */}
      {quickView &&
      <div className="qv-overlay" onClick={() => setQuickView(null)}>
          <div className="qv-modal" onClick={(e) => e.stopPropagation()}>
            <button className="qv-close" onClick={() => setQuickView(null)} aria-label="Close">
              <svg width="14" height="14" viewBox="0 0 14 14"><line x1="2" y1="2" x2="12" y2="12" stroke="currentColor" strokeWidth="1.5" /><line x1="12" y1="2" x2="2" y2="12" stroke="currentColor" strokeWidth="1.5" /></svg>
            </button>
            <div className="qv-grid">
              <div className="gold-frame qv-frame">
                <div className={`ph qv-photo tone-${quickView.tone}`} data-label={quickView.name} style={quickView.photo ? { backgroundImage: `url(${quickView.photo})`, backgroundSize: 'cover', backgroundPosition: 'center' } : null}></div>
              </div>
              <div className="qv-info">
                <div className="eyebrow">{quickView.cat}</div>
                <h3 className="display qv-name">{quickView.name}</h3>
                <div className="qv-price">₹{quickView.price.toLocaleString('en-IN')}</div>

                <div className="qv-size-block">
                  <div className="qv-size-lbl">Choose size</div>
                  <div className="qv-size-row">
                    {PRESS_ON_SIZES.map((sz) => (
                      <button
                        key={sz}
                        type="button"
                        className={`qv-size ${sizeFor(quickView) === sz ? 'active' : ''}`}
                        onClick={() => setSelectedSize({ ...selectedSize, [quickView.id]: sz })}
                      >
                        <span className="qv-size-letter">{sz}</span>
                        <span className="qv-size-desc">{SIZE_LABELS[sz]}</span>
                      </button>
                    ))}
                  </div>
                </div>

                <div className="qv-spec">
                  <div><span>Wear</span><strong>Up to 2 weeks</strong></div>
                  <div><span>Includes</span><strong>10 nails + glue + file</strong></div>
                  <div><span>Delivery</span><strong>2–3 days · Bengaluru</strong></div>
                </div>
                <p>Each Lacquery set is hand-finished in studio. Send us your nail measurements on WhatsApp after ordering — we'll match the perfect fit.</p>
                <div className="qv-actions">
                  <a href={waLink(quickView)} className="btn btn-whatsapp">Order on WhatsApp · {sizeFor(quickView)}</a>
                  <a href={waLink({ ...quickView, name: quickView.name + ' (customised)' })} className="btn btn-ghost">Customise this</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      }
    </section>);

};