// HimLocal — v2.7 Product display page, Editorial / FAQ / Legal templates,
//                  Search results, Filters bar — desktop + mobile

const { useState: useStateWPdp, useMemo: useMemoWPdp } = React;

// ─── Variant + gallery generation helpers ────────────────
// Products in `data-v2.js` are intentionally lean; PDPs synthesise
// per-category galleries, swatches and sizes so we don't have to
// hand-author every detail across 18 products.
const PDP_GALLERY_BY_CAT = {
  wool:  ['https://images.unsplash.com/photo-1606760227091-3dd870d97f1d?w=1200','https://images.unsplash.com/photo-1620799140188-3b2a02fd9a77?w=1200','https://images.unsplash.com/photo-1601244005535-a48d21d951ac?w=1200','https://images.unsplash.com/photo-1603487742131-4160ec999306?w=1200'],
  ghee:  ['https://images.unsplash.com/photo-1628088062854-d1870b4553da?w=1200','https://images.unsplash.com/photo-1559561853-08451507cbe7?w=1200','https://images.unsplash.com/photo-1542990253-0d0f5be5f0ed?w=1200','https://images.unsplash.com/photo-1559925393-8be0ec4767c8?w=1200'],
  fruit: ['https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?w=1200','https://images.unsplash.com/photo-1567721913486-6585f069b332?w=1200','https://images.unsplash.com/photo-1604908554049-5e2f7fbcd6cb?w=1200','https://images.unsplash.com/photo-1577003833619-76bbd7f82948?w=1200'],
  honey: ['https://images.unsplash.com/photo-1587049352846-4a222e784d38?w=1200','https://images.unsplash.com/photo-1597481499750-3e6b22637e12?w=1200','https://images.unsplash.com/photo-1576092768241-dec231879fc3?w=1200','https://images.unsplash.com/photo-1495474472287-4d71bcdd2085?w=1200'],
  craft: ['https://images.unsplash.com/photo-1577705998148-6da4f3963bc8?w=1200','https://images.unsplash.com/photo-1582719471384-894fbb16e074?w=1200','https://images.unsplash.com/photo-1606498679340-0aec3185edbd?w=1200','https://images.unsplash.com/photo-1604908554049-5e2f7fbcd6cb?w=1200'],
  spice: ['https://images.unsplash.com/photo-1582284540020-8acbe03f4924?w=1200','https://images.unsplash.com/photo-1532336414038-cf19250c5757?w=1200','https://images.unsplash.com/photo-1564844536311-de546a28c87d?w=1200','https://images.unsplash.com/photo-1604908554049-5e2f7fbcd6cb?w=1200'],
};

const PDP_VARIANT_BY_CAT = {
  wool:  { color:[{name:'Natural',hex:'#d8c9a7'},{name:'Charcoal',hex:'#3a3a40'},{name:'Indigo',hex:'#1f3b57'},{name:'Saffron',hex:'#c98a2a'}], size:[{name:'S'},{name:'M'},{name:'L',badge:'low stock'},{name:'XL'}] },
  ghee:  { size:[{name:'250 g',mod:-200},{name:'500 g'},{name:'1 kg',mod:+820}] },
  fruit: { size:[{name:'200 g',mod:-80},{name:'320 g'},{name:'500 g',mod:+220,badge:'best value'}] },
  honey: { size:[{name:'200 g',mod:-200},{name:'350 g'},{name:'750 g',mod:+540}] },
  craft: { color:[{name:'Brass',hex:'#b8862a'},{name:'Copper',hex:'#a05524'},{name:'Antique',hex:'#5e4628'}] },
  spice: { size:[{name:'30 g'},{name:'80 g',mod:+220},{name:'200 g',mod:+760,badge:'low stock'}] },
};

const PDP_BENEFITS = [
  { i:'⌖', t:'Hand-made', d:'Each piece is signed by the maker.' },
  { i:'↩', t:'7-day returns', d:'Damage in transit refunded in full.' },
  { i:'✓', t:'Free shipping', d:'On orders above ₹2,000 within India.' },
  { i:'✦', t:'Vendor-direct', d:'Money goes straight to the maker.' },
];

