// demo-friendly.jsx — Friendly Market interactive prototype
// Wires Variation A's screens into a real navigation flow with state.

const { useState, useEffect, useRef, useMemo } = React;

const T = {
  bg: '#FBF4E4',
  surface: '#FFFFFF',
  ink: '#2A1E14',
  inkSoft: '#7A6850',
  primary: '#E26B2C',
  accent: '#3F8A4C',
  accentSoft: '#E5F0DA',
  primarySoft: '#FFE9D0',
  cream: '#F4E8D0',
  hairline: '#EBDFC4',
  display: '"DM Serif Display", Georgia, serif',
  body: '"Plus Jakarta Sans", system-ui, sans-serif',
  mono: '"IBM Plex Mono", monospace',
};

// ── Toast
function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div style={{
      position: 'absolute', left: 18, right: 18, bottom: 110, zIndex: 80,
      background: T.ink, color: '#fff',
      borderRadius: 14, padding: '12px 16px',
      fontFamily: T.body, fontSize: 13, fontWeight: 600,
      display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
    }} className="modal-enter" key={msg}>
      <IconCheck size={16} stroke={T.accent}/>
      {msg}
    </div>
  );
}

// ── Tab bar (interactive)
function TabBar({ active, onTab }) {
  const tabs = [
    { id: 'home',    icon: IconHome,  label: 'Shop' },
    { id: 'browse',  icon: IconStore, label: 'Stores' },
    { id: 'lists',   icon: IconList,  label: 'Lists' },
    { id: 'cart',    icon: IconCart,  label: 'Cart' },
    { id: 'me',      icon: IconUser,  label: 'Me' },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      paddingBottom: 24, paddingTop: 10, zIndex: 40,
      background: 'linear-gradient(to top, ' + T.bg + ' 75%, rgba(251,244,228,0))',
      display: 'flex', justifyContent: 'space-around', alignItems: 'center',
    }}>
      {tabs.map(t => {
        const I = t.icon;
        const on = t.id === active;
        return (
          <button key={t.id} onClick={() => onTab(t.id)} style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            padding: '4px 8px',
          }}>
            <I size={22} stroke={on ? T.primary : T.inkSoft} sw={on ? 2 : 1.7}/>
            <div style={{ fontSize: 10, fontWeight: 700, color: on ? T.primary : T.inkSoft, letterSpacing: 0.2 }}>{t.label}</div>
          </button>
        );
      })}
    </div>
  );
}

// ── Header
function Nav({ left, title, right }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '8px 18px 12px', minHeight: 44,
    }}>
      <div style={{ minWidth: 36, flexShrink: 0 }}>{left}</div>
      <div style={{ fontFamily: T.display, fontSize: 22, color: T.ink, lineHeight: 1, whiteSpace: 'nowrap' }}>{title}</div>
      <div style={{ minWidth: 36, flexShrink: 0, display: 'flex', justifyContent: 'flex-end' }}>{right}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Browse screen (home)
