// HimLocal — Mobile v2.7 PDP + Editorial / FAQ + Search results + Receipt sheet
//                  + Auth sheet + Notifications sheet + Edit personal / address sheets

const { useState: useStateMEx, useMemo: useMemoMEx } = React;

// ─── Variant + gallery seed for the mobile PDP ──────────
const M_PDP_GALLERY = {
  wool:  ['https://images.unsplash.com/photo-1606760227091-3dd870d97f1d?w=900','https://images.unsplash.com/photo-1620799140188-3b2a02fd9a77?w=900','https://images.unsplash.com/photo-1601244005535-a48d21d951ac?w=900','https://images.unsplash.com/photo-1603487742131-4160ec999306?w=900'],
  ghee:  ['https://images.unsplash.com/photo-1628088062854-d1870b4553da?w=900','https://images.unsplash.com/photo-1559561853-08451507cbe7?w=900','https://images.unsplash.com/photo-1542990253-0d0f5be5f0ed?w=900','https://images.unsplash.com/photo-1559925393-8be0ec4767c8?w=900'],
  fruit: ['https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?w=900','https://images.unsplash.com/photo-1567721913486-6585f069b332?w=900','https://images.unsplash.com/photo-1604908554049-5e2f7fbcd6cb?w=900','https://images.unsplash.com/photo-1577003833619-76bbd7f82948?w=900'],
  honey: ['https://images.unsplash.com/photo-1587049352846-4a222e784d38?w=900','https://images.unsplash.com/photo-1597481499750-3e6b22637e12?w=900','https://images.unsplash.com/photo-1576092768241-dec231879fc3?w=900','https://images.unsplash.com/photo-1495474472287-4d71bcdd2085?w=900'],
  craft: ['https://images.unsplash.com/photo-1577705998148-6da4f3963bc8?w=900','https://images.unsplash.com/photo-1582719471384-894fbb16e074?w=900','https://images.unsplash.com/photo-1606498679340-0aec3185edbd?w=900','https://images.unsplash.com/photo-1604908554049-5e2f7fbcd6cb?w=900'],
  spice: ['https://images.unsplash.com/photo-1582284540020-8acbe03f4924?w=900','https://images.unsplash.com/photo-1532336414038-cf19250c5757?w=900','https://images.unsplash.com/photo-1564844536311-de546a28c87d?w=900','https://images.unsplash.com/photo-1604908554049-5e2f7fbcd6cb?w=900'],
};
const M_PDP_VARIANT = {
  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'},{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}] },
  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}] },
};
const M_PDP_REVIEWS = [
  { id:'r1', author:'Priya M.',   initials:'PM', when:'Sep 2025', stars:5, verified:true,  text:'Proper Himalayan winter quality. The smell of woodsmoke from the hands that made it is gone after the first wash.', tags:['True to photo'] },
  { id:'r2', author:'Devansh K.', initials:'DK', when:'Aug 2025', stars:5, verified:true,  text:'Worth every rupee. Maker added a hand-written note inside the box, which made my day.', tags:['Gift'] },
  { 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.', tags:[] },
];

// ─── Mobile PDP ──────────────────────────────────────────
function MobileProductDetail({ product, vendor, related, onBack, onAddToCart, wishlisted, onWishlist }) {
  if (!product) return null;
  const cat = product.cat || 'wool';
  const variantOpts = M_PDP_VARIANT[cat] || {};
  const hasColor = !!(variantOpts.color && variantOpts.color.length);
  const hasSize  = !!(variantOpts.size  && variantOpts.size.length);
  const gallery = M_PDP_GALLERY[cat] || [product.img, product.img, product.img, product.img];

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

  const sizeMod = hasSize ? (variantOpts.size[sizeIdx]?.mod || 0) : 0;
  const unit = product.price + sizeMod;
  const strike = Math.round(unit * 1.14);

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

  return (
    <div className="app-pdp">
      <div className="app-pdp__top">
        <button className="app-pdp__topbtn" onClick={onBack}>←</button>
        <div style={{font:'500 11px var(--font-mono)',color:'var(--fg-3)',letterSpacing:'.04em'}}>Shop · {cat}</div>
        <button className="app-pdp__topbtn" onClick={() => onWishlist?.(product.id)} aria-label="Wishlist">{wishlisted ? '♥' : '♡'}</button>
      </div>

      <div className="app-pdp__scroll">
        <div className="app-pdp__hero" style={{ background:'var(--bone-100)' }}>
          <img className="app-pdp__hero-img" src={gallery[galleryIdx]} alt={product.name}/>
          <div className="app-pdp__hero-dots">
            {gallery.map((_, i) => (
              <span key={i} className={`app-pdp__hero-dot ${i === galleryIdx ? 'is-on' : ''}`}/>
            ))}
          </div>
        </div>
        <div className="app-pdp__hero-strip">
          {gallery.map((src, i) => (
            <button key={i} className={`app-pdp__hero-thumb ${i === galleryIdx ? 'is-on' : ''}`}
              style={{ backgroundImage:`url(${src})` }} onClick={() => setGalleryIdx(i)} aria-label={`Frame ${i + 1}`}/>
          ))}
        </div>

        <div className="app-pdp__body">
          {vendor && <div className="app-pdp__vendor-pill">{vendor.name} · {vendor.loc}</div>}
          <h1 className="app-pdp__name">{product.name}</h1>
          <p className="app-pdp__sub">{product.weight ? `${product.weight} · ` : ''}Hand-made. Signed by the maker.</p>
          <div className="app-pdp__rating">
            <span className="app-pdp__rating-stars">★★★★★</span>
            <span className="app-pdp__rating-n">4.8 · 312 reviews</span>
          </div>

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

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

          {hasSize && (
            <div className="app-pdp__opt-group">
              <div className="app-pdp__opt-head">
                Size <strong>· {variantOpts.size[sizeIdx].name}</strong>
                <button className="app-pdp__opt-help">Size guide ↗</button>
              </div>
              <div className="app-pdp__opt-row">
                {variantOpts.size.map((s, i) => (
                  <button key={i} className={`app-pdp__opt ${i === sizeIdx ? 'is-on' : ''}`} onClick={() => setSizeIdx(i)}>
                    {s.name}{s.badge && <span style={{font:'500 10px var(--font-mono)',color:'var(--fg-3)'}}>· {s.badge}</span>}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div className="app-pdp__special">
            <div className="app-pdp__special-l">
              Note for the maker
              <span style={{font:'500 9.5px var(--font-body)',padding:'2px 6px',borderRadius:999,background:'rgba(31,59,87,.08)',color:'var(--fg-3)',letterSpacing:'.04em'}}>Optional</span>
            </div>
            <textarea value={note} maxLength={240} onChange={e => setNote(e.target.value)}
              placeholder="e.g. gift wrap with kraft paper, no plastic."/>
            <div className="app-pdp__special-help">{note.length}/240 · Sent to the vendor as-is.</div>
          </div>

          <div className="app-pdp__benefits">
            {[['⌖','Hand-made','Signed by maker'],['↩','7-day returns','Damage refunded'],['✓','Free ship','Over ₹2,000'],['✦','Vendor-direct','No middleman']].map(([i,t,d], idx) => (
              <div key={idx} className="app-pdp__benefit">
                <div className="app-pdp__benefit-icon">{i}</div>
                <div>
                  <div className="app-pdp__benefit-t">{t}</div>
                  <div className="app-pdp__benefit-d">{d}</div>
                </div>
              </div>
            ))}
          </div>

          {/* Tabs */}
          <div style={{display:'flex',gap:4,padding:4,background:'var(--bone-100)',borderRadius:10,marginTop:18,marginBottom:14,width:'fit-content'}}>
            {[['about','About'],['spec','Specs'],['ship','Ship/return']].map(([id, label]) => (
              <button key={id} onClick={() => setTab(id)}
                style={{padding:'6px 12px',borderRadius:7,background:tab===id?'white':'transparent',border:0,cursor:'pointer',font:`600 11.5px var(--font-body)`,color:tab===id?'var(--slate-700)':'var(--fg-2)',boxShadow:tab===id?'0 1px 2px rgba(14,26,36,.08)':'none'}}>
                {label}
              </button>
            ))}
          </div>
          {tab === 'about' && (
            <p style={{font:'400 13px var(--font-body)',color:'var(--fg-1)',lineHeight:1.6,margin:'0 0 12px'}}>Made by {vendor?.name || 'a local artisan'} in {vendor?.loc || 'the Himalayas'}. Each piece is signed and ships with a small card naming the workshop. Allow 1—2 cm variation in finish.</p>
          )}
          {tab === 'spec' && (
            <dl className="app-pdp__spec">
              <dt>Material</dt><dd>{cat === 'wool' ? '100% Himalayan wool' : cat === 'craft' ? 'Sand-cast brass' : 'Single-origin'}</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' : 'Cool, dry place'}</dd>
              <dt>SKU</dt><dd className="mono">HL-{product.id?.toUpperCase()}</dd>
            </dl>
          )}
          {tab === 'ship' && (
            <div>
              <div className="app-pdp__policy-card">
                <div className="app-pdp__policy-i">✓</div>
                <div>
                  <div className="app-pdp__policy-t">5—7 days · India</div>
                  <div className="app-pdp__policy-d">₹120 flat. Free over ₹2,000. Tracked.</div>
                </div>
              </div>
              <div className="app-pdp__policy-card">
                <div className="app-pdp__policy-i">⤴</div>
                <div>
                  <div className="app-pdp__policy-t">12—21 days · International</div>
                  <div className="app-pdp__policy-d">From ₹1,400. India Post EMS or DHL.</div>
                </div>
              </div>
              <div className="app-pdp__policy-card">
                <div className="app-pdp__policy-i">↩</div>
                <div>
                  <div className="app-pdp__policy-t">7-day returns</div>
                  <div className="app-pdp__policy-d">Any reason. Damage in transit fully refunded.</div>
                </div>
              </div>
            </div>
          )}

          {/* Reviews */}
          <h3 className="app-pdp__sec-h">Reviews · <em>4.8</em></h3>
          <div className="app-pdp__rev-summary">
            <div>
              <div className="app-pdp__rev-score">4.8</div>
              <div className="app-pdp__rev-stars">★★★★★</div>
              <div className="app-pdp__rev-count">312 reviews</div>
            </div>
            <div className="app-pdp__rev-bars">
              {[[5,82],[4,12],[3,4],[2,1],[1,1]].map(([star, pct]) => (
                <div key={star} className="app-pdp__rev-bar">
                  <span>{star}★</span>
                  <div className="app-pdp__rev-bar-track"><div className="app-pdp__rev-bar-fill" style={{ width:`${pct}%` }}/></div>
                  <span>{pct}%</span>
                </div>
              ))}
            </div>
          </div>
          {M_PDP_REVIEWS.map(r => (
            <div key={r.id} className="app-pdp__rev-card">
              <div className="app-pdp__rev-row">
                <div className="app-pdp__rev-avatar">{r.initials}</div>
                <div style={{flex:1,minWidth:0}}>
                  <div className="app-pdp__rev-meta">{r.author}</div>
                  <div className="app-pdp__rev-when">{r.when}{r.verified && ' · verified'}</div>
                </div>
                <div className="app-pdp__rev-stars-sm">{'★'.repeat(r.stars)}{'☆'.repeat(5 - r.stars)}</div>
              </div>
              <div className="app-pdp__rev-text">{r.text}</div>
              {r.verified && <div className="app-pdp__rev-vbadge">Verified buyer</div>}
            </div>
          ))}
          <button style={{marginTop:10,padding:'10px 16px',background:'var(--bone-100)',border:'1px solid var(--border-1)',borderRadius:999,font:'600 11.5px var(--font-body)',color:'var(--slate-700)',cursor:'pointer',width:'100%'}}>
            Read all 312 reviews →
          </button>

          {/* Maker */}
          {vendor && (
            <>
              <h3 className="app-pdp__sec-h">Meet the <em>maker</em></h3>
              <div className="app-pdp__vendor-card">
                <div className="app-pdp__vendor-img" style={{ backgroundImage:`url(${vendor.img})` }}/>
                <div>
                  <div className="app-pdp__vendor-t">{vendor.name}</div>
                  <div className="app-pdp__vendor-l">{vendor.loc}</div>
                </div>
              </div>
            </>
          )}

          {/* Related */}
          {related && related.length > 0 && (
            <>
              <h3 className="app-pdp__sec-h">From the same <em>workshop</em></h3>
              <div className="app-pdp__related">
                {related.map(p => (
                  <button key={p.id} className="app-pdp__related-card" onClick={onBack}>
                    <div className="app-pdp__related-img" style={{ backgroundImage:`url(${p.img})` }}/>
                    <div className="app-pdp__related-t">{p.name}</div>
                    <div className="app-pdp__related-p">₹{p.price.toLocaleString()}</div>
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>

      <div className="app-pdp__sticky">
        <div className="app-pdp__sticky-qty">
          <button onClick={() => setQty(q => Math.max(1, q - 1))} aria-label="Decrease">−</button>
          <span>{qty}</span>
          <button onClick={() => setQty(q => q + 1)} aria-label="Increase">+</button>
        </div>
        <div className="app-pdp__sticky-p">₹{(unit * qty).toLocaleString()}</div>
        <button className="app-pdp__sticky-btn"
          onClick={() => onAddToCart(product.id, qty, variantSummary || undefined, note.trim() || undefined)}>
          Add to basket →
        </button>
      </div>
    </div>
  );
}
window.MobileProductDetail = MobileProductDetail;

// ─── Mobile editorial page (FAQ / About / Terms / …) ──
function MobileEditorialPage({ title, lede, sections, updatedAt, type = 'rich', onBack }) {
  const [openIdx, setOpenIdx] = useStateMEx(0);
  return (
    <div className="app-edit">
      <button className="app-edit__back" onClick={onBack}>←</button>
      <div className="app-edit__crumb">HimLocal · {type === 'faq' ? 'FAQ' : 'Field guide'}</div>
      <h1 className="app-edit__title">{title}</h1>
      {lede && <div className="app-edit__lede">{lede}</div>}

      {type === 'faq' ? (
        <div className="w2-faq" style={{display:'flex',flexDirection:'column',gap:4}}>
          {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)} style={{padding:'14px 16px',fontSize:13.5}}>
                <span>{s.title}</span>
                <span className="w2-faq__chev">+</span>
              </button>
              <div className="w2-faq__a" style={{padding:'0 16px 14px',fontSize:13}}>{s.body}</div>
            </div>
          ))}
        </div>
      ) : (
        <div className="w2-rich">
          {sections.map((s, i) => (
            <section key={i}>
              <h2 style={{fontSize:22}}>{s.title}</h2>
              {typeof s.body === 'string' ? <p>{s.body}</p> : s.body}
            </section>
          ))}
        </div>
      )}
      {updatedAt && <div style={{font:'500 11px var(--font-mono)',color:'var(--fg-3)',letterSpacing:'.04em',padding:'14px 0',borderTop:'1px solid var(--border-1)',marginTop:24}}>Last updated · {updatedAt}</div>}
    </div>
  );
}
window.MobileEditorialPage = MobileEditorialPage;

// ─── Mobile search results ───────────────────────────
function MobileSearchResults({ data, query, onBack, onPickPoi, onPickActivity, onPickProduct }) {
  const q = (query || '').toLowerCase();
  const pois  = useMemoMEx(() => data.pois.filter(p => !q || p.name.toLowerCase().includes(q) || p.region.toLowerCase().includes(q)).slice(0, 5), [q]);
  const acts  = useMemoMEx(() => data.activities.filter(a => !q || a.name.toLowerCase().includes(q)).slice(0, 4), [q]);
  const prods = useMemoMEx(() => data.shopProducts.filter(p => !q || p.name.toLowerCase().includes(q)).slice(0, 4), [q]);
  const total = pois.length + acts.length + prods.length;
  return (
    <div className="app-edit" style={{paddingBottom:20}}>
      <button className="app-edit__back" onClick={onBack}>←</button>
      <div className="app-edit__crumb">Search results</div>
      <h1 className="app-edit__title" style={{fontSize:24}}>Results for <em>"{query}"</em></h1>
      <div style={{font:'500 12px var(--font-mono)',color:'var(--fg-3)',letterSpacing:'.04em',marginBottom:18}}>{total} matches</div>

      {pois.length > 0 && (
        <>
          <h2 style={{fontFamily:'var(--font-display)',fontSize:18,fontWeight:500,fontStyle:'italic',color:'var(--slate-700)',margin:'18px 0 8px'}}>Places</h2>
          {pois.map(p => (
            <button key={p.id} onClick={() => onPickPoi(p.id)} style={{display:'flex',gap:10,padding:'10px 0',borderBottom:'1px solid var(--border-1)',background:0,border:0,textAlign:'left',width:'100%',cursor:'pointer'}}>
              <div style={{width:72,height:72,backgroundImage:`url(${p.img})`,backgroundSize:'cover',backgroundPosition:'center',borderRadius:8,flexShrink:0}}/>
              <div style={{flex:1,minWidth:0}}>
                <div style={{font:'600 9.5px var(--font-body)',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--fg-3)'}}>{p.kind} · {p.region}</div>
                <div style={{fontFamily:'var(--font-display)',fontSize:15,fontWeight:500,color:'var(--slate-700)',marginTop:2}}>{p.name}</div>
                <div style={{font:'400 11px var(--font-mono)',color:'var(--fg-3)',marginTop:3}}>{p.alt.toLocaleString()} m{p.price ? ` · ₹${p.price.toLocaleString()}/n` : ''}</div>
              </div>
            </button>
          ))}
        </>
      )}

      {acts.length > 0 && (
        <>
          <h2 style={{fontFamily:'var(--font-display)',fontSize:18,fontWeight:500,fontStyle:'italic',color:'var(--slate-700)',margin:'18px 0 8px'}}>Activities</h2>
          {acts.map(a => (
            <button key={a.id} onClick={() => onPickActivity(a.id)} style={{display:'flex',gap:10,padding:'10px 0',borderBottom:'1px solid var(--border-1)',background:0,border:0,textAlign:'left',width:'100%',cursor:'pointer'}}>
              <div style={{width:72,height:72,backgroundImage:`url(${a.img})`,backgroundSize:'cover',backgroundPosition:'center',borderRadius:8,flexShrink:0}}/>
              <div style={{flex:1,minWidth:0}}>
                <div style={{font:'600 9.5px var(--font-body)',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--fg-3)'}}>{a.region} · GRADE {a.grade}</div>
                <div style={{fontFamily:'var(--font-display)',fontSize:15,fontWeight:500,color:'var(--slate-700)',marginTop:2}}>{a.name}</div>
                <div style={{font:'400 11px var(--font-mono)',color:'var(--fg-3)',marginTop:3}}>from ₹{a.priceFrom.toLocaleString()}</div>
              </div>
            </button>
          ))}
        </>
      )}

      {prods.length > 0 && (
        <>
          <h2 style={{fontFamily:'var(--font-display)',fontSize:18,fontWeight:500,fontStyle:'italic',color:'var(--slate-700)',margin:'18px 0 8px'}}>Shop</h2>
          {prods.map(p => (
            <button key={p.id} onClick={() => onPickProduct(p.id)} style={{display:'flex',gap:10,padding:'10px 0',borderBottom:'1px solid var(--border-1)',background:0,border:0,textAlign:'left',width:'100%',cursor:'pointer'}}>
              <div style={{width:72,height:72,backgroundImage:`url(${p.img})`,backgroundSize:'cover',backgroundPosition:'center',borderRadius:8,flexShrink:0}}/>
              <div style={{flex:1,minWidth:0}}>
                <div style={{font:'600 9.5px var(--font-body)',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--fg-3)'}}>{p.cat}</div>
                <div style={{fontFamily:'var(--font-display)',fontSize:15,fontWeight:500,color:'var(--slate-700)',marginTop:2}}>{p.name}</div>
                <div style={{font:'500 12px var(--font-mono)',color:'var(--slate-700)',marginTop:3}}>₹{p.price.toLocaleString()}</div>
              </div>
            </button>
          ))}
        </>
      )}

      {total === 0 && (
        <div style={{padding:'40px 20px',textAlign:'center',color:'var(--fg-3)'}}>
          <div style={{fontFamily:'var(--font-display)',fontStyle:'italic',fontSize:18,color:'var(--slate-700)',marginBottom:6}}>Nothing matches "{query}".</div>
          <div style={{font:'400 13px var(--font-body)'}}>Try a region (Spiti, Kinnaur) or a kind (paragliding, momos).</div>
        </div>
      )}
    </div>
  );
}
window.MobileSearchResults = MobileSearchResults;

// ─── Mobile auth sheet ──────────────────────────────
function MobileAuthSheet({ onClose, onSignedIn, defaultMode = 'signin' }) {
  const [mode, setMode] = useStateMEx(defaultMode);
  const [email, setEmail] = useStateMEx('aanya@example.com');
  const [name, setName] = useStateMEx('');
  const isSignup = mode === 'signup';
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:94}} onClick={onClose}>
      <div className="app-auth-sheet" onClick={e => e.stopPropagation()}>
        <div className="app-auth-sheet__hero">
          <div className="app-auth-sheet__handle"/>
          <div className="app-auth-sheet__hero-copy">
            <div style={{font:'600 10px var(--font-body)',letterSpacing:'.18em',textTransform:'uppercase',opacity:.9}}>{isSignup ? 'Create account' : 'Welcome back'}</div>
            <div className="app-auth-sheet__hero-t">{isSignup ? <>Start your <em>field guide.</em></> : <>Sign in to <em>HimLocal.</em></>}</div>
          </div>
        </div>
        <div style={{display:'flex',padding:'0 16px',borderBottom:'1px solid var(--border-1)'}}>
          <button onClick={() => setMode('signin')} style={{flex:1,padding:'12px 0',background:0,border:0,font:`${!isSignup?700:500} 13px var(--font-body)`,color:!isSignup?'var(--slate-700)':'var(--fg-3)',cursor:'pointer',borderBottom:!isSignup?'2px solid var(--slate-700)':'2px solid transparent'}}>Sign in</button>
          <button onClick={() => setMode('signup')} style={{flex:1,padding:'12px 0',background:0,border:0,font:`${isSignup?700:500} 13px var(--font-body)`,color:isSignup?'var(--slate-700)':'var(--fg-3)',cursor:'pointer',borderBottom:isSignup?'2px solid var(--slate-700)':'2px solid transparent'}}>Sign up</button>
        </div>
        <div className="app-auth-sheet__body">
          {isSignup && (
            <div style={{marginBottom:10}}>
              <label style={{font:'600 10px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>Your name</label>
              <input value={name} onChange={e => setName(e.target.value)} placeholder="Aanya Rana" style={{display:'block',marginTop:5,width:'100%',height:42,padding:'0 12px',background:'white',border:'1px solid var(--border-2)',borderRadius:8,font:'500 14px var(--font-body)',color:'var(--slate-700)',outline:0}}/>
            </div>
          )}
          <div style={{marginBottom:10}}>
            <label style={{font:'600 10px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>Email</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} style={{display:'block',marginTop:5,width:'100%',height:42,padding:'0 12px',background:'white',border:'1px solid var(--border-2)',borderRadius:8,font:'500 14px var(--font-body)',color:'var(--slate-700)',outline:0}}/>
          </div>
          <div style={{marginBottom:14}}>
            <label style={{font:'600 10px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>Password</label>
            <input type="password" placeholder="••••••••" style={{display:'block',marginTop:5,width:'100%',height:42,padding:'0 12px',background:'white',border:'1px solid var(--border-2)',borderRadius:8,font:'500 14px var(--font-body)',color:'var(--slate-700)',outline:0}}/>
          </div>
          <button onClick={() => onSignedIn?.({ email, name:name || 'Aanya Rana' })} style={{width:'100%',height:46,borderRadius:10,background:'var(--grad-cta-itinerary)',border:0,color:'white',font:'700 13px var(--font-body)',cursor:'pointer',boxShadow:'0 6px 16px rgba(48,92,222,.28)'}}>{isSignup ? 'Create account →' : 'Sign in →'}</button>
          <div style={{display:'flex',gap:8,margin:'14px 0 10px'}}>
            <button style={{flex:1,height:40,borderRadius:8,background:'white',border:'1px solid var(--border-2)',cursor:'pointer',font:'600 11.5px var(--font-body)',color:'var(--slate-700)'}}>G  Google</button>
            <button style={{flex:1,height:40,borderRadius:8,background:'white',border:'1px solid var(--border-2)',cursor:'pointer',font:'600 11.5px var(--font-body)',color:'var(--slate-700)'}}></button>
            <button style={{flex:1,height:40,borderRadius:8,background:'white',border:'1px solid var(--border-2)',cursor:'pointer',font:'600 11.5px var(--font-body)',color:'var(--slate-700)'}}>⊞ Phone</button>
          </div>
          <div style={{textAlign:'center',font:'400 11px var(--font-body)',color:'var(--fg-3)',marginTop:10,lineHeight:1.5}}>By continuing, you agree to our <a style={{color:'var(--slate-600)'}}>Terms</a> and <a style={{color:'var(--slate-600)'}}>Privacy Policy</a>.</div>
        </div>
      </div>
    </div>
  );
}
window.MobileAuthSheet = MobileAuthSheet;

// ─── Mobile notifications sheet ─────────────────────
function MobileNotificationsSheet({ items, onClose, onMarkAllRead, onPick }) {
  const [filter, setFilter] = useStateMEx('all');
  const filtered = useMemoMEx(() => filter === 'all' ? items : items.filter(n => n.kind === filter), [items, filter]);
  const unread = items.filter(n => !n.read).length;
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:91}} onClick={onClose}>
      <div className="app-notif-sheet" onClick={e => e.stopPropagation()}>
        <div className="app-notif-sheet__head">
          <button className="app-notif-sheet__close" onClick={onClose}>×</button>
          <div className="app-notif-sheet__t">Notifications {unread > 0 && <span style={{font:'600 10px var(--font-mono)',color:'var(--leaf-700)',background:'var(--leaf-100)',padding:'2px 7px',borderRadius:999,marginLeft:6,letterSpacing:'.05em',verticalAlign:'middle'}}>{unread}</span>}</div>
          <button onClick={onMarkAllRead} style={{background:0,border:0,font:'600 10px var(--font-body)',letterSpacing:'.14em',color:'var(--leaf-700)',cursor:'pointer',padding:4}}>READ ALL</button>
        </div>
        <div style={{display:'flex',gap:6,padding:'10px 16px',borderBottom:'1px solid var(--border-1)',overflowX:'auto'}}>
          {[['all','All'],['booking','Bookings'],['order','Orders'],['host','Hosts'],['alert','Alerts']].map(([id, lbl]) => (
            <button key={id} onClick={() => setFilter(id)} style={{flexShrink:0,padding:'5px 11px',borderRadius:999,background:filter===id?'var(--slate-700)':'transparent',color:filter===id?'white':'var(--slate-700)',border:`1px solid ${filter===id?'var(--slate-700)':'var(--border-1)'}`,font:'600 10.5px var(--font-body)',cursor:'pointer'}}>{lbl}</button>
          ))}
        </div>
        <div className="app-notif-sheet__body">
          {filtered.length === 0 ? (
            <div style={{padding:'48px 20px',textAlign:'center',color:'var(--fg-3)'}}>
              <div style={{fontFamily:'var(--font-display)',fontStyle:'italic',fontSize:18,color:'var(--slate-700)',marginBottom:6}}>All caught up.</div>
              <div style={{font:'400 12.5px var(--font-body)'}}>No notifications in this category.</div>
            </div>
          ) : filtered.map(n => (
            <div key={n.id} onClick={() => onPick?.(n)} style={{display:'grid',gridTemplateColumns:'34px 1fr auto',gap:10,padding:'12px 16px',borderBottom:'1px solid var(--border-1)',cursor:'pointer',position:'relative'}}>
              {!n.read && <div style={{position:'absolute',left:6,top:'50%',transform:'translateY(-50%)',width:5,height:5,borderRadius:'50%',background:'var(--leaf-700)'}}/>}
              <div style={{width:34,height:34,borderRadius:8,display:'flex',alignItems:'center',justifyContent:'center',background:n.kind==='booking'?'var(--leaf-100)':n.kind==='order'?'var(--sky-100)':n.kind==='host'?'var(--lavender-100)':'rgba(229,169,59,.18)',color:n.kind==='booking'?'var(--leaf-700)':n.kind==='order'?'var(--sky-700)':n.kind==='host'?'var(--lavender-700)':'#8B5A2B',fontSize:13}}>{n.kind === 'booking' ? '◈' : n.kind === 'order' ? '⊛' : n.kind === 'host' ? '✉' : '⚠'}</div>
              <div style={{minWidth:0}}>
                <div style={{font:'600 12.5px var(--font-body)',color:'var(--slate-700)'}}>{n.title}</div>
                <div style={{font:'400 11.5px var(--font-body)',color:'var(--fg-2)',marginTop:2,lineHeight:1.45}}>{n.sub}</div>
              </div>
              <div style={{font:'500 10px var(--font-mono)',color:'var(--fg-3)',letterSpacing:'.04em',whiteSpace:'nowrap',alignSelf:'flex-start',paddingTop:2}}>{n.when}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.MobileNotificationsSheet = MobileNotificationsSheet;

// ─── Mobile receipt sheet (booking / order / activity) ─
function MobileReceiptSheet({ kind, item, onClose, onCancel, onModify }) {
  if (!item) return null;
  const isBooking = kind === 'booking';
  const isOrder = kind === 'order' || kind === 'cafe-order';
  const isActivity = kind === 'activity';
  const trackSteps = (() => {
    if (kind === 'order') return [
      { name:'Placed', when:'02 Apr · 11:14', state:'done' },
      { name:'Packed', when:'03 Apr · 09:30', state:'done' },
      { name:'Shipped', when:'03 Apr · 17:42', state:'done' },
      { name:'Out for delivery', when:'14 May exp.', state:'current' },
      { name:'Delivered', when:'14—15 May', state:'pending' },
    ];
    if (kind === 'cafe-order') return [
      { name:'Placed',    when:'08:42', state:'done' },
      { name:'Cooking',   when:'08:48', state:'done' },
      { name:'Out for delivery', when:'09:05', state:'current' },
      { name:'Delivered', when:'~09:25', state:'pending' },
    ];
    return null;
  })();
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:96}} onClick={onClose}>
      <div style={{position:'absolute',left:0,right:0,bottom:0,background:'var(--bg-paper)',borderRadius:'16px 16px 0 0',maxHeight:'90%',overflow:'hidden',display:'flex',flexDirection:'column',animation:'v2-detail-in 280ms var(--ease-out)'}} onClick={e => e.stopPropagation()}>
        <div style={{padding:'14px 18px 12px',background:'linear-gradient(105deg, var(--bg-paper) 0%, var(--leaf-100) 100%)',borderBottom:'1px solid var(--border-1)'}}>
          <div style={{width:38,height:4,borderRadius:4,background:'var(--border-2)',margin:'0 auto 10px'}}/>
          <div style={{font:'600 10px var(--font-body)',letterSpacing:'.18em',textTransform:'uppercase',color:'var(--leaf-700)'}}>
            {isBooking ? 'Booking' : isActivity ? 'Activity' : kind === 'cafe-order' ? 'Café order' : 'Shop order'}
          </div>
          <div style={{fontFamily:'var(--font-display)',fontSize:20,fontWeight:500,color:'var(--slate-700)',margin:'4px 0 4px',letterSpacing:'-.02em'}}>{item.title || item.cafe}</div>
          <div style={{font:'500 11px var(--font-mono)',color:'var(--fg-3)',letterSpacing:'.04em'}}>{item.ref} · ₹{(item.amount || item.total)?.toLocaleString()}</div>
        </div>
        <div style={{flex:1,overflowY:'auto',padding:'14px 18px 8px'}}>
          {(isBooking || isActivity) && (
            <>
              <div style={{display:'flex',gap:14,padding:14,background:'var(--bone-100)',borderRadius:12,marginBottom:14}}>
                <div style={{width:80,height:80,borderRadius:6,background:'repeating-linear-gradient(0deg,var(--slate-700) 0 5px,white 5px 10px),repeating-linear-gradient(90deg,var(--slate-700) 0 5px,white 5px 10px)',backgroundBlendMode:'multiply',flexShrink:0,border:'3px solid white',boxShadow:'0 0 0 1px var(--border-1)'}}/>
                <div style={{flex:1}}>
                  <div style={{font:'600 9.5px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>Show at check-in</div>
                  <div style={{fontFamily:'var(--font-mono)',fontSize:14,color:'var(--slate-700)',marginTop:3,letterSpacing:'.04em'}}>{item.voucher || item.ref}</div>
                  <div style={{font:'400 11.5px var(--font-body)',color:'var(--fg-2)',marginTop:6,lineHeight:1.45}}>{isBooking ? item.dates : item.date} · {item.vendor || 'Direct'}</div>
                </div>
              </div>
              <div style={{font:'600 11px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)',marginBottom:6}}>Details</div>
              {isBooking && (<>
                <div style={{display:'flex',justifyContent:'space-between',padding:'7px 0',borderBottom:'1px dashed var(--border-1)',font:'400 13px var(--font-body)',color:'var(--fg-2)'}}><span>Dates</span><strong style={{color:'var(--slate-700)'}}>{item.dates}</strong></div>
                <div style={{display:'flex',justifyContent:'space-between',padding:'7px 0',borderBottom:'1px dashed var(--border-1)',font:'400 13px var(--font-body)',color:'var(--fg-2)'}}><span>Ref</span><strong style={{color:'var(--slate-700)',fontFamily:'var(--font-mono)'}}>{item.ref}</strong></div>
                <div style={{display:'flex',justifyContent:'space-between',padding:'7px 0',font:'400 13px var(--font-body)',color:'var(--fg-2)'}}><span>Amount</span><strong style={{color:'var(--slate-700)',fontFamily:'var(--font-mono)'}}>₹{item.amount?.toLocaleString()}</strong></div>
              </>)}
              {isActivity && (<>
                <div style={{display:'flex',justifyContent:'space-between',padding:'7px 0',borderBottom:'1px dashed var(--border-1)',font:'400 13px var(--font-body)',color:'var(--fg-2)'}}><span>Operator</span><strong style={{color:'var(--slate-700)'}}>{item.vendor}</strong></div>
                <div style={{display:'flex',justifyContent:'space-between',padding:'7px 0',borderBottom:'1px dashed var(--border-1)',font:'400 13px var(--font-body)',color:'var(--fg-2)'}}><span>When</span><strong style={{color:'var(--slate-700)'}}>{item.date}</strong></div>
                <div style={{display:'flex',justifyContent:'space-between',padding:'7px 0',font:'400 13px var(--font-body)',color:'var(--fg-2)'}}><span>Travellers</span><strong style={{color:'var(--slate-700)'}}>{item.adults}</strong></div>
              </>)}
            </>
          )}
          {isOrder && trackSteps && (<>
            <div style={{font:'600 11px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)',marginBottom:10}}>Track this order</div>
            {trackSteps.map((s, i) => (
              <div key={i} style={{display:'grid',gridTemplateColumns:'28px 1fr',gap:12,padding:'6px 0',position:'relative'}}>
                {i < trackSteps.length - 1 && <div style={{position:'absolute',left:13,top:22,bottom:-6,width:2,background:s.state === 'done' ? 'var(--leaf-700)' : 'var(--border-2)'}}/>}
                <div style={{width:28,height:28,borderRadius:'50%',display:'flex',alignItems:'center',justifyContent:'center',background:s.state==='pending'?'var(--bone-100)':'var(--leaf-700)',border:`2px solid ${s.state==='pending'?'var(--border-2)':'var(--leaf-700)'}`,color:s.state==='pending'?'var(--fg-3)':'white',font:'600 11px var(--font-body)',boxShadow:s.state==='current'?'0 0 0 5px rgba(43,124,4,.2)':'none'}}>{s.state==='done'?'✓':s.state==='current'?'●':(i+1)}</div>
                <div style={{padding:'4px 0 10px'}}>
                  <div style={{font:'600 12.5px var(--font-body)',color:s.state==='pending'?'var(--fg-3)':'var(--slate-700)'}}>{s.name}</div>
                  <div style={{font:'400 10.5px var(--font-mono)',color:'var(--fg-3)',marginTop:2,letterSpacing:'.03em'}}>{s.when}</div>
                </div>
              </div>
            ))}
          </>)}
        </div>
        <div style={{padding:'12px 16px 18px',borderTop:'1px solid var(--border-1)',display:'flex',gap:6}}>
          {(isBooking || isActivity) && (<>
            <button onClick={onModify} style={{flex:1,height:42,borderRadius:10,background:'var(--bone-100)',border:'1px solid var(--border-1)',cursor:'pointer',font:'600 11.5px var(--font-body)',color:'var(--slate-700)'}}>Modify</button>
            <button onClick={onCancel} style={{flex:1,height:42,borderRadius:10,background:0,border:'1px solid var(--terracotta)',cursor:'pointer',font:'600 11.5px var(--font-body)',color:'var(--terracotta)'}}>Cancel</button>
            <button onClick={onClose} style={{flex:1,height:42,borderRadius:10,background:'var(--slate-700)',border:0,cursor:'pointer',font:'700 12px var(--font-body)',color:'white'}}>Done</button>
          </>)}
          {isOrder && (<>
            <button onClick={onClose} style={{flex:1,height:42,borderRadius:10,background:'var(--bone-100)',border:'1px solid var(--border-1)',cursor:'pointer',font:'600 11.5px var(--font-body)',color:'var(--slate-700)'}}>Help with order</button>
            <button onClick={onClose} style={{flex:1,height:42,borderRadius:10,background:'var(--slate-700)',border:0,cursor:'pointer',font:'700 12px var(--font-body)',color:'white'}}>Done</button>
          </>)}
        </div>
      </div>
    </div>
  );
}
window.MobileReceiptSheet = MobileReceiptSheet;

// ─── Mobile edit personal / address sheets ─────────
function MobileEditPersonalSheet({ profile, onClose, onSave }) {
  const [name, setName] = useStateMEx(profile?.name || '');
  const [email, setEmail] = useStateMEx('aanya.rana@example.com');
  const [phone, setPhone] = useStateMEx('+91 98765 43210');
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:96}} onClick={onClose}>
      <div className="app-create-sheet" onClick={e => e.stopPropagation()}>
        <div className="app-create-sheet__handle"/>
        <div className="app-create-sheet__lbl">Personal details</div>
        <h2 className="app-create-sheet__t">Edit your <em>info.</em></h2>
        <div className="app-create-sheet__field">
          <label className="app-create-sheet__field-l">Full name</label>
          <input className="app-create-sheet__input" value={name} onChange={e => setName(e.target.value)}/>
        </div>
        <div className="app-create-sheet__field">
          <label className="app-create-sheet__field-l">Email</label>
          <input className="app-create-sheet__input" type="email" value={email} onChange={e => setEmail(e.target.value)}/>
        </div>
        <div className="app-create-sheet__field">
          <label className="app-create-sheet__field-l">Phone</label>
          <input className="app-create-sheet__input" value={phone} onChange={e => setPhone(e.target.value)}/>
        </div>
        <div className="app-create-sheet__actions">
          <button className="app-create-sheet__cancel" onClick={onClose}>Cancel</button>
          <button className="app-create-sheet__submit" onClick={() => onSave({ name, email, phone })}>Save</button>
        </div>
      </div>
    </div>
  );
}
window.MobileEditPersonalSheet = MobileEditPersonalSheet;

function MobileEditAddressSheet({ addr, onClose, onSave, onDelete }) {
  const [draft, setDraft] = useStateMEx(addr || { label:'Home', name:'', phone:'', line1:'', line2:'', city:'', state:'', pincode:'' });
  const isEdit = !!addr?.id;
  const set = (k, v) => setDraft(d => ({ ...d, [k]:v }));
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:96}} onClick={onClose}>
      <div className="app-create-sheet" onClick={e => e.stopPropagation()} style={{maxHeight:'90%'}}>
        <div className="app-create-sheet__handle"/>
        <div className="app-create-sheet__lbl">{isEdit ? 'Edit address' : 'Add address'}</div>
        <h2 className="app-create-sheet__t">{isEdit ? <>Edit <em>{draft.label}.</em></> : <>Add a <em>new address.</em></>}</h2>
        <div className="app-create-sheet__row">
          <div className="app-create-sheet__field">
            <label className="app-create-sheet__field-l">Label</label>
            <select className="app-create-sheet__input" value={draft.label} onChange={e => set('label', e.target.value)}>
              {['Home','Office','Other'].map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div className="app-create-sheet__field">
            <label className="app-create-sheet__field-l">Phone</label>
            <input className="app-create-sheet__input" placeholder="+91 …" value={draft.phone} onChange={e => set('phone', e.target.value)}/>
          </div>
        </div>
        <div className="app-create-sheet__field">
          <label className="app-create-sheet__field-l">Full name</label>
          <input className="app-create-sheet__input" value={draft.name} onChange={e => set('name', e.target.value)}/>
        </div>
        <div className="app-create-sheet__field">
          <label className="app-create-sheet__field-l">Address line 1</label>
          <input className="app-create-sheet__input" value={draft.line1} onChange={e => set('line1', e.target.value)}/>
        </div>
        <div className="app-create-sheet__field">
          <label className="app-create-sheet__field-l">Address line 2 (optional)</label>
          <input className="app-create-sheet__input" value={draft.line2} onChange={e => set('line2', e.target.value)}/>
        </div>
        <div className="app-create-sheet__row">
          <div className="app-create-sheet__field">
            <label className="app-create-sheet__field-l">City</label>
            <input className="app-create-sheet__input" value={draft.city} onChange={e => set('city', e.target.value)}/>
          </div>
          <div className="app-create-sheet__field">
            <label className="app-create-sheet__field-l">Pincode</label>
            <input className="app-create-sheet__input" value={draft.pincode} onChange={e => set('pincode', e.target.value)}/>
          </div>
        </div>
        <div className="app-create-sheet__actions">
          {isEdit && <button onClick={() => onDelete?.(addr.id)} style={{padding:'0 14px',height:46,background:0,border:'1px solid var(--terracotta)',color:'var(--terracotta)',borderRadius:10,cursor:'pointer',font:'600 12px var(--font-body)'}}>Delete</button>}
          <button className="app-create-sheet__cancel" onClick={onClose}>Cancel</button>
          <button className="app-create-sheet__submit" onClick={() => onSave({ ...draft, id:draft.id || ('a' + Date.now()) })}>Save</button>
        </div>
      </div>
    </div>
  );
}
window.MobileEditAddressSheet = MobileEditAddressSheet;

// ─── Pro upgrade sheet (mobile) ─────────────────────────
function MobileUpgradeSheet({ onClose, onSubscribe }) {
  const [cycle, setCycle] = useStateMEx('monthly');
  const price = cycle === 'monthly' ? 299 : 2990;
  return (
    <>
      <div style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:90}} onClick={onClose}/>
      <div className="app-sheet app-sheet--upgrade" onClick={e => e.stopPropagation()}>
        <div className="app-sheet__handle"/>
        <div style={{font:'600 10.5px var(--font-body)',letterSpacing:'.18em',textTransform:'uppercase',color:'var(--leaf-700)'}}>HimLocal Pro</div>
        <h2 style={{fontFamily:'var(--font-display)',fontSize:24,fontWeight:500,letterSpacing:'-.02em',color:'var(--slate-700)',margin:'6px 0 6px'}}>More trips. More <em style={{fontStyle:'italic',fontWeight:400}}>map.</em></h2>
        <p style={{font:'400 13px var(--font-body)',color:'var(--fg-2)',margin:'0 0 16px',lineHeight:1.55}}>Pro is for planners. Upgrade any time, cancel any time.</p>

        <div style={{display:'inline-flex',padding:3,background:'var(--bone-100)',borderRadius:999,marginBottom:16}}>
          <button onClick={() => setCycle('monthly')}
            style={{padding:'7px 14px',border:0,background:cycle==='monthly'?'white':'transparent',color:cycle==='monthly'?'var(--slate-700)':'var(--fg-2)',borderRadius:999,font:'600 11.5px var(--font-body)',cursor:'pointer',boxShadow:cycle==='monthly'?'0 1px 2px rgba(14,26,36,.10)':'none'}}>Monthly</button>
          <button onClick={() => setCycle('annual')}
            style={{padding:'7px 14px',border:0,background:cycle==='annual'?'white':'transparent',color:cycle==='annual'?'var(--slate-700)':'var(--fg-2)',borderRadius:999,font:'600 11.5px var(--font-body)',cursor:'pointer',boxShadow:cycle==='annual'?'0 1px 2px rgba(14,26,36,.10)':'none'}}>Annual <span style={{font:'500 9px var(--font-mono)',padding:'1px 5px',marginLeft:4,borderRadius:999,background:'var(--leaf-100)',color:'var(--leaf-800)'}}>−17%</span></button>
        </div>

        <div style={{padding:18,background:'linear-gradient(155deg, var(--leaf-100) 0%, var(--bg-paper) 70%)',border:'1px solid var(--leaf-500)',borderRadius:12,marginBottom:14}}>
          <div style={{font:'600 10.5px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--leaf-700)'}}>Pro · Multi-trip</div>
          <div style={{fontFamily:'var(--font-display)',fontSize:28,fontWeight:500,letterSpacing:'-.02em',color:'var(--slate-700)',marginTop:4}}>₹{price.toLocaleString()}<small style={{font:'500 12px var(--font-body)',color:'var(--fg-3)',marginLeft:4}}>/{cycle === 'monthly' ? 'month' : 'year'}</small></div>
          <ul style={{listStyle:'none',padding:0,margin:'12px 0 0',display:'flex',flexDirection:'column',gap:6}}>
            {['10 itineraries (Free is 1)','Nearby mode + offline tiles','Curated departures 7 days early','0% platform fee on bookings','4-hour reply SLA · host support','GST invoice export'].map((f, i) => (
              <li key={i} style={{font:'400 12.5px var(--font-body)',color:'var(--fg-1)',paddingLeft:20,position:'relative',lineHeight:1.5}}>
                <span style={{position:'absolute',left:0,top:2,width:14,height:14,borderRadius:'50%',background:'var(--leaf-700)',color:'white',display:'inline-flex',alignItems:'center',justifyContent:'center',fontSize:8,fontWeight:700}}>✓</span>
                {f}
              </li>
            ))}
          </ul>
        </div>

        <button onClick={() => onSubscribe(cycle, price)}
          style={{width:'100%',height:48,borderRadius:12,border:0,background:'var(--grad-cta-itinerary)',color:'white',font:'700 13.5px var(--font-body)',cursor:'pointer',boxShadow:'0 6px 18px rgba(48,92,222,.30)'}}>
          Start Pro · ₹{price.toLocaleString()}
        </button>
        <div style={{font:'400 10.5px var(--font-body)',color:'var(--fg-3)',textAlign:'center',marginTop:10,lineHeight:1.45}}>Auto-renews until cancelled. 7-day refund. UPI · card · net-banking.</div>
        <button onClick={onClose} style={{width:'100%',marginTop:10,padding:8,background:0,border:0,font:'500 11.5px var(--font-body)',color:'var(--fg-3)',cursor:'pointer'}}>Not now</button>
      </div>
    </>
  );
}
window.MobileUpgradeSheet = MobileUpgradeSheet;

// ─── Modify booking sheet (mobile) ──────────────────────
function MobileModifyBookingSheet({ booking, onClose, onSubmit }) {
  const today = new Date();
  const fmt = (d) => d.toISOString().slice(0, 10);
  const [start, setStart] = useStateMEx(booking?.start || fmt(today));
  const [end,   setEnd]   = useStateMEx(booking?.end   || fmt(new Date(today.getTime() + 86400000)));
  const [note,  setNote]  = useStateMEx('');
  const nights = useMemoMEx(() => {
    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 style={{position:'absolute',inset:0,background:'rgba(14,26,36,.55)',zIndex:90}} onClick={onClose}/>
      <div className="app-sheet" onClick={e => e.stopPropagation()}>
        <div className="app-sheet__handle"/>
        <div style={{font:'600 10.5px var(--font-body)',letterSpacing:'.18em',textTransform:'uppercase',color:'var(--leaf-700)'}}>Modify booking</div>
        <h2 style={{fontFamily:'var(--font-display)',fontSize:22,fontWeight:500,letterSpacing:'-.02em',color:'var(--slate-700)',margin:'6px 0 4px'}}>{booking?.title || 'Your stay'}</h2>
        <p style={{font:'400 12.5px var(--font-body)',color:'var(--fg-2)',margin:'0 0 14px',lineHeight:1.5}}>Pick new dates. We'll send the request to the host — they reply within 4 hours.</p>

        {window.MobileDateRangePicker ? (
          <div style={{marginBottom:12}}>
            <window.MobileDateRangePicker start={start} end={end} label="Dates"
              onChange={({ start:s, end:e }) => { if (s) setStart(s); if (e) setEnd(e); }}/>
          </div>
        ) : (
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:10}}>
            <label style={{display:'flex',flexDirection:'column',gap:5}}>
              <span style={{font:'600 10px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>Check-in</span>
              <input type="date" value={start} onChange={e => setStart(e.target.value)}
                style={{height:42,padding:'0 10px',borderRadius:9,border:'1px solid var(--border-2)',background:'white',font:'500 13px var(--font-body)',color:'var(--slate-700)'}}/>
            </label>
            <label style={{display:'flex',flexDirection:'column',gap:5}}>
              <span style={{font:'600 10px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>Check-out</span>
              <input type="date" value={end} onChange={e => setEnd(e.target.value)} min={start}
                style={{height:42,padding:'0 10px',borderRadius:9,border:'1px solid var(--border-2)',background:'white',font:'500 13px var(--font-body)',color:'var(--slate-700)'}}/>
            </label>
          </div>
        )}
        <div style={{padding:'10px 12px',background:'var(--leaf-100)',borderRadius:9,font:'500 12.5px var(--font-body)',color:'var(--leaf-800)',marginBottom:12}}>
          <strong>{nights}</strong> {nights === 1 ? 'night' : 'nights'} · {start} → {end}
        </div>
        <label style={{display:'flex',flexDirection:'column',gap:5,marginBottom:12}}>
          <span style={{font:'600 10px var(--font-body)',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--fg-3)'}}>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."
            style={{minHeight:56,padding:'8px 10px',borderRadius:8,border:'1px solid var(--border-2)',background:'white',font:'400 12.5px var(--font-body)',color:'var(--fg-1)',resize:'vertical'}}/>
        </label>
        <button onClick={() => onSubmit({ start, end, note:note.trim() || undefined, nights })}
          style={{width:'100%',height:46,borderRadius:11,border:0,background:'var(--grad-cta-book)',color:'white',font:'700 13.5px var(--font-body)',cursor:'pointer',boxShadow:'0 6px 18px rgba(11,218,81,.30)'}}>
          Send modification request
        </button>
        <button onClick={onClose}
          style={{width:'100%',marginTop:10,padding:8,background:0,border:0,font:'500 11.5px var(--font-body)',color:'var(--fg-3)',cursor:'pointer'}}>Cancel</button>
      </div>
    </>
  );
}
window.MobileModifyBookingSheet = MobileModifyBookingSheet;

// ─── Shared mobile date-range picker (uses WebCalendarPanel inside a sheet) ──
// One component so every flow (booking gate, create-itin, modify dates, trip
// context) uses the SAME in-app calendar instead of the native iOS picker.
function MobileDateRangePicker({ start, end, onChange, label = 'Dates', minNights = 1 }) {
  const [open, setOpen] = useStateMEx(false);
  const fmt = (s) => {
    if (!s) return '—';
    try { return new Date(s + 'T00:00:00').toLocaleDateString('en-IN', { day:'numeric', month:'short' }); }
    catch { return s; }
  };
  return (
    <>
      <button type="button" className="app-daterange-pill" onClick={() => setOpen(true)}>
        <span className="app-daterange-pill__l">{label}</span>
        <span className="app-daterange-pill__v">{fmt(start)} → {fmt(end)}</span>
      </button>
      {open && (
        <>
          <div className="app-daterange-back" onClick={() => setOpen(false)}/>
          <div className="app-daterange-sheet" onClick={e => e.stopPropagation()}>
            <div className="app-sheet__handle"/>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
              <div style={{font:'600 10.5px var(--font-body)',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--leaf-700)'}}>{label}</div>
              <button onClick={() => setOpen(false)} style={{background:0,border:0,font:'500 16px var(--font-body)',color:'var(--fg-3)',cursor:'pointer'}}>×</button>
            </div>
            {window.WebCalendarPanel ? (
              <window.WebCalendarPanel mode="mobile" start={start} end={end}
                onChange={({ start:s, end:e }) => onChange({ start:s, end:e })}/>
            ) : (
              <div style={{padding:20,color:'var(--fg-3)',textAlign:'center'}}>Calendar component missing.</div>
            )}
            <button onClick={() => setOpen(false)}
              style={{width:'100%',marginTop:10,height:46,borderRadius:11,border:0,background:'var(--slate-700)',color:'white',font:'700 13px var(--font-body)',cursor:'pointer'}}>
              Done
            </button>
          </div>
        </>
      )}
    </>
  );
}
window.MobileDateRangePicker = MobileDateRangePicker;