const PDP_REVIEWS_SEED = [
  { id:'r1', author:'Priya M.',   initials:'PM', when:'Sep 2025', stars:5, verified:true,  text:'The wool is heavier than I expected — proper Himalayan winter quality. The smell of woodsmoke from the hands that made it is gone after the first wash.', tags:['True to photo','Heavier than expected'] },
  { id:'r2', author:'Devansh K.', initials:'DK', when:'Aug 2025', stars:5, verified:true,  text:'Worth every rupee. Beautiful weave. I bought one and immediately ordered a second for my mother. Maker added a hand-written note inside the box, which made my day.', tags:['Gift','Note from maker'] },
  { id:'r3', author:'Anita J.',   initials:'AJ', when:'May 2025', stars:4, verified:true,  text:'Lovely piece. Shipping took 9 days instead of 7 but the courier called ahead, which I appreciated. Colour is closer to mustard than the saffron in the photos.', tags:['Colour slightly off'] },
  { id:'r4', author:'Maya R.',    initials:'MR', when:'Apr 2025', stars:5, verified:true,  text:'I went to the workshop in person while in Manali — they showed me the loom this was made on. Buy with confidence; the makers are real.', tags:['Met the maker'] },
  { id:'r5', author:'Vikram S.',  initials:'VS', when:'Feb 2025', stars:5, verified:false, text:'Came as part of a curated trip-essentials bundle. The fact that this gets sold direct from the artisan is the point — the price-to-quality is unmatched.', tags:[] },
];

const PDP_QA_SEED = [
  { id:'q1', q:'Is this machine-washable?',    a:'Hand-wash recommended for the first three washes, then cold machine cycle on wool setting. Dry flat — never tumble dry.', by:'Sangye · vendor',  when:'2 weeks ago' },
  { id:'q2', q:'Will the colour run?',         a:'Naturally dyed with walnut bark and indigo. There may be slight bleed on the first wash; wash separately the first time.', by:'Sangye · vendor',  when:'1 month ago' },
  { id:'q3', q:'Can you ship to Singapore?',   a:'Yes, international shipping is by India Post (12—21 days) or DHL (5—7 days). Message us with your address for a quote.', by:'HimLocal team',     when:'3 weeks ago' },
];

function pdpComputeUnit(product, sizeIdx, colorIdx, cat) {
  const v = PDP_VARIANT_BY_CAT[cat] || {};
  const sizeMod  = v.size  ? (v.size[sizeIdx]?.mod  || 0) : 0;
  return product.price + sizeMod;
}

