// Product card + grid + detail panel

const { useEffect: _e2, useRef: _r2, useState: _s2 } = React;

function ProductCard({ p, isSaved, showPrice, onOpen, onSave }) {
  const ageLabel = formatAge(p.ageMin, p.ageMax);
  return (
    <article className="card" onClick={() => onOpen(p)}>
      <div className="card-img">
        <img src={p.img} alt={p.name} loading="lazy" />
        <button
          className={`card-save${isSaved ? ' is-saved' : ''}`}
          onClick={(e) => { e.stopPropagation(); onSave(p.id); }}
          aria-label="Save"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill={isSaved ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.6">
            <path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>
          </svg>
        </button>
        <div className="card-tag">{p.benefit}</div>
      </div>
      <div className="card-body">
        <div className="card-brand">{p.brand}</div>
        <h3 className="card-name">{p.name}</h3>
        <div className="card-meta">
          <span className="card-age">{ageLabel}</span>
          {showPrice && <span className="card-price">${p.price}</span>}
        </div>
      </div>
    </article>
  );
}

function formatAge(min, max) {
  if (min === -1) return 'Pre-baby';
  if (max <= 12) return `${min}–${max} months`;
  const minY = Math.floor(min / 12);
  const maxY = Math.floor(max / 12);
  if (maxY >= 16) return `${minY}+ years`;
  return `${minY || '0'}–${maxY} years`;
}

function ProductGrid({ products, saved, showPrice, onOpen, onSave }) {
  if (products.length === 0) {
    return (
      <div className="empty">
        <h3 className="empty-title">No matches just yet</h3>
        <p>Try widening the price range, or clearing a filter.</p>
      </div>
    );
  }
  return (
    <div className="grid">
      {products.map(p => (
        <ProductCard
          key={p.id}
          p={p}
          isSaved={saved.includes(p.id)}
          showPrice={showPrice}
          onOpen={onOpen}
          onSave={onSave}
        />
      ))}
    </div>
  );
}

function DetailPanel({
  product, isSaved, isWishlisted, isOwned,
  onClose, onSave, onToggleWishlist, onToggleOwned,
  onAddToList, onCreateList,
  userLists, ctx, onPickProduct,
}) {
  const [galIdx, setGalIdx] = useState(0);
  const [listPickerOpen, setListPickerOpen] = useState(false);
  useEffect(() => { setGalIdx(0); setListPickerOpen(false); }, [product?.id]);

  const open = !!product;
  const p = product || { name: '', brand: '', price: 0, ageMin: 0, ageMax: 0, why: '', img: '', gallery: [], retailers: [], learning: [], benefit: '' };
  const ageLabel = formatAge(p.ageMin, p.ageMax);
  const gallery = p.gallery && p.gallery.length ? p.gallery : [p.img];

  // Prev/next within the context list (if any)
  const ctxArr = Array.isArray(ctx) ? ctx : [];
  const idx = open ? ctxArr.findIndex(x => x && x.id === p.id) : -1;
  const prev = idx > 0 ? ctxArr[idx - 1] : null;
  const next = idx >= 0 && idx < ctxArr.length - 1 ? ctxArr[idx + 1] : null;
  const total = ctxArr.length;

  const goPrev = () => { if (prev) onPickProduct(prev); };
  const goNext = () => { if (next) onPickProduct(next); };

  // Global keyboard nav while open.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      const tag = e.target && e.target.tagName;
      if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable)) return;
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      if (e.key === 'ArrowLeft' && prev) { e.preventDefault(); goPrev(); }
      else if (e.key === 'ArrowRight' && next) { e.preventDefault(); goNext(); }
      else if (e.key === 'l' || e.key === 'L') { e.preventDefault(); onSave(p.id); }
      else if (e.key === 'w' || e.key === 'W') { e.preventDefault(); onToggleWishlist && onToggleWishlist(p.id); }
      else if (e.key === 'o' || e.key === 'O') { e.preventDefault(); onToggleOwned && onToggleOwned(p.id); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, prev, next, p.id, onSave, onToggleWishlist, onToggleOwned]);

  // Close list picker on outside click
  useEffect(() => {
    if (!listPickerOpen) return;
    const onClick = (e) => {
      if (!e.target.closest('.list-picker-pop') && !e.target.closest('[data-list-picker-trigger]')) setListPickerOpen(false);
    };
    setTimeout(() => document.addEventListener('click', onClick), 50);
    return () => document.removeEventListener('click', onClick);
  }, [listPickerOpen]);

  return (
    <>
      <div className={`scrim${open ? ' is-open' : ''}`} onClick={onClose} />
      <aside className={`detail${open ? ' is-open' : ''}`} aria-hidden={!open}>
        <div className="detail-topnav">
          <button className="detail-close" onClick={onClose} aria-label="Close" data-tip="Close · Esc">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
          </button>
          {total > 1 && (
            <div className="detail-pager">
              <button
                className="detail-pager-btn"
                onClick={goPrev}
                disabled={!prev}
                aria-label="Previous"
                data-tip="Previous · ←"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M15 6l-6 6 6 6"/></svg>
              </button>
              <span className="detail-pager-count">{idx + 1} / {total}</span>
              <button
                className="detail-pager-btn"
                onClick={goNext}
                disabled={!next}
                aria-label="Next"
                data-tip="Next · →"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M9 6l6 6-6 6"/></svg>
              </button>
            </div>
          )}
        </div>

        <div className="detail-scroll">
          <div className="detail-gallery">
            <img src={gallery[galIdx]} alt={p.name} style={{ transform: `translateX(0)` }} />
            <div className="detail-dots">
              {gallery.map((_, i) => (
                <button key={i} className={`detail-dot${i === galIdx ? ' is-active' : ''}`} onClick={() => setGalIdx(i)} />
              ))}
            </div>
          </div>
          <div className="detail-body">
            <div className="detail-brand">{p.brand}</div>
            <h2 className="detail-name">{p.name}</h2>
            <div className="detail-meta">
              <span className="price">${p.price}</span>
              <span className="dot" />
              <span>{ageLabel}</span>
              <span className="dot" />
              <span>{p.benefit}</span>
            </div>

            <div className="detail-quickactions">
              <button
                className={`detail-quick detail-quick--loved${isSaved ? ' is-on' : ''}`}
                onClick={() => onSave(p.id)}
                data-tip={isSaved ? 'Loved · L to remove' : 'Save to Loved · L'}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill={isSaved ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.8"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
                <span>{isSaved ? 'Loved' : 'Love'}</span>
              </button>
              <button
                className={`detail-quick detail-quick--wishlist${isWishlisted ? ' is-on' : ''}`}
                onClick={() => onToggleWishlist && onToggleWishlist(p.id)}
                data-tip={isWishlisted ? 'On wishlist · W to remove' : 'Add to wishlist · W'}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill={isWishlisted ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.6"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>
                <span>{isWishlisted ? 'Wishlisted' : 'Wishlist'}</span>
              </button>
              <button
                className={`detail-quick detail-quick--owned${isOwned ? ' is-on' : ''}`}
                onClick={() => onToggleOwned && onToggleOwned(p.id)}
                data-tip={isOwned ? "Marked as owned · O to remove" : "Mark as owned · O"}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9"><circle cx="12" cy="12" r="9.5"/><path d="M7.5 12.5l3 3L17 9"/></svg>
                <span>{isOwned ? 'Got it' : 'I own one'}</span>
              </button>
              <div className="detail-quick-listwrap">
                <button
                  className="detail-quick detail-quick--list"
                  onClick={() => setListPickerOpen(o => !o)}
                  aria-expanded={listPickerOpen}
                  data-list-picker-trigger
                  data-tip="Add to a list"
                >
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg>
                  <span>Add to list</span>
                </button>
                {listPickerOpen && (
                  <div className="list-picker-pop" role="dialog" aria-label="Add to list">
                    <div className="list-picker-h">Add to a list</div>
                    {(userLists || []).length === 0 ? (
                      <div className="list-picker-empty">No lists yet.</div>
                    ) : (
                      <ul className="list-picker-list">
                        {(userLists || []).map(l => (
                          <li key={l.id}>
                            <button
                              className={`list-picker-item${(l.productIds || []).includes(p.id) ? ' is-on' : ''}`}
                              onClick={() => { if (!(l.productIds || []).includes(p.id)) { onAddToList(l.id, p.id); } setListPickerOpen(false); }}
                            >
                              <span className="list-picker-name">{l.name}</span>
                              <span className="list-picker-meta">{(l.productIds || []).length} items</span>
                              {(l.productIds || []).includes(p.id) && (
                                <span className="list-picker-check"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg></span>
                              )}
                            </button>
                          </li>
                        ))}
                      </ul>
                    )}
                    <button className="list-picker-create" onClick={() => { setListPickerOpen(false); onCreateList && onCreateList(); }}>
                      <span className="plus">+</span>
                      <span>Create new list</span>
                    </button>
                  </div>
                )}
              </div>
            </div>

            <div className="detail-section">
              <div className="detail-h">Why we love it</div>
              <p className="detail-why">{p.why}</p>
            </div>

            {p.learning && p.learning.length > 0 && (
              <div className="detail-section">
                <div className="detail-h">Learning Focus</div>
                <div className="detail-tags">
                  {p.learning.map(l => {
                    const lbl = (window.LEARNING.find(x => x.key === l) || {}).label || l;
                    return <span key={l} className="detail-pill">{lbl}</span>;
                  })}
                </div>
              </div>
            )}

            {total > 1 && (
              <div className="detail-keyhint">Use ← → to flip between {total} items</div>
            )}
          </div>
        </div>
        <div className="detail-actions">
          {p.retailers && p.retailers[0] && (
            <button className="btn">
              <span className="btn-row">
                <span className="btn-logo">{p.retailers[0][0]}</span>
                Buy on {p.retailers[0]}
              </span>
              <span className="arrow">→</span>
            </button>
          )}
        </div>
      </aside>
    </>
  );
}

window.ProductCard = ProductCard;
window.ProductGrid = ProductGrid;
window.DetailPanel = DetailPanel;
window.formatAge = formatAge;
