// pages/product.jsx — PDP with CustomerCommerce pricing + real reviews only

function ProductPage() {
  const route = useRoute();
  const store = useStore();
  const p = HAP.productBySlug(route.params.slug);
  const C = window.CustomerCommerce;

  React.useEffect(() => {
    if (p) {
      store.markViewed(p.id);
      if (window.CustomerSeo) window.CustomerSeo.applyProduct(p);
    } else if (window.CommerceRedirects && route.params.slug) {
      CommerceRedirects.navigateIfRedirect('#/products/' + route.params.slug);
    }
    return () => { if (window.CustomerSeo) window.CustomerSeo.applyDefault(); };
  }, [p?.id, route.params.slug]);

  if (!p) {
    return (
      <main className="container section">
        <h1 className="serif">Product not found</h1>
        <p style={{ color: 'var(--muted)', marginBlock: 12 }}>This product may have been removed or the link is outdated.</p>
        <a className="btn btn--primary" href="#/collections/pebbles">Browse pebbles</a>
      </main>
    );
  }

  const [variant, setVariant] = React.useState(p.variants[0]);
  const [qty, setQty] = React.useState(1);
  const [tab, setTab] = React.useState('care');
  const [imageIdx, setImageIdx] = React.useState(0);

  const cats = p.categories;
  const breadCat = HAP.findCategory(cats[1]) || HAP.findCategory(cats[0]);
  const related = (window.CustomerIntelligence && window.CustomerIntelligence.related)
    ? window.CustomerIntelligence.related(p.id, 8)
    : (window.CustomerPersonalization
      ? window.CustomerPersonalization.relatedTo(p, 8)
      : HAP.PRODUCTS.filter((x) => x.id !== p.id && x.categories.some((c) => cats.includes(c))).slice(0, 8));

  const livePrice = C.unitPrice(p.price, variant);
  const liveCompare = C.compareAtPrice(p.compareAt, variant);
  const off = C.discountPercent(livePrice, liveCompare);
  const stock = C.stockState(p);
  const stockText = C.stockLabel(stock, { revealLow: true });
  const purchasable = C.isPurchasable(p, qty);
  const wished = store.inWishlist(p.id);
  const agg = window.CustomerReviews.aggregate(p.id);
  const ship = C.shippingSettings();

  const galleryIds = React.useMemo(() => {
    const relatedImgs = HAP.PRODUCTS
      .filter((x) => x.id !== p.id && x.image && x.categories.some((c) => p.categories.includes(c)))
      .map((x) => x.image);
    return [p.image, ...relatedImgs].filter((src, i, arr) => src && arr.indexOf(src) === i).slice(0, 4);
  }, [p.id, p.image, p.categories]);

  const buyNow = () => {
    if (!store.addToCart(p.id, variant, qty)) return;
    HAPRouter.nav('#/checkout');
  };

  return (
    <main>
      <div className="container" style={{ paddingBlock: 16 }}>
        <div className="crumb">
          <a href="#/">Home</a><span className="sep">/</span>
          {breadCat?.top && <a href={'#/collections/' + breadCat.top.slug}>{breadCat.top.name}</a>}
          <span className="sep">/</span>
          <span className="here">{p.name}</span>
        </div>
      </div>

      <section className="container" style={{ paddingBottom: 64 }}>
        <div className="pdp-grid">
          <div className="pdp-gallery">
            <div className="pdp-thumbs">
              {galleryIds.map((id, i) => (
                <button key={id + i} type="button" onClick={() => setImageIdx(i)}
                  className={'pdp-thumb' + (imageIdx === i ? ' pdp-thumb--active' : '')}
                  aria-label={'View image ' + (i + 1)}>
                  <img src={id} alt="" decoding="async" loading="lazy" />
                </button>
              ))}
            </div>
            <div className="pdp-main">
              <img src={galleryIds[imageIdx]} alt={p.name + ' — main image'}
                   decoding="async" fetchPriority="high" />
              {off != null && (
                <div className="pdp-main__badge">
                  <span className="tag tag--sale">−{off}% off</span>
                </div>
              )}
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 18, position: 'sticky', top: 'calc(var(--header-h) + 16px)', alignSelf: 'flex-start' }}>
            <div className="eyebrow">{p.vendor} · {p.type}</div>
            <h1 className="serif" style={{ fontSize: 'clamp(2rem, 4vw, 3rem)', lineHeight: 1.05 }}>{p.name}</h1>

            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <Rating value={agg.average} count={agg.count} />
              <span style={{ color: 'var(--muted)', fontSize: '.85rem' }}>· SKU {p.sku}</span>
            </div>

            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 4 }}>
              <span className="serif" style={{ fontSize: '2rem', color: 'var(--ink)' }}>{HAP.formatPrice(livePrice)}</span>
              {liveCompare != null && liveCompare > livePrice && (
                <span style={{ color: 'var(--muted)', textDecoration: 'line-through' }}>{HAP.formatPrice(liveCompare)}</span>
              )}
              {off != null && <span className="tag tag--sale" style={{ marginLeft: 4 }}>Save {HAP.formatPrice(liveCompare - livePrice)}</span>}
            </div>
            <div style={{ fontSize: '.82rem', color: 'var(--muted)' }}>
              Inclusive of applicable GST (see checkout). Free shipping above {HAP.formatPrice(ship.freeAbove)}.
            </div>
            <div style={{ fontSize: '.9rem', fontWeight: 500, color: stock === 'out_of_stock' ? 'var(--danger)' : 'var(--forest)' }}>
              {stockText}
            </div>

            <p style={{ color: 'var(--ink-2)', lineHeight: 1.6, marginTop: 4 }}>{p.blurb}</p>

            <div className="pdp-specs-strip">
              <div className="pdp-specs-strip__item">
                <div className="pdp-specs-strip__icon"><Icon name="package" size={16} /></div>
                <div className="pdp-specs-strip__label">Pack sizes</div>
                <div className="pdp-specs-strip__value">{(p.variants || []).length || 1}</div>
              </div>
              <div className="pdp-specs-strip__item">
                <div className="pdp-specs-strip__icon"><Icon name="spark" size={16} /></div>
                <div className="pdp-specs-strip__label">Colour</div>
                <div className="pdp-specs-strip__value">{p.color || 'Natural'}</div>
              </div>
              <div className="pdp-specs-strip__item">
                <div className="pdp-specs-strip__icon"><Icon name="sun" size={16} /></div>
                <div className="pdp-specs-strip__label">Use</div>
                <div className="pdp-specs-strip__value">Indoor / outdoor</div>
              </div>
              <div className="pdp-specs-strip__item">
                <div className="pdp-specs-strip__icon"><Icon name="ruler" size={16} /></div>
                <div className="pdp-specs-strip__label">Type</div>
                <div className="pdp-specs-strip__value">{p.type || 'Pebble'}</div>
              </div>
            </div>

            <div>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Pack size</div>
              <div role="group" aria-label="Pack size" style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {p.variants.map((v) => {
                  const vp = C.unitPrice(p.price, v);
                  return (
                    <button key={v} type="button" onClick={() => setVariant(v)}
                      aria-pressed={variant === v}
                      style={{
                        padding: '12px 18px', borderRadius: 999, fontSize: '.88rem',
                        border: '1px solid ' + (variant === v ? 'var(--forest)' : 'var(--line-strong)'),
                        background: variant === v ? 'var(--forest)' : 'var(--paper)',
                        color: variant === v ? 'var(--paper)' : 'var(--ink)',
                        cursor: 'pointer'
                      }}>
                      {v}
                      <span style={{ opacity: 0.75, marginLeft: 6, fontSize: '.75rem' }}>{HAP.formatPrice(vp)}</span>
                    </button>
                  );
                })}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
              <div className="cart-line__qty" style={{ height: 52 }}>
                <button onClick={() => setQty((q) => Math.max(1, q - 1))} style={{ width: 44, height: 52 }} aria-label="Decrease quantity"><Icon name="minus" size={16} /></button>
                <span className="count" style={{ width: 36, fontSize: '1rem' }}>{qty}</span>
                <button onClick={() => setQty((q) => q + 1)} style={{ width: 44, height: 52 }} aria-label="Increase quantity"><Icon name="plus" size={16} /></button>
              </div>
              <button className="btn btn--primary btn--lg" style={{ flex: 1, opacity: purchasable ? 1 : 0.5 }}
                      disabled={!purchasable}
                      onClick={() => store.addToCart(p.id, variant, qty)}>
                {purchasable ? ('Add to bag · ' + HAP.formatPrice(livePrice * qty)) : 'Unavailable'}
              </button>
              <button className="icon-btn" onClick={() => store.toggleWishlist(p.id)}
                      style={{ background: wished ? 'var(--terra)' : 'var(--cream)', color: wished ? 'var(--paper)' : 'var(--ink)', width: 52, height: 52 }}
                      title="Wishlist" aria-label="Wishlist">
                <Icon name="heart" />
              </button>
            </div>
            <button className="btn btn--secondary btn--full" disabled={!purchasable} style={{ opacity: purchasable ? 1 : 0.5 }} onClick={buyNow}>
              Buy now
            </button>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginTop: 8, padding: '16px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
              <TrustBadge i="truck" t="Free shipping" s={'On orders above ' + HAP.formatPrice(ship.freeAbove)} />
              <TrustBadge i="shield" t="Quality checked" s="Cleaned & graded" />
              <TrustBadge i="refresh" t="Returns" s="See Help / Returns policy" />
              <TrustBadge i="phone" t="Help & bulk" s="WhatsApp anytime" />
            </div>

            <PincodeCheck />
            <button className="btn btn--ghost btn--sm" onClick={() => {
              if (window.RinpoRuntime) window.RinpoRuntime.open({ tab: 'chat', seed: 'Tell me about ' + product.name, source: 'pdp' });
              else store.openRinpoChat('Tell me about ' + product.name);
            }}>Ask RINPO about this product</button>
          </div>
        </div>
      </section>

      <div className="pdp-sticky-bar">
        <div>
          <div className="pdp-sticky-bar__price">{HAP.formatPrice(livePrice)}</div>
          <div style={{ fontSize: '.72rem', color: 'var(--muted)' }}>{variant}</div>
        </div>
        <button className="btn btn--primary btn--lg" disabled={!purchasable}
                onClick={() => store.addToCart(p.id, variant, qty)}>
          ADD TO CART
        </button>
      </div>

      <section style={{ background: 'var(--cream)', paddingBlock: 'clamp(40px, 5vw, 64px)' }}>
        <div className="container">
          <div role="tablist" style={{ display: 'flex', gap: 6, borderBottom: '1px solid var(--line-strong)', marginBottom: 32, overflowX: 'auto' }}>
            {[
              ['care', 'Using & care'],
              ['details', 'Details'],
              ['ship', 'Shipping & returns'],
              ['reviews', 'Reviews' + (agg.count ? ' (' + agg.count + ')' : '')]
            ].map(([k, t]) => (
              <button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)}
                style={{
                  padding: '14px 18px', fontSize: '.92rem',
                  borderBottom: tab === k ? '2px solid var(--forest)' : '2px solid transparent',
                  color: tab === k ? 'var(--forest)' : 'var(--ink-2)',
                  fontWeight: tab === k ? 600 : 400,
                  marginBottom: -1, whiteSpace: 'nowrap', cursor: 'pointer'
                }}>{t}</button>
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 48 }} className="pdp-tabs-grid">
            {tab === 'care' && <CareTab p={p} />}
            {tab === 'details' && <DetailsTab p={p} />}
            {tab === 'ship' && <ShipTab />}
            {tab === 'reviews' && <ReviewsTab p={p} />}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="spread" style={{ marginBottom: 20 }}>
            <h2 className="serif" style={{ fontSize: 'clamp(1.6rem, 3vw, 2.4rem)' }}>You may also like</h2>
            <a href={'#/collections/' + (cats[1] || cats[0])} className="btn btn--ghost">See more <Icon name="arrow-right" size={14} /></a>
          </div>
          <div className="product-grid product-grid--4">
            {related.map((rp) => <ProductCard key={rp.id} p={rp} />)}
          </div>
        </div>
      </section>
    </main>
  );
}

