// ========== MARKETPLACE ==========
const MarketplacePage = ({ nav, cart, addToCart, openProduct, saved = {providers:[],products:[]}, toggleSave = () => {} }) => {
  const [filter, setFilter] = React.useState('all');
  const filtered = filter === 'all' ? PRODUCTS : PRODUCTS.filter(p => p.tag === filter);

  return (
    <div className="fade-in">
      <div className="container">
        <div className="market-hero">
          <div className="market-head">
            <div>
              <div className="eyebrow">The Marketplace</div>
              <h1>Caribbean beauty, <span style={{fontStyle:'italic', color:'var(--primary-deep)'}}>shipped</span>.</h1>
            </div>
            <div style={{display:'flex', gap: 8}}>
              <button className="btn btn-outline" onClick={() => nav('seller-dashboard')}><Icon name="shop" size={14}/> Seller dashboard</button>
            </div>
          </div>

          <div className="market-tabs">
            {['All','Bestsellers','New','Hair','Skincare','Makeup','Nails','Tools','Accessories'].map(t => {
              const k = t === 'All' ? 'all' : t.toLowerCase();
              const isActive = filter === k || (filter === 'bestseller' && t === 'Bestsellers');
              return (
                <button key={t} className={isActive ? 'active' : ''} onClick={() => setFilter(t === 'Bestsellers' ? 'bestseller' : k)}>
                  {t}
                </button>
              );
            })}
          </div>
        </div>

        <div className="product-grid">
          {filtered.map(p => (
            <div key={p.id} className="product-card" onClick={() => openProduct(p.id)}>
              <div className="product-image">
                <Ph tone={p.tone} style={{fontSize: 11}}>{p.name.split(' ').slice(0,3).join(' ')}</Ph>
                {p.sale && <div className="sale">{p.sale}</div>}
                {p.tag === 'bestseller' && !p.sale && <div className="sale" style={{background:'var(--ink)'}}>BESTSELLER</div>}
                {p.tag === 'new' && !p.sale && <div className="sale" style={{background:'var(--teal)'}}>NEW</div>}
                <button className={`fav ${saved.products.includes(p.id) ? 'active' : ''}`}
                  onClick={e => { e.stopPropagation(); toggleSave('products', p.id); }}
                  style={{position:'absolute', top: 10, right: 10, width: 32, height: 32, borderRadius:'50%', background:'rgba(255,255,255,0.92)', border:'none', display:'grid', placeItems:'center', cursor:'pointer', color: saved.products.includes(p.id) ? 'var(--coral)' : 'var(--muted)'}}>
                  <Icon name="heart" size={14}/>
                </button>
                <button className="qadd" onClick={e => { e.stopPropagation(); addToCart(p); }}>
                  <Icon name="plus" size={16}/>
                </button>
              </div>
              <div className="product-body">
                <div className="seller">{p.seller}</div>
                <h4>{p.name}</h4>
                <div style={{display:'flex', alignItems:'center', gap: 4, fontSize: 11.5, color:'var(--muted)', marginBottom: 8}}>
                  <Icon name="star" size={11}/> <strong style={{color:'var(--ink)'}}>{p.rating}</strong> ({p.reviews})
                </div>
                <div className="product-prices">
                  <div className="p">${p.price}</div>
                  {p.compare && <div className="c">${p.compare}</div>}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ========== PRODUCT DETAIL ==========
const ProductDetailPage = ({ productId, nav, addToCart, saved = {providers:[],products:[]}, toggleSave = () => {} }) => {
  const p = PRODUCTS.find(x => x.id === productId) || PRODUCTS[0];
  const [thumb, setThumb] = React.useState(0);
  const thumbs = [p.tone, 'sand', 'lav', 'mint'];
  const [qty, setQty] = React.useState(1);

  return (
    <div className="fade-in">
      <div className="container">
        <div style={{padding: '20px 0', fontSize: 13, color:'var(--muted)'}}>
          <span onClick={() => nav('marketplace')} style={{cursor:'pointer'}}>Marketplace</span> <span style={{margin:'0 8px'}}>/</span> <span style={{color:'var(--ink)'}}>{p.name}</span>
        </div>

        <div className="pd-layout">
          <div className="pd-gallery">
            <div className="pd-main">
              <Ph tone={thumbs[thumb]} style={{fontSize: 13}}>{p.name}</Ph>
            </div>
            <div className="pd-thumbs">
              {thumbs.map((t, i) => (
                <div key={i} className={`pd-thumb ${thumb === i ? 'active' : ''}`} onClick={() => setThumb(i)}>
                  <Ph tone={t} style={{fontSize: 9}}>view {i + 1}</Ph>
                </div>
              ))}
            </div>
          </div>

          <div className="pd-info">
            <div style={{color:'var(--primary-deep)', fontSize: 13, fontWeight: 600}}>{p.seller}</div>
            <h1>{p.name}</h1>
            <div style={{display:'flex', alignItems:'center', gap: 6, fontSize: 13}}>
              <Stars n={Math.round(p.rating)} size={14}/>
              <strong>{p.rating}</strong>
              <span style={{color:'var(--muted)'}}>· {p.reviews} reviews</span>
            </div>

            <div className="pd-price">
              <div className="p">${p.price}</div>
              {p.compare && <div className="c">${p.compare}</div>}
              {p.sale && <div className="s">SAVE {p.sale}</div>}
            </div>

            <p style={{color:'var(--ink-2)', fontSize: 14.5, lineHeight: 1.6}}>
              Cold-pressed hibiscus petals steeped in castor and jojoba oil. Weightless, non-greasy finish. Handmade in small batches at Island Apothecary in Kingston. Use as a scalp treatment or mid-length seal.
            </p>

            <div style={{display:'flex', alignItems:'center', gap: 12, margin: '28px 0 16px'}}>
              <div style={{display:'flex', alignItems:'center', gap: 12, border:'1px solid var(--line)', borderRadius: 999, padding: '8px 14px'}}>
                <button onClick={() => setQty(Math.max(1, qty - 1))} className="qty-btn"><Icon name="minus" size={12}/></button>
                <span style={{fontWeight: 600, minWidth: 14, textAlign:'center'}}>{qty}</span>
                <button onClick={() => setQty(qty + 1)} className="qty-btn"><Icon name="plus" size={12}/></button>
              </div>
              <button className="btn btn-brand btn-lg" style={{flex: 1}} onClick={() => addToCart(p, qty)}>
                Add to cart · ${(p.price * qty).toFixed(2)}
              </button>
              <button className="icon-btn" style={{width: 48, height: 48}}><Icon name="heart" size={18}/></button>
            </div>

            <div style={{background:'var(--sand)', borderRadius: 14, padding: 16, display:'grid', gridTemplateColumns:'1fr 1fr', gap: 10, fontSize: 12.5}}>
              <div style={{display:'flex', gap: 8, alignItems:'center'}}><Icon name="truck" size={14}/> Ships in 2–3 days</div>
              <div style={{display:'flex', gap: 8, alignItems:'center'}}><Icon name="box" size={14}/> Regional shipping</div>
              <div style={{display:'flex', gap: 8, alignItems:'center'}}><Icon name="verified" size={14}/> Authentic product</div>
              <div style={{display:'flex', gap: 8, alignItems:'center'}}><Icon name="check" size={14}/> 30-day returns</div>
            </div>

            <div style={{marginTop: 28, padding: 20, border:'1px solid var(--line)', borderRadius: 14, display:'flex', gap: 14, alignItems:'center'}}>
              <div className="placeholder-av teal"/>
              <div style={{flex: 1}}>
                <div style={{fontSize: 12.5, fontWeight: 600}}>{p.seller}</div>
                <div style={{fontSize: 11.5, color:'var(--muted)'}}>4.92★ · 1,240 products sold · Kingston, JM</div>
              </div>
              <button className="btn btn-outline btn-sm">Visit store</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ========== CART DRAWER ==========
const CartDrawer = ({ open, onClose, cart, setCart, toast }) => {
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const shipping = subtotal > 0 ? 8 : 0;
  const total = subtotal + shipping;

  const setQty = (id, qty) => {
    setCart(cart.map(i => i.id === id ? {...i, qty} : i).filter(i => i.qty > 0));
  };

  return (
    <>
      <div className={`cart-overlay ${open ? 'open' : ''}`} onClick={onClose}/>
      <div className={`cart-drawer ${open ? 'open' : ''}`}>
        <div className="cart-head">
          <h3>Your cart <span style={{fontStyle:'italic', color:'var(--muted)'}}>({cart.reduce((s, i) => s + i.qty, 0)})</span></h3>
          <button className="icon-btn" onClick={onClose} style={{border:'none', background:'var(--sand)'}}><Icon name="x" size={16}/></button>
        </div>

        <div className="cart-body">
          {cart.length === 0 ? (
            <div style={{textAlign:'center', padding:'60px 20px', color:'var(--muted)'}}>
              <div style={{fontFamily:'Fraunces, serif', fontSize: 24, color:'var(--ink)', marginBottom: 6}}>Cart's empty</div>
              <div style={{fontSize: 13}}>Add something from the marketplace</div>
            </div>
          ) : cart.map(item => (
            <div key={item.id} className="cart-item">
              <div className="img"><Ph tone={item.tone} style={{fontSize: 8}}>img</Ph></div>
              <div>
                <div className="n">{item.name}</div>
                <div className="s">{item.seller}</div>
                <div className="qty">
                  <button className="qty-btn" onClick={() => setQty(item.id, item.qty - 1)}><Icon name="minus" size={10}/></button>
                  <span style={{fontSize: 12.5, fontWeight: 600}}>{item.qty}</span>
                  <button className="qty-btn" onClick={() => setQty(item.id, item.qty + 1)}><Icon name="plus" size={10}/></button>
                </div>
              </div>
              <div className="p">${(item.price * item.qty).toFixed(2)}</div>
            </div>
          ))}
        </div>

        {cart.length > 0 && (
          <div className="cart-foot">
            <div className="cart-line"><span>Subtotal</span><span>${subtotal.toFixed(2)}</span></div>
            <div className="cart-line"><span>Shipping</span><span>${shipping.toFixed(2)}</span></div>
            <div className="cart-line total"><span>Total</span><span>${total.toFixed(2)}</span></div>
            <button className="btn btn-brand" style={{width:'100%'}} onClick={() => { toast('Checkout started — Stripe demo'); onClose(); }}>
              Checkout securely <Icon name="arrowRight" size={14}/>
            </button>
            <div style={{textAlign:'center', fontSize: 11, color:'var(--muted)', marginTop: 10}}>Secured by Stripe · Free returns within 30 days</div>
          </div>
        )}
      </div>
    </>
  );
};

Object.assign(window, { MarketplacePage, ProductDetailPage, CartDrawer });