// ─── Desktop: PDP ───────────────────────────────────────
function WebProductDetail({ product, vendor, related, onBack, onAddToCart, onAddWishlist, onOpenVendor, wishlisted, onZoom }) {
  if (!product) return null;
  const cat = product.cat || 'wool';
  const variantOpts = PDP_VARIANT_BY_CAT[cat] || {};
  const hasColor = !!(variantOpts.color && variantOpts.color.length);
  const hasSize  = !!(variantOpts.size  && variantOpts.size.length);

  const gallery = PDP_GALLERY_BY_CAT[cat] || [product.img, product.img, product.img, product.img];

  const [galleryIdx, setGalleryIdx] = useStateWPdp(0);
  const [colorIdx,   setColorIdx]   = useStateWPdp(0);
  const [sizeIdx,    setSizeIdx]    = useStateWPdp(hasSize ? Math.max(0, variantOpts.size.findIndex(s => !s.mod || s.mod === 0)) : 0);
  const [qty,        setQty]        = useStateWPdp(1);
  const [tab,        setTab]        = useStateWPdp('about');
  const [note,       setNote]       = useStateWPdp('');
  const [reviewFilt, setReviewFilt] = useStateWPdp('all');
  const [reviewSort, setReviewSort] = useStateWPdp('helpful');

  const unit = pdpComputeUnit(product, sizeIdx, colorIdx, cat);
  const strike = Math.round(unit * 1.14);
  const reviews = useMemoWPdp(() => {
    let l = PDP_REVIEWS_SEED;
    if (reviewFilt !== 'all') {
      if (reviewFilt === 'verified') l = l.filter(r => r.verified);
      else if (reviewFilt === '5')    l = l.filter(r => r.stars === 5);
      else if (reviewFilt === '4-')   l = l.filter(r => r.stars <= 4);
      else if (reviewFilt === 'photo') l = l.filter(r => r.tags && r.tags.length);
    }
    if (reviewSort === 'new')    l = [...l].sort((a, b) => a.when.localeCompare(b.when) > 0 ? -1 : 1);
    return l;
  }, [reviewFilt, reviewSort]);

  const variantSummary = [
    hasColor && variantOpts.color[colorIdx]?.name,
    hasSize  && variantOpts.size[sizeIdx]?.name,
  ].filter(Boolean).join(' · ');

  const onAdd = () => {
    onAddToCart(product.id, qty, variantSummary || undefined, note.trim() || undefined);
  };

  return (
    <div className="w2-pdp w2-route">
      <div className="w2-pdp__crumb">
        <button className="w2-pdp__crumb-back" onClick={onBack}>← Shop</button>
        <span className="w2-pdp__crumb-sep">›</span>
        <span style={{textTransform:'capitalize'}}>{cat}</span>
        <span className="w2-pdp__crumb-sep">›</span>
        <span style={{color:'var(--slate-700)'}}>{product.name}</span>
      </div>

      <div className="w2-pdp__grid">
        {/* Gallery */}
        <div className="w2-pdp__gal">
          <div className="w2-pdp__gal-thumbs">
            {gallery.map((src, i) => (
              <button key={i} className={`w2-pdp__gal-thumb ${i === galleryIdx ? 'is-on' : ''}`}
                style={{ backgroundImage:`url(${src})` }} onClick={() => setGalleryIdx(i)} aria-label={`Image ${i + 1}`}/>
            ))}
          </div>
          <div className="w2-pdp__gal-main" style={{ backgroundImage:`url(${gallery[galleryIdx]})` }}
            onClick={() => onZoom && onZoom(gallery, galleryIdx)}>
            <span className="w2-pdp__gal-pill">Frame · {galleryIdx + 1} of {gallery.length}</span>
            <button className="w2-pdp__gal-zoom" onClick={e => { e.stopPropagation(); onZoom && onZoom(gallery, galleryIdx); }}>⤢</button>
          </div>
        </div>

        {/* Right rail */}
        <div className="w2-pdp__rail">
          <div>
            {vendor && (
              <button className="w2-pdp__vendor-link" onClick={() => onOpenVendor && onOpenVendor(vendor)}>
                {vendor.name} · {vendor.loc}
              </button>
            )}
            <h1 className="w2-pdp__name">{product.name}</h1>
            <p className="w2-pdp__sub">{product.weight ? `${product.weight} · ` : ''}Hand-made in the Himalayas. Signed by the maker.</p>
            <div className="w2-pdp__rating">
              <span className="w2-pdp__rating-stars">★★★★★</span>
              <span className="w2-pdp__rating-n">4.8 · 312 reviews</span>
              <button className="w2-pdp__rating-link" onClick={() => { setTab('reviews'); document.querySelector('.w2-pdp__below')?.scrollIntoView({behavior:'smooth',block:'start'}); }}>Read</button>
            </div>
          </div>

          <div className="w2-pdp__price">
            <span className="w2-pdp__price-v">₹{unit.toLocaleString()}</span>
            <span className="w2-pdp__price-strike">₹{strike.toLocaleString()}</span>
            <span className="w2-pdp__price-save">Save {Math.round((1 - unit / strike) * 100)}%</span>
          </div>

          {hasColor && (
            <div className="w2-pdp__opt-group">
              <div className="w2-pdp__opt-head">
                Choose colour <strong>· {variantOpts.color[colorIdx].name}</strong>
              </div>
              <div className="w2-pdp__opt-row">
                {variantOpts.color.map((c, i) => (
                  <button key={i} className={`w2-pdp__opt ${i === colorIdx ? 'is-on' : ''}`}
                    onClick={() => setColorIdx(i)}>
                    <span className="w2-pdp__opt-swatch" style={{ background:c.hex }}/>
                    {c.name}
                  </button>
                ))}
              </div>
            </div>
          )}

          {hasSize && (
            <div className="w2-pdp__opt-group">
              <div className="w2-pdp__opt-head">
                Size <strong>· {variantOpts.size[sizeIdx].name}</strong>
                <button className="w2-pdp__opt-help">Size guide ↗</button>
              </div>
              <div className="w2-pdp__opt-row">
                {variantOpts.size.map((s, i) => (
                  <button key={i} className={`w2-pdp__opt ${i === sizeIdx ? 'is-on' : ''}`}
                    onClick={() => setSizeIdx(i)}>
                    {s.name}
                    {s.badge && <span className="w2-pdp__opt-meta">· {s.badge}</span>}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div className="w2-pdp__special">
            <div className="w2-pdp__special-l">
              Note for the maker
              <span className="w2-pdp__special-tag">Optional</span>
            </div>
            <textarea
              value={note}
              maxLength={240}
              onChange={e => setNote(e.target.value)}
              placeholder="e.g. gift wrap with kraft paper, no plastic — or leave blank."/>
            <div className="w2-pdp__special-help">
              {note.length}/240 · For monograms, dietary requests, or delivery instructions. The vendor sees this exactly as you type it.
            </div>
          </div>

          <div className="w2-pdp__cta-row">
            <div className="w2-pdp__qty">
              <button onClick={() => setQty(q => Math.max(1, q - 1))} aria-label="Decrease quantity">−</button>
              <span>{qty}</span>
              <button onClick={() => setQty(q => q + 1)} aria-label="Increase quantity">+</button>
            </div>
            <button className="w2-pdp__add" onClick={onAdd}>
              <span>Add to basket</span>
              <span className="w2-pdp__add-price">· ₹{(unit * qty).toLocaleString()}</span>
            </button>
            <button className={`w2-pdp__wishlist ${wishlisted ? 'is-on' : ''}`}
              onClick={() => onAddWishlist && onAddWishlist(product.id)} aria-label="Save to wishlist">
              {wishlisted ? '♥' : '♡'}
            </button>
          </div>

          <div className="w2-pdp__benefits">
            {PDP_BENEFITS.map((b, i) => (
              <div key={i} className="w2-pdp__benefit">
                <div className="w2-pdp__benefit-icon">{b.i}</div>
                <div>
                  <div className="w2-pdp__benefit-t">{b.t}</div>
                  <div className="w2-pdp__benefit-d">{b.d}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Below the fold */}
      <div className="w2-pdp__below">
        <section>
          <div className="w2-pdp__tabs">
            {[
              ['about',    'About'],
              ['spec',     'Specs'],
              ['shipping', 'Shipping & returns'],
              ['reviews',  `Reviews · ${PDP_REVIEWS_SEED.length}`],
              ['qa',       'Questions'],
            ].map(([id, label]) => (
              <button key={id} className={`w2-pdp__tab ${tab === id ? 'is-on' : ''}`} onClick={() => setTab(id)}>
                {label}
              </button>
            ))}
          </div>

          {tab === 'about' && (
            <div className="w2-pdp__desc">
              <p>{product.name} is hand-made by {vendor?.name || 'a local artisan'} in {vendor?.loc || 'the Himalayas'}. Each piece is signed by the maker and ships with a small card naming the village, the family workshop, and the date it left the loom.</p>
              <p>Allow 1—2 cm variation in finish — the texture comes from being made by hand, not a machine. Most pieces are sold within two weeks of completion; in winter, lead times extend a bit while wool is being prepared.</p>
            </div>
          )}
          {tab === 'spec' && (
            <dl className="w2-pdp__spec">
              <dt>Material</dt><dd>{cat === 'wool' ? '100% Himalayan sheep wool, hand-spun' : cat === 'craft' ? 'Sand-cast brass, hand-hammered' : cat === 'ghee' ? 'Single-source cow ghee, slow-clarified' : 'Single-origin Himalayan'}</dd>
              <dt>Weight</dt><dd>{product.weight || '—'}</dd>
              <dt>Origin</dt><dd>{vendor?.loc || 'Himachal Pradesh'}</dd>
              <dt>Care</dt><dd>{cat === 'wool' ? 'Hand-wash, dry flat, no bleach' : cat === 'craft' ? 'Polish with dry cloth; lemon for tarnish' : 'Store in a cool, dry place'}</dd>
              <dt>Maker</dt><dd>{vendor?.name || 'Local artisan'}</dd>
              <dt>Lead time</dt><dd>Made on order — 3 working days</dd>
              <dt>SKU</dt><dd className="mono">HL-{product.id?.toUpperCase()}</dd>
            </dl>
          )}
          {tab === 'shipping' && (
            <div className="w2-pdp__policy">
              <div className="w2-pdp__policy-card">
                <div className="w2-pdp__policy-l">India</div>
                <div className="w2-pdp__policy-t">5—7 days · ₹120 flat</div>
                <div className="w2-pdp__policy-d">Free over ₹2,000. Tracked by Bluedart. Courier calls ahead.</div>
              </div>
              <div className="w2-pdp__policy-card">
                <div className="w2-pdp__policy-l">International</div>
                <div className="w2-pdp__policy-t">12—21 days · from ₹1,400</div>
                <div className="w2-pdp__policy-d">India Post EMS or DHL. Duties at destination — message us first.</div>
              </div>
              <div className="w2-pdp__policy-card">
                <div className="w2-pdp__policy-l">Returns</div>
                <div className="w2-pdp__policy-t">7-day no-questions</div>
                <div className="w2-pdp__policy-d">Return for any reason within 7 days. Damage in transit fully refunded.</div>
              </div>
            </div>
          )}
          {tab === 'reviews' && (
            <>
              <div className="w2-pdp__rev-summary">
                <div>
                  <div className="w2-pdp__rev-score">4.8</div>
                  <div className="w2-pdp__rev-stars">★★★★★</div>
                  <div className="w2-pdp__rev-count">312 reviews · 96% would recommend</div>
                </div>
                <div className="w2-pdp__rev-bars">
                  {[[5,82],[4,12],[3,4],[2,1],[1,1]].map(([star, pct]) => (
                    <div key={star} className="w2-pdp__rev-bar">
                      <span>{star}★</span>
                      <div className="w2-pdp__rev-bar-track"><div className="w2-pdp__rev-bar-fill" style={{ width:`${pct}%` }}/></div>
                      <span>{pct}%</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="w2-pdp__rev-tools">
                <div className="w2-pdp__rev-filters">
                  {[['all','All'],['5','5 stars only'],['4-','4 stars & below'],['verified','Verified buyers'],['photo','With tags']].map(([id, label]) => (
                    <button key={id} className={`w2-pdp__rev-filter ${reviewFilt === id ? 'is-on' : ''}`} onClick={() => setReviewFilt(id)}>{label}</button>
                  ))}
                </div>
                <select className="w2-pdp__rev-sort" value={reviewSort} onChange={e => setReviewSort(e.target.value)}>
                  <option value="helpful">Most helpful</option>
                  <option value="new">Most recent</option>
                </select>
              </div>
              {reviews.map(r => (
                <div key={r.id} className="w2-pdp__rev-card">
                  <div className="w2-pdp__rev-avatar">{r.initials}</div>
                  <div>
                    <div className="w2-pdp__rev-meta">{r.author}</div>
                    <div className="w2-pdp__rev-when">{r.when}{r.verified && ` · verified buyer`}</div>
                    <div className="w2-pdp__rev-stars-sm">{'★'.repeat(r.stars)}{'☆'.repeat(5 - r.stars)}</div>
                    <p className="w2-pdp__rev-text">{r.text}</p>
                    {r.tags && r.tags.length > 0 && (
                      <div className="w2-pdp__rev-tags">
                        {r.tags.map((t, j) => <span key={j} className="w2-pdp__rev-tag">{t}</span>)}
                      </div>
                    )}
                  </div>
                  {r.verified && <div className="w2-pdp__rev-vbadge" style={{alignSelf:'start',whiteSpace:'nowrap'}}>Verified</div>}
                </div>
              ))}
              <button style={{marginTop:18,padding:'12px 22px',background:'var(--bone-100)',border:'1px solid var(--border-1)',borderRadius:999,cursor:'pointer',font:'600 12px var(--font-body)',color:'var(--slate-700)'}}>
                Read all 312 reviews →
              </button>
            </>
          )}
          {tab === 'qa' && (
            <div>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
                <p className="w2-sech__sub" style={{margin:0}}>Buyers and the maker answer here. 24-hour median reply.</p>
                <button className="w2-btn w2-btn--quiet w2-btn--sm">Ask a question</button>
              </div>
              {PDP_QA_SEED.map(q => (
                <div key={q.id} className="w2-pdp__qa-card">
                  <div className="w2-pdp__qa-q">Q · {q.q}</div>
                  <div className="w2-pdp__qa-a">A · {q.a}</div>
                  <div className="w2-pdp__qa-meta">— {q.by} · {q.when}</div>
                </div>
              ))}
            </div>
          )}
        </section>

        {vendor && (
          <section>
            <h2 className="w2-sech__t">Meet the <em>maker</em></h2>
            <div className="w2-pdp__vendor-card">
              <div className="w2-pdp__vendor-img" style={{ backgroundImage:`url(${vendor.img})` }}/>
              <div>
                <div className="w2-pdp__vendor-t">{vendor.name}</div>
                <div className="w2-pdp__vendor-l">{vendor.loc}</div>
                <div className="w2-pdp__vendor-d">{vendor.story || 'A family workshop, three generations in. The looms are wooden, the patterns walk back to grandmother. Buying from HimLocal goes directly to the artisan — there is no middleman.'}</div>
              </div>
              <button className="w2-btn w2-btn--ghost" onClick={() => onOpenVendor && onOpenVendor(vendor)}>Visit vendor →</button>
            </div>
          </section>
        )}

        {related && related.length > 0 && (
          <section>
            <h2 className="w2-sech__t">From the same <em>workshop</em></h2>
            <div className="w2-pdp__related">
              {related.map(p => (
                <button key={p.id} className="w2-pdp__related-card" onClick={onBack}>
                  <div className="w2-pdp__related-img" style={{ backgroundImage:`url(${p.img})` }}/>
                  <div className="w2-pdp__related-t">{p.name}</div>
                  <div className="w2-pdp__related-p">₹{p.price.toLocaleString()}</div>
                </button>
              ))}
            </div>
          </section>
        )}
      </div>
    </div>
  );
}
window.WebProductDetail = WebProductDetail;

// ─── Desktop: Editorial / FAQ / About / Legal ──────────
function WebEditorialPage({ title, lede, sections, updatedAt, type = 'rich', onBack }) {
  const [openIdx, setOpenIdx] = useStateWPdp(0);
  return (
    <div className="w2-edit w2-route">
      <div className="w2-edit__inner" style={{maxWidth:1100}}>
        <button onClick={onBack} style={{background:0,border:0,font:'600 11px var(--font-body)',letterSpacing:'.14em',color:'var(--fg-3)',cursor:'pointer',padding:0,marginBottom:14}}>← BACK</button>
        <div className="w2-edit__crumb">HimLocal · {type === 'faq' ? 'FAQ' : 'Field guide'}</div>
        <h1 className="w2-edit__title">{title}</h1>
        {lede && <div className="w2-edit__lede">{lede}</div>}

        <div className="w2-edit__layout">
          <aside className="w2-edit__nav">
            <div className="w2-edit__nav-l">On this page</div>
            {sections.map((s, i) => (
              <a key={i} className={openIdx === i ? 'is-on' : ''} onClick={() => setOpenIdx(i)}>{s.title}</a>
            ))}
          </aside>

          <div className="w2-rich">
            {type === 'faq' ? (
              <div className="w2-faq">
                {sections.map((s, i) => (
                  <div key={i} className={`w2-faq__item ${openIdx === i ? 'is-open' : ''}`}>
                    <button className="w2-faq__q" onClick={() => setOpenIdx(openIdx === i ? -1 : i)}>
                      <span>{s.title}</span>
                      <span className="w2-faq__chev">+</span>
                    </button>
                    <div className="w2-faq__a">{s.body}</div>
                  </div>
                ))}
              </div>
            ) : (
              sections.map((s, i) => (
                <section key={i}>
                  <h2>{s.title}</h2>
                  {typeof s.body === 'string' ? <p>{s.body}</p> : s.body}
                </section>
              ))
            )}
            {updatedAt && <div className="w2-edit__updated">Last updated · {updatedAt}</div>}
          </div>
        </div>
      </div>
    </div>
  );
}
window.WebEditorialPage = WebEditorialPage;

// ─── Search results ──────────────────────────────────
function WebSearchResults({ data, query, onPickPoi, onPickActivity, onPickProduct, onBack }) {
  const q = (query || '').toLowerCase();
  const pois = useMemoWPdp(() => data.pois.filter(p => !q || p.name.toLowerCase().includes(q) || p.region.toLowerCase().includes(q)), [q]);
  const acts = useMemoWPdp(() => data.activities.filter(a => !q || a.name.toLowerCase().includes(q) || a.location.toLowerCase().includes(q)), [q]);
  const prods = useMemoWPdp(() => data.shopProducts.filter(p => !q || p.name.toLowerCase().includes(q)), [q]);
  const total = pois.length + acts.length + prods.length;
  return (
    <div className="w2-srh w2-route">
      <div className="w2-srh__inner">
        <button onClick={onBack} style={{background:0,border:0,font:'600 11px var(--font-body)',letterSpacing:'.14em',color:'var(--fg-3)',cursor:'pointer',padding:0,marginBottom:14}}>← BACK</button>
        <div className="w2-srh__head">
          <h1 className="w2-srh__title">Results for <em>"{query}"</em></h1>
          <div className="w2-srh__count">{total} matches</div>
        </div>

        {pois.length > 0 && (
          <div className="w2-srh__sect">
            <h2 className="w2-srh__sect-t">Places ({pois.length})</h2>
            <div className="w2-srh__row">
              {pois.slice(0,6).map(p => (
                <button key={p.id} className="w2-qprod" onClick={() => onPickPoi(p.id)}>
                  <div className="w2-qprod__img" style={{ backgroundImage:`url(${p.img})`,aspectRatio:'1.6/1' }}/>
                  <div className="w2-qprod__body">
                    <div className="w2-qprod__cat">{p.kind} · {p.region}</div>
                    <div className="w2-qprod__name">{p.name}</div>
                    <div className="w2-qprod__price">{p.alt.toLocaleString()} m{p.price ? ` · ₹${p.price.toLocaleString()}/n` : ''}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}

        {acts.length > 0 && (
          <div className="w2-srh__sect">
            <h2 className="w2-srh__sect-t">Activities ({acts.length})</h2>
            <div className="w2-srh__row">
              {acts.slice(0,6).map(a => (
                <button key={a.id} className="w2-qprod" onClick={() => onPickActivity(a.id)}>
                  <div className="w2-qprod__img" style={{ backgroundImage:`url(${a.img})`,aspectRatio:'1.6/1' }}/>
                  <div className="w2-qprod__body">
                    <div className="w2-qprod__cat">{a.region} · GRADE {a.grade}</div>
                    <div className="w2-qprod__name">{a.name}</div>
                    <div className="w2-qprod__price">from ₹{a.priceFrom.toLocaleString()}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}

        {prods.length > 0 && (
          <div className="w2-srh__sect">
            <h2 className="w2-srh__sect-t">Shop ({prods.length})</h2>
            <div className="w2-srh__row">
              {prods.slice(0,6).map(p => (
                <button key={p.id} className="w2-qprod" onClick={() => onPickProduct(p.id)}>
                  <div className="w2-qprod__img" style={{ backgroundImage:`url(${p.img})` }}/>
                  <div className="w2-qprod__body">
                    <div className="w2-qprod__cat">{p.cat}</div>
                    <div className="w2-qprod__name">{p.name}</div>
                    <div className="w2-qprod__price">₹{p.price.toLocaleString()}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}

        {total === 0 && (
          <window.WebEmptyState icon="?" title="No results match that search."
            body={`Try a region (Spiti, Kinnaur), a kind (paragliding, momos), or a vendor.`}
            ctaLabel="Browse all places" onCta={onBack}/>
        )}
      </div>
    </div>
  );
}
window.WebSearchResults = WebSearchResults;

// ─── Pro upgrade modal ──────────────────────────────────
function WebUpgradeModal({ onClose, onSubscribe }) {
  const [cycle, setCycle] = useStateWPdp('monthly');
  const price = cycle === 'monthly' ? 299 : 2990;
  const billed = cycle === 'monthly' ? '/month' : '/year (save 17%)';
  return (
    <div className="w2-modal-backdrop" onClick={onClose}>
      <div className="w2-modal w2-upgrade" onClick={e => e.stopPropagation()}>
        <button className="w2-modal__close" onClick={onClose}>×</button>
        <div className="w2-upgrade__lbl">HimLocal Pro</div>
        <h2 className="w2-upgrade__title">More trips. More <em>map.</em></h2>
        <p className="w2-upgrade__sub">Free is generous — Pro is for the planners. Upgrade any time, cancel any time.</p>

        <div className="w2-upgrade__cycle">
          <button className={`w2-upgrade__cycle-b ${cycle === 'monthly' ? 'is-on' : ''}`} onClick={() => setCycle('monthly')}>Monthly</button>
          <button className={`w2-upgrade__cycle-b ${cycle === 'annual' ? 'is-on' : ''}`} onClick={() => setCycle('annual')}>Annual <span style={{font:'500 9.5px var(--font-mono)',marginLeft:6,padding:'2px 6px',borderRadius:999,background:'var(--leaf-100)',color:'var(--leaf-800)',letterSpacing:'.04em'}}>Save 17%</span></button>
        </div>

        <div className="w2-upgrade__plans">
          <div className="w2-upgrade__plan">
            <div className="w2-upgrade__plan-l">Free · Trail-head</div>
            <div className="w2-upgrade__plan-p">₹0</div>
            <ul className="w2-upgrade__plan-fl">
              <li>1 itinerary at a time</li>
              <li>Map exploration, no nearby mode</li>
              <li>Standard booking inventory</li>
              <li>Razorpay checkout (5% platform)</li>
            </ul>
          </div>
          <div className="w2-upgrade__plan w2-upgrade__plan--pro">
            <div className="w2-upgrade__plan-l" style={{color:'var(--leaf-700)'}}>Pro · Multi-trip</div>
            <div className="w2-upgrade__plan-p">₹{price.toLocaleString()}<small>{billed}</small></div>
            <ul className="w2-upgrade__plan-fl">
              <li><strong>10 itineraries</strong> — plan a season ahead</li>
              <li><strong>Nearby mode</strong> + offline map tiles</li>
              <li><strong>Curated departures</strong> 7 days early</li>
              <li><strong>0% platform fee</strong> on bookings</li>
              <li>Priority host support · 4-hour reply SLA</li>
              <li>Receipt + GST invoice export</li>
            </ul>
          </div>
        </div>

        <button className="w2-upgrade__cta" onClick={() => onSubscribe(cycle, price)}>Start Pro · ₹{price.toLocaleString()} {billed}</button>
        <div className="w2-upgrade__legal">Auto-renews until cancelled. UPI, card, net-banking accepted. 7-day refund.</div>
      </div>
    </div>
  );
}
window.WebUpgradeModal = WebUpgradeModal;

// ─── Modify booking dates modal ─────────────────────────
function WebModifyBookingModal({ booking, onClose, onSubmit }) {
  const today = new Date();
  const fmt = (d) => d.toISOString().slice(0, 10);
  const [start, setStart] = useStateWPdp(booking?.start || fmt(today));
  const [end,   setEnd]   = useStateWPdp(booking?.end   || fmt(new Date(today.getTime() + 86400000)));
  const [note,  setNote]  = useStateWPdp('');
  const nights = useMemoWPdp(() => {
    try {
      const s = new Date(start + 'T00:00:00');
      const e = new Date(end + 'T00:00:00');
      return Math.max(1, Math.round((e - s) / 86400000));
    } catch { return 1; }
  }, [start, end]);

  return (
    <div className="w2-modal-backdrop" onClick={onClose}>
      <div className="w2-modal w2-modify" onClick={e => e.stopPropagation()}>
        <button className="w2-modal__close" onClick={onClose}>×</button>
        <div className="w2-modify__lbl">Modify booking</div>
        <h2 className="w2-modify__title">{booking?.title || 'Your stay'}</h2>
        <p className="w2-modify__sub">Pick new dates. We'll send the request to the host — they reply within 4 hours during the season.</p>

        <div className="w2-modify__grid">
          <label className="w2-modify__field">
            <span>Check-in</span>
            <input type="date" value={start} onChange={e => setStart(e.target.value)}/>
          </label>
          <label className="w2-modify__field">
            <span>Check-out</span>
            <input type="date" value={end} onChange={e => setEnd(e.target.value)} min={start}/>
          </label>
        </div>
        <div className="w2-modify__summary">
          <strong>{nights}</strong> {nights === 1 ? 'night' : 'nights'} · {start} → {end}
        </div>

        <label className="w2-modify__field" style={{gridColumn:'1 / -1'}}>
          <span>Note for the host (optional)</span>
          <textarea value={note} onChange={e => setNote(e.target.value)} maxLength={240}
            placeholder="e.g. arriving by taxi after midnight — please leave key with caretaker."
            style={{minHeight:60,padding:'10px 12px',border:'1px solid var(--border-2)',borderRadius:8,font:'400 13px var(--font-body)',resize:'vertical'}}/>
        </label>

        <button className="w2-modify__cta" onClick={() => onSubmit({ start, end, note:note.trim() || undefined, nights })}>
          Send modification request
        </button>
        <div className="w2-modify__legal">If the new dates are unavailable, the host will suggest alternatives. No charge until you accept.</div>
      </div>
    </div>
  );
}
window.WebModifyBookingModal = WebModifyBookingModal;