function TrustBadge({ i, t, s }) {
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <Icon name={i} size={18} style={{ color: 'var(--forest)', marginTop: 2 }} />
      <div>
        <div style={{ fontSize: '.85rem', fontWeight: 500 }}>{t}</div>
        <div style={{ fontSize: '.74rem', color: 'var(--muted)' }}>{s}</div>
      </div>
    </div>
  );
}

function PincodeCheck() {
  const [pin, setPin] = React.useState('');
  const [res, setRes] = React.useState(null);
  const check = () => setRes(window.CustomerCommerce.pincodeCheck(pin));
  return (
    <div style={{ background: 'var(--cream)', borderRadius: 12, padding: 14 }}>
      <div className="eyebrow" style={{ marginBottom: 8 }}>Check pincode format</div>
      <div style={{ display: 'flex', gap: 8 }}>
        <input className="input" placeholder="6-digit pincode" maxLength={6} inputMode="numeric"
               value={pin} onChange={(e) => setPin(e.target.value.replace(/\D/g, ''))}
               style={{ flex: 1, background: 'var(--paper)' }} aria-label="Pincode" />
        <button className="btn btn--primary btn--sm" onClick={check}>Check</button>
      </div>
      {res && (
        <div style={{ marginTop: 10, fontSize: '.85rem', color: res.ok ? 'var(--success)' : 'var(--danger)' }}>
          {res.message}
        </div>
      )}
    </div>
  );
}

