// Product detail
const { useState: useStatePD } = React;

function getStockMeta(stock) {
  if (!stock && stock !== 0) return null;
  if (stock === 0) return { label: 'Out of stock', tier: 'out' };
  if (stock <= 3)  return { label: `Only ${stock} left — order soon!`, tier: 'critical' };
  if (stock <= 10) return { label: `${stock} in stock`, tier: 'low' };
  return { label: `${stock} in stock`, tier: 'good' };
}

function ProductPage({ productId, setPage, addToCart, openProduct, wishlist = [], toggleWishlist }) {
  const [qty, setQty] = useStatePD(1);
  const [thumbIdx, setThumbIdx] = useStatePD(0);
  const product = window.BAMBOO_PRODUCTS.find(p => p.id === productId) || window.BAMBOO_PRODUCTS[0];
  const related = window.BAMBOO_PRODUCTS.filter(p => p.cat === product.cat && p.id !== product.id).slice(0, 4);

  const thumbLabels = ['front', 'detail', 'side', 'in use'];

  return (
    <React.Fragment>
      <div className="pd">
        <div className="container">
          <a href="/shop/" className="pd-back" onClick={(e) => { e.preventDefault(); setPage('shop'); }}>← Back to shop</a>
          <div className="pd-grid">
            <div className="pd-gallery">
              {product.images && product.images.length > 1 && (
                <div className="pd-thumbs">
                  {product.images.map((imgUrl, i) => (
                    <SmoothBackground
                      key={i}
                      className={'pd-thumb ' + (thumbIdx === i ? 'active' : '')}
                      onClick={() => setThumbIdx(i)}
                      src={imgUrl}
                      style={{ backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat' }}
                      role="img"
                      aria-label={`${product.name} gallery thumbnail - Bamboos Culture`}
                    />
                  ))}
                </div>
              )}
              <SmoothBackground
                className="pd-main-img"
                data-label={product.name}
                src={product.images ? (product.images[thumbIdx] || product.image) : product.image}
                style={{ backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat' }}
                role="img"
                aria-label={`${product.name} main view - Bamboos Culture`}
              />
            </div>
            <div>
              <div className="pd-cat">{product.cat}</div>
              <h1 className="pd-title">{window.renderProductName ? window.renderProductName(product.name) : product.name}</h1>
              <div className="pd-price">₹{product.price}</div>
              {(() => {
                const sm = getStockMeta(product.stock);
                if (!sm) return null;
                return (
                  <div className={'pd-stock pd-stock--' + sm.tier}>
                    <span className="pd-stock-dot"></span>
                    <span className="pd-stock-label">{sm.label}</span>
                  </div>
                );
              })()}
              <p className="pd-desc">{product.desc}</p>
              <div className="pd-qty">
                <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
                <span>{qty}</span>
                <button onClick={() => setQty(qty + 1)}>+</button>
              </div>
              <div className="pd-actions">
                <button className="pd-add" onClick={() => addToCart(product.id, qty)}>Add to cart — ₹{product.price * qty}</button>
                <button
                  className={'pd-wishlist-btn ' + (wishlist.includes(product.id) ? 'active' : '')}
                  onClick={() => toggleWishlist(product.id)}
                  aria-label="Toggle Wishlist"
                >
                  <svg viewBox="0 0 24 24">
                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                  </svg>
                </button>
              </div>
              <div className="pd-specs" style={{marginTop:40}}>
                {Object.entries(product.specs).map(([k, v]) => (
                  <div key={k} className="pd-spec">
                    <span className="pd-spec-label">{k}</span>
                    <span>{v}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {related.length > 0 && (
            <div style={{marginTop:120}}>
              <div className="section-head">
                <div><div className="mono">— You may also like</div><h2 style={{fontSize:48}}>More from {product.cat}</h2></div>
              </div>
              <div className="products-grid" style={{'--cols': 4}}>
                {related.map(p => (
                  <a
                    key={p.id}
                    href={`/products/${window.slugify(p.name)}/`}
                    className="product-card"
                    onClick={(e) => { e.preventDefault(); openProduct(p.id); }}
                    style={{ textDecoration: 'none', color: 'inherit', display: 'block' }}
                  >
                    <SmoothBackground
                      className="product-card-img"
                      data-label={p.name}
                      src={p.image}
                      style={{ backgroundSize: 'cover', backgroundPosition: 'center', position: 'relative' }}
                      role="img"
                      aria-label={`Handmade ${p.name} - Bamboos Culture`}
                    >
                      <button
                        className={'wishlist-btn-card ' + (wishlist.includes(p.id) ? 'active' : '')}
                        onClick={(e) => {
                          e.stopPropagation();
                          e.preventDefault();
                          toggleWishlist(p.id);
                        }}
                        aria-label="Wishlist"
                      >
                        <svg viewBox="0 0 24 24">
                          <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                        </svg>
                      </button>
                    </SmoothBackground>
                    <div className="product-card-cat">{p.cat}</div>
                    <div className="product-card-name">{window.renderProductName ? window.renderProductName(p.name) : p.name}</div>
                    <div className="product-card-price">₹{p.price}</div>
                  </a>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
      <Footer setPage={setPage} />
    </React.Fragment>
  );
}

Object.assign(window, { ProductPage });