// ─────────────────────────────────────────────────────────
function BrowseScreen({ go, openProduct, addToast, cart }) {
  const cartCount = cart.reduce((n,l) => n + l.qty, 0);
  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 110 }}>
      <div style={{ padding: '8px 18px 6px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <button style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <IconPin size={16} stroke={T.primary}/>
            <span style={{ fontSize: 13, fontWeight: 700 }}>Bushwick, BK</span>
            <IconChevD size={14} stroke={T.ink}/>
          </button>
          <div style={{ display: 'flex', gap: 14 }}>
            <button><IconBell size={20} stroke={T.ink}/></button>
            <button onClick={() => go('cart')} style={{ position: 'relative' }}>
              <IconCart size={20} stroke={T.ink}/>
              {cartCount > 0 && (
                <span style={{
                  position: 'absolute', top: -4, right: -6,
                  background: T.primary, color: '#fff',
                  width: 16, height: 16, borderRadius: 999,
                  fontSize: 9, fontWeight: 700,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{cartCount}</span>
              )}
            </button>
          </div>
        </div>
        <div style={{ fontFamily: T.display, fontSize: 30, lineHeight: 1.05, marginTop: 4 }}>
          Hi Maya — let's<br/>find you a deal.
        </div>
      </div>

      {/* Search */}
      <div style={{ padding: '14px 18px 14px' }}>
        <button onClick={() => go('search')} style={{
          background: T.surface, borderRadius: 18, padding: '12px 14px',
          display: 'flex', alignItems: 'center', gap: 10, width: '100%',
          boxShadow: '0 1px 0 ' + T.hairline,
        }}>
          <IconSearch size={18} stroke={T.inkSoft}/>
          <span style={{ flex: 1, color: T.inkSoft, fontSize: 14, textAlign: 'left' }}>Search across 5 stores…</span>
          <IconScan size={18} stroke={T.primary}/>
        </button>
      </div>

      {/* Categories */}
      <div style={{ display: 'flex', gap: 10, padding: '0 18px 18px', overflow: 'hidden' }}>
        {CATEGORIES.map((c, i) => (
          <button key={c.id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, minWidth: 64 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 18,
              background: i === 0 ? T.ink : T.surface,
              color: i === 0 ? '#fff' : T.ink,
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
              boxShadow: '0 1px 0 ' + T.hairline,
            }}>{c.emoji}</div>
            <div style={{ fontSize: 11, fontWeight: 600 }}>{c.label}</div>
          </button>
        ))}
      </div>

      {/* Featured deal */}
      <div style={{ padding: '0 18px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
          <div style={{ fontFamily: T.display, fontSize: 20 }}>This week's deals</div>
          <div style={{ fontSize: 12, color: T.primary, fontWeight: 700 }}>See all</div>
        </div>
        <button onClick={() => openProduct('apples')} style={{
          background: 'linear-gradient(135deg, #FFE9D0 0%, #F4E8D0 100%)',
          borderRadius: 24, padding: 18, position: 'relative', overflow: 'hidden', textAlign: 'left', width: '100%',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 76, height: 76, borderRadius: 20, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 40 }}>🍎</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', gap: 6, marginBottom: 4 }}>
                <Pill bg={T.primary} color="#fff" size={10}>20% OFF</Pill>
                <Pill bg={T.surface} color={T.ink} size={10}>2 days left</Pill>
              </div>
              <div style={{ fontFamily: T.display, fontSize: 20, lineHeight: 1.1 }}>Honeycrisp Apples</div>
              <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 4 }}>at Greenleaf · 3 lb bag</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8 }}>
                <span style={{ fontFamily: T.display, fontSize: 22, color: T.primary }}>$7.99</span>
                <span style={{ fontSize: 13, color: T.inkSoft, textDecoration: 'line-through' }}>$9.99</span>
              </div>
            </div>
          </div>
        </button>
      </div>

      <div style={{ padding: '0 18px' }}>
        <div style={{ fontFamily: T.display, fontSize: 18, marginBottom: 10 }}>More to save on</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {DEALS.slice(1).map(d => {
            const store = STORES.find(s => s.id === d.store);
            const matchProduct = PRODUCTS.find(p => p.name.toLowerCase().includes(d.product.toLowerCase().split(' ')[0])) || PRODUCTS[0];
            return (
              <button key={d.id} onClick={() => openProduct(matchProduct.id)} style={{
                background: T.surface, borderRadius: 16, padding: '10px 12px',
                display: 'flex', alignItems: 'center', gap: 12, boxShadow: '0 1px 0 ' + T.hairline, width: '100%',
              }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12, background: T.cream,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
                }}>{d.emoji}</div>
                <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                  <div style={{ fontSize: 14, fontWeight: 700 }}>{d.product}</div>
                  <div style={{ fontSize: 11, color: T.inkSoft, marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <span style={{ width: 6, height: 6, borderRadius: 999, background: store.color }}/>
                    {store.name} · {d.badge}
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: T.display, fontSize: 16, color: T.primary }}>${d.now.toFixed(2)}</div>
                  <div style={{ fontSize: 10, color: T.inkSoft, textDecoration: 'line-through' }}>${d.was.toFixed(2)}</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Search input → product compare
// ─────────────────────────────────────────────────────────
function SearchScreen({ go, openProduct }) {
  const [q, setQ] = useState('');
  const filtered = useMemo(() => {
    if (!q) return PRODUCTS;
    return PRODUCTS.filter(p => p.name.toLowerCase().includes(q.toLowerCase()));
  }, [q]);

  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 110 }}>
      <Nav
        left={<button onClick={() => go('home')}><IconChevL size={24} stroke={T.ink}/></button>}
        title="Search"
        right={<div style={{ width: 24 }}/>}
      />
      <div style={{ padding: '0 18px 14px' }}>
        <div style={{
          background: T.surface, borderRadius: 18,
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '12px 14px', boxShadow: '0 1px 0 ' + T.hairline,
        }}>
          <IconSearch size={18} stroke={T.inkSoft}/>
          <input
            autoFocus
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Try 'carrots', 'milk'…"
            style={{
              flex: 1, border: 'none', outline: 'none',
              fontFamily: T.body, fontSize: 14, fontWeight: 600, color: T.ink,
              background: 'transparent', minWidth: 0,
            }}/>
          {q && <button onClick={() => setQ('')}><IconX size={16} stroke={T.inkSoft}/></button>}
        </div>
      </div>

      {!q && (
        <div style={{ padding: '0 18px 14px' }}>
          <div style={{ fontSize: 11, color: T.inkSoft, fontWeight: 700, letterSpacing: 1, marginBottom: 8 }}>POPULAR</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {['Carrots','Whole milk','Sourdough','Eggs','Apples','Pasta'].map(s => (
              <button key={s} onClick={() => setQ(s)} style={{
                padding: '7px 12px', borderRadius: 999, background: T.surface,
                fontSize: 12, fontWeight: 600, color: T.ink, boxShadow: '0 1px 0 ' + T.hairline,
              }}>{s}</button>
            ))}
          </div>
        </div>
      )}

      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.map(p => {
          const prices = STORES.map(s => p.prices[s.id].price);
          const min = Math.min(...prices), max = Math.max(...prices);
          return (
            <button key={p.id} onClick={() => openProduct(p.id)} className="fade-enter" style={{
              background: T.surface, borderRadius: 16, padding: 12,
              display: 'flex', alignItems: 'center', gap: 12, width: '100%',
              boxShadow: '0 1px 0 ' + T.hairline,
            }}>
              <div style={{
                width: 48, height: 48, borderRadius: 12, background: T.cream,
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
              }}>{p.emoji}</div>
              <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: T.inkSoft, marginTop: 2 }}>{p.unit} · 5 stores</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0, minWidth: 96 }}>
                <div style={{ fontFamily: T.display, fontSize: 14, color: T.primary, lineHeight: 1.1, whiteSpace: 'nowrap' }}>
                  ${min.toFixed(2)}–${max.toFixed(2)}
                </div>
                <div style={{ fontSize: 10, color: T.inkSoft, marginTop: 4 }}>compare →</div>
              </div>
            </button>
          );
        })}
        {!filtered.length && (
          <div style={{ padding: 40, textAlign: 'center', color: T.inkSoft, fontSize: 13 }}>
            No matches. Try "milk", "apples"…
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Product compare (single item)
// ─────────────────────────────────────────────────────────
function ProductScreen({ productId, go, addToCart, cart, addToast }) {
  const product = PRODUCTS.find(p => p.id === productId);
  const [sortBy, setSortBy] = useState('value');
  const [savedStore, setSavedStore] = useState(null);

  const sortedStores = useMemo(() => {
    const list = [...STORES];
    if (sortBy === 'price') return list.sort((a,b) => product.prices[a.id].price - product.prices[b.id].price);
    if (sortBy === 'quality') return list.sort((a,b) => product.prices[b.id].quality - product.prices[a.id].quality);
    if (sortBy === 'distance') return list.sort((a,b) => parseFloat(a.distance) - parseFloat(b.distance));
    if (sortBy === 'organic') return list.filter(s => product.prices[s.id].organic).concat(list.filter(s => !product.prices[s.id].organic));
    // value: combine
    return list.sort((a,b) => {
      const A = product.prices[a.id].quality / product.prices[a.id].price;
      const B = product.prices[b.id].quality / product.prices[b.id].price;
      return B - A;
    });
  }, [sortBy, productId]);

  const min = Math.min(...STORES.map(s => product.prices[s.id].price));
  const maxQ = Math.max(...STORES.map(s => product.prices[s.id].quality));

  const sorts = [
    { id: 'value',    label: 'Best value' },
    { id: 'price',    label: 'Cheapest' },
    { id: 'quality',  label: 'Highest quality' },
    { id: 'distance', label: 'Closest' },
    { id: 'organic',  label: 'Organic only' },
  ];

  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 130 }}>
      <Nav
        left={<button onClick={() => go(-1)}><IconChevL size={24} stroke={T.ink}/></button>}
        title="Compare"
        right={<button onClick={() => addToast('Saved to favorites')}><IconHeart size={22} stroke={T.ink}/></button>}
      />
      {/* Hero */}
      <div style={{ padding: '0 18px 12px' }}>
        <div style={{
          background: T.primarySoft, borderRadius: 24, padding: 18,
          display: 'flex', alignItems: 'center', gap: 14, position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            width: 72, height: 72, borderRadius: 18, background: T.surface,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 38,
          }}>{product.emoji}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: T.display, fontSize: 22, lineHeight: 1.1 }}>{product.name}</div>
            <div style={{ fontSize: 13, color: T.inkSoft, marginTop: 2 }}>{product.unit} · 5 stores nearby</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
              <Pill bg={T.accentSoft} color={T.accent}>From ${min.toFixed(2)}</Pill>
              <Pill bg="#F4E8D0" color={T.ink}>Pickup ≤ 30m</Pill>
            </div>
          </div>
        </div>
      </div>

      {/* Sort chips */}
      <div style={{ display: 'flex', gap: 8, padding: '4px 18px 14px', overflowX: 'auto' }}>
        {sorts.map(s => (
          <button key={s.id} onClick={() => setSortBy(s.id)} style={{
            padding: '7px 12px', borderRadius: 999, flexShrink: 0,
            background: sortBy === s.id ? T.ink : T.surface,
            color: sortBy === s.id ? '#fff' : T.ink,
            fontSize: 12, fontWeight: 700,
          }}>{s.label}</button>
        ))}
      </div>

      {/* Rows */}
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {sortedStores.map((s, i) => {
          const offer = product.prices[s.id];
          const isCheapest = offer.price === min;
          const isHighestQ = offer.quality === maxQ;
          const saved = savedStore === s.id;
          return (
            <div key={s.id} className="fade-enter" style={{
              background: T.surface, borderRadius: 20, padding: '14px 14px 12px',
              boxShadow: '0 1px 0 ' + T.hairline,
              border: saved ? `1.5px solid ${T.primary}` : (i === 0 && sortBy === 'value' ? `1.5px solid ${T.accent}` : '1.5px solid transparent'),
              position: 'relative', transition: 'border-color 200ms',
            }}>
              {isCheapest && (
                <div style={{
                  position: 'absolute', top: -10, right: 14,
                  background: T.primary, color: '#fff',
                  padding: '4px 10px', borderRadius: 999,
                  fontSize: 10, fontWeight: 700, letterSpacing: 0.4,
                }}>BEST PRICE</div>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <StoreMark store={s} size={42} radius={12}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                    <span style={{ fontWeight: 700, fontSize: 15, whiteSpace: 'nowrap' }}>{s.name}</span>
                    {isHighestQ && <Pill bg={T.accentSoft} color={T.accent} size={10}>TOP QUALITY</Pill>}
                    {offer.organic && <Pill bg={T.accentSoft} color={T.accent} size={10}>ORGANIC</Pill>}
                  </div>
                  <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {s.distance} · {offer.tag}
                  </div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontFamily: T.display, fontSize: 22, color: T.ink, lineHeight: 1 }}>
                    ${offer.price.toFixed(2)}
                  </div>
                  <div style={{ fontSize: 10, color: T.inkSoft, marginTop: 2 }}>each</div>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
                <div style={{ flex: 1, height: 6, background: T.cream, borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{
                    width: `${offer.quality}%`, height: '100%',
                    background: `linear-gradient(90deg, ${T.accent}, ${T.primary})`,
                    transition: 'width 400ms ease',
                  }}/>
                </div>
                <div style={{ fontSize: 11, fontWeight: 700, minWidth: 60, textAlign: 'right' }}>
                  Q {offer.quality} · ★ {s.rating}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                <button onClick={() => {
                  addToCart(productId, s.id);
                  addToast(`Added ${product.name} from ${s.name}`);
                }} style={{
                  flex: 1, padding: '10px 0', borderRadius: 12,
                  background: T.ink, color: '#fff',
                  fontSize: 12, fontWeight: 700,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                }}>
                  <IconPlus size={14} stroke="#fff"/> Add to cart
                </button>
                <button onClick={() => setSavedStore(saved ? null : s.id)} style={{
                  width: 44, padding: '10px 0', borderRadius: 12,
                  background: saved ? T.primarySoft : T.cream, color: T.ink,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <IconBookmark size={16} stroke={saved ? T.primary : T.ink} fill={saved ? T.primary : 'none'}/>
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Cart compare
// ─────────────────────────────────────────────────────────
function CartScreen({ cart, setCart, go, addToast, mode, setMode, deliveryPartner }) {
  const totals = useMemo(() => {
    const list = STORES.map(s => ({
      store: s,
      ...storeTotal(cart, s.id, { delivery: mode === 'delivery' ? deliveryPartner : null }),
    })).sort((a,b) => a.total - b.total);
    return list;
  }, [cart, mode, deliveryPartner]);

  if (cart.length === 0) {
    return (
      <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 110 }}>
        <Nav left={<button onClick={() => go('home')}><IconChevL size={24} stroke={T.ink}/></button>} title="Your basket" right={<div style={{ width:24}}/>}/>
        <div style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 64, marginBottom: 12 }}>🧺</div>
          <div style={{ fontFamily: T.display, fontSize: 22, marginBottom: 8 }}>Your basket is empty</div>
          <div style={{ fontSize: 13, color: T.inkSoft, marginBottom: 20 }}>Add items from the home screen to compare totals.</div>
          <button onClick={() => go('home')} style={{
            background: T.primary, color: '#fff', padding: '12px 24px', borderRadius: 14,
            fontSize: 13, fontWeight: 700,
          }}>Start shopping</button>
        </div>
      </div>
    );
  }

  const min = totals[0].total, max = totals[totals.length-1].total;

  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 130 }}>
      <Nav
        left={<button onClick={() => go('home')}><IconChevL size={24} stroke={T.ink}/></button>}
        title="Your basket"
        right={<button onClick={() => { setCart([]); addToast('Basket cleared'); }}><IconX size={22} stroke={T.ink}/></button>}
      />

      {/* Cart strip */}
      <div style={{ padding: '0 18px 12px' }}>
        <div style={{
          background: T.surface, borderRadius: 20, padding: '12px 14px',
          boxShadow: '0 1px 0 ' + T.hairline,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={{ fontSize: 13, color: T.inkSoft }}>{cart.length} item{cart.length === 1 ? '' : 's'}</div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {cart.map((line, i) => {
              const p = PRODUCTS.find(x => x.id === line.productId);
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 10, background: T.cream,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, flexShrink: 0,
                  }}>{p.emoji}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
                    <div style={{ fontSize: 10, color: T.inkSoft }}>{p.unit}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <button onClick={() => {
                      const next = cart.map((l,j) => j === i ? { ...l, qty: Math.max(0, l.qty - 1) } : l).filter(l => l.qty > 0);
                      setCart(next);
                    }} style={{
                      width: 24, height: 24, borderRadius: 999, background: T.cream,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <IconMinus size={12} stroke={T.ink}/>
                    </button>
                    <span style={{ fontFamily: T.display, fontSize: 14, minWidth: 12, textAlign: 'center' }}>{line.qty}</span>
                    <button onClick={() => {
                      setCart(cart.map((l,j) => j === i ? { ...l, qty: l.qty + 1 } : l));
                    }} style={{
                      width: 24, height: 24, borderRadius: 999, background: T.cream,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <IconPlus size={12} stroke={T.ink}/>
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Mode toggle */}
      <div style={{ padding: '0 18px 14px' }}>
        <div style={{
          background: T.surface, borderRadius: 14, padding: 4, display: 'flex',
          boxShadow: '0 1px 0 ' + T.hairline,
        }}>
          {['delivery','pickup'].map(m => (
            <button key={m} onClick={() => setMode(m)} style={{
              flex: 1, padding: '10px 0', borderRadius: 10,
              background: mode === m ? T.ink : 'transparent',
              color: mode === m ? '#fff' : T.inkSoft,
              fontWeight: 700, fontSize: 13,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              transition: 'background 200ms',
            }}>
              {m === 'delivery' ? <IconTruck size={16}/> : <IconBag size={16}/>}
              {m === 'delivery' ? 'Delivery' : 'Pickup'}
            </button>
          ))}
        </div>
      </div>

      <div style={{ padding: '0 18px 8px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div style={{ fontFamily: T.display, fontSize: 18 }}>Total at each store</div>
        <div style={{ fontSize: 11, color: T.inkSoft, fontWeight: 600 }}>{mode === 'delivery' ? 'incl. fees' : 'no fees'}</div>
      </div>

      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {totals.map((t, i) => (
          <div key={t.store.id} className="fade-enter" style={{
            background: T.surface, borderRadius: 20, padding: '14px',
            boxShadow: '0 1px 0 ' + T.hairline,
            border: i === 0 ? `1.5px solid ${T.primary}` : '1.5px solid transparent',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
              <StoreMark store={t.store} size={40}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 15, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                  <span style={{ whiteSpace: 'nowrap' }}>{t.store.name}</span>
                  {i === 0 && <Pill bg={T.primary} color="#fff" size={10}>SAVE ${(max-t.total).toFixed(2)}</Pill>}
                </div>
                <div style={{ fontSize: 11, color: T.inkSoft, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {t.availableCount}/{t.totalCount} items · Q {Math.round(t.avgQuality)}
                  {mode === 'delivery' ? ` · ${deliveryPartner.etaMin}–${deliveryPartner.etaMax}m` : ` · ${t.store.pickupReady}`}
                </div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontFamily: T.display, fontSize: 22, lineHeight: 1 }}>
                  ${t.total.toFixed(2)}
                </div>
                {mode === 'delivery' && (
                  <div style={{ fontSize: 10, color: T.inkSoft, marginTop: 2 }}>+${(t.fees + t.serviceFee).toFixed(2)} fees</div>
                )}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 4 }}>
              <div style={{ flex: 1, height: 6, background: T.cream, borderRadius: 999, overflow: 'hidden' }}>
                <div style={{
                  width: `${100 - ((t.total - min) / (max - min || 1)) * 80}%`,
                  height: '100%', background: T.primary, transition: 'width 400ms',
                }}/>
              </div>
              <div style={{ flex: 1, height: 6, background: T.cream, borderRadius: 999, overflow: 'hidden' }}>
                <div style={{ width: `${t.avgQuality}%`, height: '100%', background: T.accent, transition: 'width 400ms' }}/>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
              <div style={{ flex: 1, fontSize: 9, color: T.primary, fontWeight: 700, letterSpacing: 0.3 }}>VALUE</div>
              <div style={{ flex: 1, fontSize: 9, color: T.accent, fontWeight: 700, letterSpacing: 0.3 }}>QUALITY</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ padding: '20px 18px 0' }}>
        <button onClick={() => go('delivery')} style={{
          background: T.primary, color: '#fff', borderRadius: 16, width: '100%',
          padding: '16px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1 }}>Choose how to get it</div>
            <div style={{ fontSize: 12, opacity: 0.9, marginTop: 4 }}>From {totals[0].store.name} · ${totals[0].total.toFixed(2)}</div>
          </div>
          <IconArrowR size={22} stroke="#fff"/>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Delivery vs pickup decision
// ─────────────────────────────────────────────────────────
function DeliveryScreen({ cart, go, addToast, mode, setMode, deliveryPartner, setDeliveryPartner }) {
  const totals = STORES.map(s => ({ store: s, ...storeTotal(cart, s.id) }))
    .sort((a,b) => a.total - b.total);
  const bestStore = totals[0].store;

  const pickupOptions = totals.slice(0,3)
    .map(o => ({ kind: 'pickup', store: o.store, total: o.total, eta: o.store.pickupReady, note: o.store.distance + ' away' }));
  const deliveryOptions = DELIVERY_PARTNERS.map(p => {
    const t = storeTotal(cart, bestStore.id, { delivery: p });
    return { kind: 'delivery', partner: p, store: bestStore, total: t.total, fees: t.fees + t.serviceFee, eta: `${p.etaMin}–${p.etaMax} min` };
  });

  const all = [...pickupOptions, ...deliveryOptions].sort((a,b) => a.total - b.total);
  const cheapest = all[0];
  const max = all[all.length-1].total;
  const [selected, setSelected] = useState(`${cheapest.kind}-${cheapest.kind === 'pickup' ? cheapest.store.id : cheapest.partner.id}`);

  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 130 }}>
      <Nav
        left={<button onClick={() => go('cart')}><IconChevL size={24} stroke={T.ink}/></button>}
        title="How to get it"
        right={<div style={{ width: 24 }}/>}
      />

      <div style={{ padding: '0 18px 14px' }}>
        <div style={{
          background: T.ink, color: '#fff', borderRadius: 22, padding: 18,
        }}>
          <div style={{ fontSize: 11, letterSpacing: 1.4, opacity: 0.7, fontWeight: 700 }}>BEST OVERALL</div>
          <div style={{ fontFamily: T.display, fontSize: 24, lineHeight: 1.1, marginTop: 6 }}>
            {cheapest.kind === 'pickup' ? `Pickup at ${cheapest.store.name}` : `${cheapest.partner.name} delivery`}
          </div>
          <div style={{ fontSize: 13, opacity: 0.8, marginTop: 6 }}>
            ${cheapest.total.toFixed(2)} — {cheapest.kind === 'pickup' ? `ready in ${cheapest.eta}` : cheapest.eta}. Save ${(max - cheapest.total).toFixed(2)} vs priciest.
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
            <Pill bg="rgba(255,255,255,0.15)" color="#fff" size={11}>{cheapest.kind === 'pickup' ? 'NO FEES' : 'CHEAPEST DELIVERY'}</Pill>
            <Pill bg={T.primary} color="#fff" size={11}>RECOMMENDED</Pill>
          </div>
        </div>
      </div>

      <div style={{ padding: '4px 18px 8px', display: 'flex', alignItems: 'baseline', gap: 8, whiteSpace: 'nowrap' }}>
        <IconBag size={16} stroke={T.ink}/>
        <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1 }}>Pick it up</div>
        <div style={{ fontSize: 11, color: T.inkSoft, fontWeight: 600 }}>· no fees</div>
      </div>
      <div style={{ padding: '0 18px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {pickupOptions.map((o,i) => {
          const k = `pickup-${o.store.id}`;
          const sel = selected === k;
          return (
            <button key={k} onClick={() => { setSelected(k); setMode('pickup'); }} style={{
              background: T.surface, borderRadius: 16, padding: '12px 14px', width: '100%',
              display: 'flex', alignItems: 'center', gap: 12,
              boxShadow: '0 1px 0 ' + T.hairline,
              border: sel ? `1.5px solid ${T.primary}` : '1.5px solid transparent',
              transition: 'border-color 150ms',
            }}>
              <StoreMark store={o.store} size={36}/>
              <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{o.store.name}</div>
                <div style={{ fontSize: 11, color: T.inkSoft, marginTop: 2 }}>Ready in {o.eta} · {o.note}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1 }}>${o.total.toFixed(2)}</div>
                <div style={{ fontSize: 10, color: T.accent, fontWeight: 700, marginTop: 2 }}>FREE</div>
              </div>
            </button>
          );
        })}
      </div>

      <div style={{ padding: '4px 18px 8px', display: 'flex', alignItems: 'baseline', gap: 8, whiteSpace: 'nowrap', overflow: 'hidden' }}>
        <IconTruck size={16} stroke={T.ink}/>
        <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1 }}>Deliver to me</div>
        <div style={{ fontSize: 11, color: T.inkSoft, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis' }}>· from {bestStore.name}</div>
      </div>
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {deliveryOptions.map((o,i) => {
          const k = `delivery-${o.partner.id}`;
          const sel = selected === k;
          return (
            <button key={k} onClick={() => { setSelected(k); setMode('delivery'); setDeliveryPartner(o.partner); }} style={{
              background: T.surface, borderRadius: 16, padding: '12px 14px', width: '100%',
              display: 'flex', alignItems: 'center', gap: 12,
              boxShadow: '0 1px 0 ' + T.hairline,
              border: sel ? `1.5px solid ${T.primary}` : '1.5px solid transparent',
              transition: 'border-color 150ms',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: o.partner.color, color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: T.display, fontSize: 18, lineHeight: 1,
              }}>{o.partner.name[0]}</div>
              <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                <div style={{ fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
                  {o.partner.name}
                  {o.partner.fee < 4 && <Pill bg={T.accentSoft} color={T.accent} size={10}>LOW FEE</Pill>}
                </div>
                <div style={{ fontSize: 11, color: T.inkSoft, marginTop: 2 }}>{o.eta} · contactless</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1 }}>${o.total.toFixed(2)}</div>
                <div style={{ fontSize: 10, color: T.inkSoft, marginTop: 2 }}>+${o.fees.toFixed(2)} fees</div>
              </div>
            </button>
          );
        })}
      </div>

      <div style={{ padding: '20px 18px 0' }}>
        <button onClick={() => { addToast('Order placed! 🎉'); setTimeout(() => go('home'), 800); }} style={{
          background: T.primary, color: '#fff', borderRadius: 16, width: '100%',
          padding: '16px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1 }}>Place order</div>
            <div style={{ fontSize: 12, opacity: 0.9, marginTop: 4 }}>${all.find(o => `${o.kind}-${o.kind === 'pickup' ? o.store.id : o.partner.id}` === selected).total.toFixed(2)}</div>
          </div>
          <IconArrowR size={22} stroke="#fff"/>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Lists
// ─────────────────────────────────────────────────────────
function ListsScreen({ go, setCart, addToast }) {
  const lists = [
    { id: 'staples', name: 'Weekly Staples', count: 7, last: 'Sun', emoji: '🛒', color: T.primarySoft, on: true,
      items: ['carrots','milk','eggs','apples','spinach','bread','pasta'] },
    { id: 'roast',   name: 'Sunday Roast',   count: 4, last: 'Last week', emoji: '🍗', color: T.accentSoft, on: false,
      items: ['carrots','spinach','bread','pasta'] },
    { id: 'lunches', name: 'Kid Lunches',    count: 4, last: 'Mon', emoji: '🥪', color: T.cream, on: true,
      items: ['milk','bread','apples','eggs'] },
    { id: 'pasta',   name: 'Pasta Night',    count: 3, last: '2 weeks', emoji: '🍝', color: '#FBE3E3', on: false,
      items: ['pasta','tomato','spinach'] },
  ];
  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 110 }}>
      <Nav left={<div/>} title="My lists" right={<button><IconPlus size={22} stroke={T.ink}/></button>}/>

      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          background: T.accentSoft, borderRadius: 20, padding: 16,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 48, height: 48, borderRadius: 14, background: T.accent,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <IconRepeat size={24} stroke="#fff"/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: T.display, fontSize: 18, lineHeight: 1.1 }}>Weekly Staples</div>
            <div style={{ fontSize: 12, color: T.ink, opacity: 0.7, marginTop: 3 }}>Reorders Sundays · next Apr 27</div>
          </div>
          <Pill bg={T.accent} color="#fff" size={11}>ON</Pill>
        </div>
      </div>

      <div style={{ padding: '0 18px 8px', fontFamily: T.display, fontSize: 18 }}>All lists</div>
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {lists.map(l => (
          <button key={l.id} onClick={() => {
            setCart(l.items.map(id => ({ productId: id, qty: 1 })));
            addToast(`Added ${l.name} to basket`);
            setTimeout(() => go('cart'), 400);
          }} style={{
            background: T.surface, borderRadius: 18, padding: '12px 14px', width: '100%',
            display: 'flex', alignItems: 'center', gap: 12,
            boxShadow: '0 1px 0 ' + T.hairline,
          }}>
            <div style={{
              width: 48, height: 48, borderRadius: 14, background: l.color,
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
            }}>{l.emoji}</div>
            <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>{l.name}</div>
              <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 2 }}>{l.count} items · last {l.last}</div>
            </div>
            <IconChevR size={20} stroke={T.inkSoft}/>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Me screen (placeholder)
// ─────────────────────────────────────────────────────────
function MeScreen({ go }) {
  return (
    <div className="screen-enter" style={{ background: T.bg, minHeight: '100%', fontFamily: T.body, color: T.ink, paddingBottom: 110 }}>
      <Nav left={<div/>} title="Account" right={<button><IconSettings size={22} stroke={T.ink}/></button>}/>
      <div style={{ padding: '0 18px' }}>
        <div style={{
          background: T.surface, borderRadius: 20, padding: 18,
          display: 'flex', alignItems: 'center', gap: 14,
          boxShadow: '0 1px 0 ' + T.hairline,
        }}>
          <div style={{
            width: 60, height: 60, borderRadius: 999, background: T.primary, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: T.display, fontSize: 28,
          }}>M</div>
          <div>
            <div style={{ fontFamily: T.display, fontSize: 22 }}>Maya R.</div>
            <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 2 }}>Member since Mar 2024</div>
          </div>
        </div>
        <div style={{
          marginTop: 16, padding: 18, borderRadius: 20,
          background: T.primarySoft,
        }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, color: T.primary, fontWeight: 700 }}>SAVED THIS YEAR</div>
          <div style={{ fontFamily: T.display, fontSize: 36, marginTop: 4 }}>$214.80</div>
          <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 6 }}>across 47 baskets compared</div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Root demo component
// ─────────────────────────────────────────────────────────
function FriendlyDemo() {
  // Stack-based navigation
  const [stack, setStack] = useState([{ screen: 'home' }]);
  const top = stack[stack.length - 1];
  const [cart, setCart] = useState(DEFAULT_CART.slice());
  const [mode, setMode] = useState('delivery');
  const [deliveryPartner, setDeliveryPartner] = useState(DELIVERY_PARTNERS[1]);
  const [toast, setToast] = useState(null);
  const toastTimer = useRef(null);

  const addToast = (msg) => {
    setToast(msg);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 1800);
  };

  const go = (target) => {
    if (target === -1) {
      if (stack.length > 1) setStack(stack.slice(0, -1));
      return;
    }
    // Tabs reset stack
    const tabs = ['home','browse','lists','cart','me'];
    if (tabs.includes(target)) {
      setStack([{ screen: target }]);
    } else {
      setStack([...stack, { screen: target }]);
    }
  };
  const openProduct = (id) => setStack([...stack, { screen: 'product', productId: id }]);
  const addToCart = (productId, storeId) => {
    const existing = cart.find(l => l.productId === productId);
    if (existing) {
      setCart(cart.map(l => l.productId === productId ? { ...l, qty: l.qty + 1 } : l));
    } else {
      setCart([...cart, { productId, qty: 1, storeId }]);
    }
  };

  const screen = top.screen;
  const tabActive = ['home','browse','lists','cart','me'].includes(screen) ? screen : (
    screen === 'product' || screen === 'search' ? 'home' :
    screen === 'delivery' ? 'cart' : null
  );

  let body = null;
  if (screen === 'home')      body = <BrowseScreen go={go} openProduct={openProduct} addToast={addToast} cart={cart}/>;
  else if (screen === 'browse')   body = <BrowseScreen go={go} openProduct={openProduct} addToast={addToast} cart={cart}/>;
  else if (screen === 'search')   body = <SearchScreen go={go} openProduct={openProduct}/>;
  else if (screen === 'product')  body = <ProductScreen productId={top.productId} go={go} addToCart={addToCart} cart={cart} addToast={addToast}/>;
  else if (screen === 'cart')     body = <CartScreen cart={cart} setCart={setCart} go={go} addToast={addToast} mode={mode} setMode={setMode} deliveryPartner={deliveryPartner}/>;
  else if (screen === 'delivery') body = <DeliveryScreen cart={cart} go={go} addToast={addToast} mode={mode} setMode={setMode} deliveryPartner={deliveryPartner} setDeliveryPartner={setDeliveryPartner}/>;
  else if (screen === 'lists')    body = <ListsScreen go={go} setCart={setCart} addToast={addToast}/>;
  else if (screen === 'me')       body = <MeScreen go={go}/>;

  return (
    <div className="stage">
      <IOSDevice width={402} height={874}>
        <div style={{ height: '100%', paddingTop: 54, position: 'relative' }} key={screen + (top.productId || '')}>
          {body}
          <Toast msg={toast}/>
          {tabActive && <TabBar active={tabActive} onTab={go}/>}
        </div>
      </IOSDevice>
    </div>
  );
}

Object.assign(window, { FriendlyDemo });