function CareTab({ p }) {
  return (
    <>
      <div>
        <h3 className="serif" style={{ fontSize: '1.5rem', marginBottom: 12 }}>Using & care</h3>
        <p style={{ color: 'var(--ink-2)', maxWidth: 540 }}>{p.name} is easy to use and built to last.</p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
        <CareCard icon="spark" title="Top-dress pots" body="Spread a 1–2 cm layer over the soil for a clean finish." />
        <CareCard icon="drop" title="Rinse to refresh" body="A quick rinse restores shine." />
        <CareCard icon="sun" title="Indoor or outdoor" body="Colour is UV-stable outdoors." />
        <CareCard icon="leaf" title="Terrariums & vases" body="Works as drainage or top layer." />
      </div>
    </>
  );
}
function CareCard({ icon, title, body }) {
  return (
    <div style={{ background: 'var(--paper)', borderRadius: 12, padding: 16 }}>
      <Icon name={icon} size={18} style={{ color: 'var(--forest)' }} />
      <div className="serif" style={{ fontSize: '1.05rem', marginTop: 6 }}>{title}</div>
      <div style={{ fontSize: '.85rem', color: 'var(--muted)', marginTop: 4, lineHeight: 1.5 }}>{body}</div>
    </div>
  );
}

function DetailsTab({ p }) {
  return (
    <>
      <div>
        <h3 className="serif" style={{ fontSize: '1.5rem', marginBottom: 12 }}>Details</h3>
        <p style={{ color: 'var(--ink-2)', maxWidth: 540 }}>{p.description}</p>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '.92rem' }}>
        <tbody>
          {[
            ['Product', p.name],
            ['Colour', p.color],
            ['Type', p.type],
            ['Pack sizes', (p.variants || []).join(', ')],
            ['SKU', p.sku]
          ].map(([k, v]) => (
            <tr key={k} style={{ borderBottom: '1px solid var(--line)' }}>
              <td style={{ padding: '14px 0', color: 'var(--muted)', width: '40%' }}>{k}</td>
              <td style={{ padding: '14px 0' }}>{v}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}

function ShipTab() {
  const ship = window.CustomerCommerce.shippingSettings();
  return (
    <>
      <div>
        <h3 className="serif" style={{ fontSize: '1.5rem', marginBottom: 12 }}>Shipping & returns</h3>
        <p style={{ color: 'var(--ink-2)' }}>Amounts come from store settings. Free standard shipping above {HAP.formatPrice(ship.freeAbove)}.</p>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <ShipRow t="Standard delivery" s={'Flat ' + HAP.formatPrice(ship.flat) + ' · free above ' + HAP.formatPrice(ship.freeAbove)} />
        <ShipRow t="Express tracked" s={HAP.formatPrice(ship.express) + ' (from settings)'} />
        <ShipRow t="Returns" s="See Help. Self-serve return workflow is not available yet." />
      </div>
    </>
  );
}
function ShipRow({ t, s }) {
  return (
    <div style={{ background: 'var(--paper)', padding: 16, borderRadius: 12, display: 'flex', gap: 12 }}>
      <Icon name="truck" size={18} style={{ color: 'var(--forest)', marginTop: 2 }} />
      <div>
        <div style={{ fontWeight: 500 }}>{t}</div>
        <div style={{ fontSize: '.85rem', color: 'var(--muted)', marginTop: 2 }}>{s}</div>
      </div>
    </div>
  );
}

function ReviewsTab({ p }) {
  const store = useStore();
  const agg = window.CustomerReviews.aggregate(p.id);
  const user = store.state.user;
  const elig = window.CustomerReviews.eligibility(user, p.id);
  const [form, setForm] = React.useState({ rating: 5, title: '', content: '' });
  const [msg, setMsg] = React.useState('');

  const submit = (e) => {
    e.preventDefault();
    try {
      window.CustomerReviews.submit(user, { productId: p.id, rating: form.rating, title: form.title, content: form.content });
      if (window.CustomerAnalytics) window.CustomerAnalytics.review_submitted(p.id);
      setMsg('Review submitted — status: pending moderation.');
      setForm({ rating: 5, title: '', content: '' });
    } catch (err) {
      setMsg(err.message || 'Could not submit review');
    }
  };

  return (
    <>
      <div>
        <h3 className="serif" style={{ fontSize: '1.5rem', marginBottom: 12 }}>Reviews</h3>
        {agg.count > 0 ? (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
            <span className="serif" style={{ fontSize: '3rem', lineHeight: 1 }}>{agg.average.toFixed(1)}</span>
            <Rating value={agg.average} count={agg.count} />
          </div>
        ) : (
          <p style={{ color: 'var(--muted)' }}>No published reviews yet. We do not show fabricated ratings.</p>
        )}

        {elig.ok ? (
          <form onSubmit={submit} style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <label className="field"><span>Rating</span>
              <select className="input" value={form.rating} onChange={(e) => setForm({ ...form, rating: Number(e.target.value) })}>
                {[5, 4, 3, 2, 1].map((n) => <option key={n} value={n}>{n}</option>)}
              </select>
            </label>
            <label className="field" htmlFor="review-title"><span>Title</span>
              <input id="review-title" className="input" placeholder="Title (optional)" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
            </label>
            <label className="field" htmlFor="review-content"><span>Your review</span>
              <textarea id="review-content" className="textarea" placeholder="Your experience" value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} required />
            </label>
            <button className="btn btn--secondary" type="submit">Submit review</button>
          </form>
        ) : (
          <p style={{ marginTop: 16, fontSize: '.9rem', color: 'var(--ink-2)' }}>{elig.message}</p>
        )}
        {msg && <p style={{ marginTop: 10, fontSize: '.85rem', color: 'var(--forest)' }}>{msg}</p>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {agg.rows.length === 0 ? (
          <EmptyState icon="star" title="No published reviews" note="Eligible buyers can review after delivery." />
        ) : agg.rows.map((r) => (
          <div key={r.id} style={{ borderBottom: '1px solid var(--line)', paddingBottom: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{ width: 36, height: 36, borderRadius: 999, background: 'var(--sage-2)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, color: 'var(--forest)' }}>{(r.name || 'A')[0]}</div>
              <div>
                <div style={{ fontSize: '.92rem', fontWeight: 500 }}>{r.name}</div>
                <div style={{ fontSize: '.74rem', color: 'var(--muted)' }}>Verified purchase · {new Date(r.createdAt).toLocaleDateString('en-IN')}</div>
              </div>
              <div style={{ marginLeft: 'auto' }}><Rating value={r.rating} /></div>
            </div>
            {r.title && <div className="serif" style={{ fontSize: '1.05rem', marginBottom: 4 }}>{r.title}</div>}
            <p style={{ color: 'var(--ink-2)', fontSize: '.9rem' }}>{r.content}</p>
          </div>
        ))}
      </div>
    </>
  );
}

window.ProductPage = ProductPage;
