// QReward Customer — Marketplace, Product, Cart, Wishlist, Checkout, Order status
const { useState: uS4, useEffect: uE4, useMemo: uM4 } = React;

/* ============ MARKETPLACE ============ */
const MarketplaceScreen = ({ lang, onNav, cart, fav, onFav, onAdd, toast }) => {
  const [cat, setCat] = uS4('All');
  const [query, setQuery] = uS4('');
  const [offerIdx, setOfferIdx] = uS4(0);
  uE4(() => { const t = setInterval(() => setOfferIdx(i => (i + 1) % DATA.offers.length), 5000); return () => clearInterval(t); }, []);

  const products = DATA.products.filter(p =>
    (cat === 'All' || p.cat === cat) &&
    (!query || p.name.toLowerCase().includes(query.toLowerCase()) || p.brand.toLowerCase().includes(query.toLowerCase()))
  );
  const cartCount = cart.reduce((a, c) => a + c.qty, 0);

  return (
    <div className="scr scr-pad-status">
      <div className="tbar">
        <div className="tbar-title">{L(lang, 'marketplace')}</div>
        <button className="tbar-action-icon" onClick={() => onNav('push', 'wishlist')}><Icon n="heart" s={21} fill={fav.length ? 'var(--red-500)' : 'none'} c={fav.length ? 'var(--red-500)' : 'currentColor'} /></button>
      </div>
      <div className="search" style={{ marginTop: 0 }}>
        <Icon n="search" s={16} />
        <input value={query} onChange={e => setQuery(e.target.value)} placeholder={lang === 'jp' ? '商品・ブランド・カテゴリを検索' : 'Search products, brands, categories'} />
      </div>
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 100 }}>
        {/* Promo banner carousel */}
        <div style={{ padding: '4px 0 4px' }}>
          <button className={`market-banner-large ${DATA.offers[offerIdx].theme}`} style={{ width: 'auto' }} onClick={() => onNav('push', 'scopedMarket', { offer: DATA.offers[offerIdx] })}>
            <span className="offer-card-tag" style={{ position: 'absolute', top: 14, left: 14 }}>{DATA.offers[offerIdx].tag}</span>
            <h3>{DATA.offers[offerIdx].name}</h3>
            <p>{DATA.offers[offerIdx].scope} · {lang === 'jp' ? 'タップして商品を見る' : 'Tap to shop this offer'}</p>
            <div style={{ position: 'absolute', bottom: 12, right: 14, display: 'flex', gap: 4 }}>
              {DATA.offers.map((_, i) => <span key={i} style={{ width: 5, height: 5, borderRadius: '50%', background: i === offerIdx ? 'white' : 'rgba(255,255,255,0.4)' }}></span>)}
            </div>
          </button>
        </div>
        {/* Category strip */}
        <div className="cat-strip">
          {DATA.categories.map(c => <button key={c} className={`cat-chip ${cat === c ? 'active' : ''}`} onClick={() => setCat(c)}>{c}</button>)}
        </div>
        {/* Product grid */}
        {products.length === 0
          ? <div className="empty-state"><div className="empty-state-icon"><Icon n="search" s={24} /></div><div className="empty-state-title">{lang === 'jp' ? '商品が見つかりません' : 'Nothing matches'}</div><div className="empty-state-body">{lang === 'jp' ? '検索やフィルターを変更してください' : 'Try a different search or category'}</div></div>
          : <div className="prod-grid">
              {products.map(p => <ProductTile key={p.id} p={p} lang={lang} fav={fav.includes(p.id)} onFav={() => onFav(p.id)} onAdd={(qty) => onAdd(p, qty)} onOpen={() => onNav('push', 'product', { product: p })} toast={toast} />)}
            </div>}
      </div>
      {/* Floating cart */}
      <button className="cart-fab" onClick={() => onNav('push', 'cart')}>
        <Icon n="cart" s={22} />
        {cartCount > 0 && <span className="cart-fab-badge">{cartCount}</span>}
      </button>
    </div>
  );
};

const ProductTile = ({ p, lang, fav, onFav, onAdd, onOpen, toast }) => {
  const [qty, setQty] = uS4(1);
  return (
    <div className={`prod-tile ${p.oos ? 'out-of-stock' : ''}`}>
      <div className="prod-img" style={{ background: `linear-gradient(135deg, ${p.img}22, ${p.img}44)` }} onClick={onOpen}>
        <Icon n="gift" s={32} c={p.img} style={{ opacity: 0.5 }} />
        {p.offer && <span className="prod-offer-chip">{p.offer}</span>}
        {p.oos && <div className="prod-unavail">{lang === 'jp' ? '在庫切れ' : 'Unavailable'}</div>}
        {!p.oos && <button className={`prod-heart ${fav ? 'on' : ''}`} onClick={(e) => { e.stopPropagation(); onFav(); }}><Icon n="heart" s={16} fill={fav ? 'currentColor' : 'none'} /></button>}
      </div>
      <div className="prod-body">
        <div className="prod-brand">{p.brand}</div>
        <div className="prod-name" onClick={onOpen}>{lang === 'jp' ? p.nameJp : p.name}</div>
        <div className="prod-price">{fmt(p.price)}<span className="r-glyph" style={{ fontSize: '0.62em' }}>&thinsp;r</span></div>
        {!p.oos && (
          <div className="prod-qty-row">
            <div className="prod-qty">
              <button onClick={() => setQty(Math.max(1, qty - 1))}><Icon n="minus" s={14} /></button>
              <span>{qty}</span>
              <button onClick={() => setQty(qty + 1)}><Icon n="plus" s={14} /></button>
            </div>
            <button className="prod-add" onClick={() => { onAdd(qty); toast(lang === 'jp' ? 'カートに追加しました' : 'Added to cart'); }}>{lang === 'jp' ? '追加' : 'Add'}</button>
          </div>
        )}
      </div>
    </div>
  );
};

/* ============ SCOPED MARKETPLACE (from banner) ============ */
const ScopedMarketScreen = ({ lang, onBack, offer, fav, onFav, onAdd, onNav, toast }) => {
  const products = DATA.products.filter(p => offer.scope === 'Platform-wide' || p.cat === offer.scope || ['p1', 'p5', 'p8'].includes(p.id)).slice(0, 6);
  return (
    <div className="scr scr-pad-status">
      <TopBar title={L(lang, 'marketplace')} onBack={onBack} lang={lang} />
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 30 }}>
        <div style={{ padding: '4px 16px 8px' }}>
          <div className={`market-banner-large ${offer.theme}`} style={{ margin: 0, height: 130 }}>
            <span className="offer-card-tag" style={{ position: 'absolute', top: 14, left: 14 }}>{offer.tag}</span>
            <h3>{offer.name}</h3>
            <p>{offer.scope}</p>
          </div>
        </div>
        <div className="prod-grid">
          {products.map(p => <ProductTile key={p.id} p={{ ...p, offer: offer.tag }} lang={lang} fav={fav.includes(p.id)} onFav={() => onFav(p.id)} onAdd={(qty) => onAdd(p, qty)} onOpen={() => onNav('push', 'product', { product: { ...p, offer: offer.tag } })} toast={toast} />)}
        </div>
      </div>
    </div>
  );
};

/* ============ PRODUCT PAGE ============ */
const ProductScreen = ({ lang, product, onBack, fav, onFav, onAdd, onNav, toast }) => {
  const [qty, setQty] = uS4(1);
  const [imgIdx, setImgIdx] = uS4(0);
  const total = product.price * qty;
  const afford = DATA.balance >= total;
  const imgs = [product.img, '#1f2937', '#475569'];

  return (
    <div className="scr scr-pad-status" style={{ paddingBottom: 0 }}>
      <TopBar onBack={onBack} lang={lang}
        right={<button className="tbar-action-icon" onClick={onFav}><Icon n="heart" s={21} fill={fav ? 'var(--red-500)' : 'none'} c={fav ? 'var(--red-500)' : 'currentColor'} /></button>} />
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 110 }}>
        {/* Image gallery */}
        <div style={{ position: 'relative', height: 260, background: `linear-gradient(135deg, ${imgs[imgIdx]}22, ${imgs[imgIdx]}44)`, display: 'grid', placeItems: 'center' }}>
          <Icon n="gift" s={64} c={imgs[imgIdx]} style={{ opacity: 0.4 }} />
          {product.offer && <span className="prod-offer-chip" style={{ top: 16, left: 16, fontSize: 12, padding: '5px 10px' }}>{product.offer}</span>}
          <button className="gallery-chev" style={{ left: 12 }} onClick={() => setImgIdx((imgIdx - 1 + imgs.length) % imgs.length)}><Icon n="chevL" s={20} /></button>
          <button className="gallery-chev" style={{ right: 12 }} onClick={() => setImgIdx((imgIdx + 1) % imgs.length)}><Icon n="chevR" s={20} /></button>
          <div style={{ position: 'absolute', bottom: 14, display: 'flex', gap: 5 }}>
            {imgs.map((_, i) => <span key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: i === imgIdx ? 'var(--brand-600)' : 'var(--ink-200)' }}></span>)}
          </div>
        </div>
        <div style={{ padding: '16px 20px 0' }}>
          <div className="prod-brand" style={{ fontSize: 12 }}>{product.brand}</div>
          <div className="h2" style={{ marginTop: 4 }}>{lang === 'jp' ? product.nameJp : product.name}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 12 }}>
            <div className="balance-big" style={{ fontSize: 32 }}>{fmt(product.price)}<span className="r-glyph" style={{ fontSize: '0.6em' }}>r</span></div>
          </div>
          {/* Balance line */}
          <div style={{ marginTop: 8, fontSize: 14 }} className={afford ? '' : ''}>
            <span className="muted">{lang === 'jp' ? '残高' : 'Your balance'}: </span>
            <span style={{ fontWeight: 700, color: afford ? 'var(--green-600)' : 'var(--red-600)', fontFeatureSettings: '"tnum"' }}>{fmt(DATA.balance)} r</span>
            {!afford && <span style={{ color: 'var(--red-600)', marginLeft: 8 }}>· {lang === 'jp' ? '残高不足' : 'Insufficient balance'}</span>}
          </div>

          {/* Quantity */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 18 }}>
            <div style={{ fontWeight: 600 }}>{lang === 'jp' ? '数量' : 'Quantity'}</div>
            <div className="prod-qty" style={{ height: 40 }}>
              <button style={{ width: 40, height: 38 }} onClick={() => setQty(Math.max(1, qty - 1))}><Icon n="minus" s={16} /></button>
              <span style={{ width: 32, fontSize: 16 }}>{qty}</span>
              <button style={{ width: 40, height: 38 }} onClick={() => setQty(qty + 1)}><Icon n="plus" s={16} /></button>
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, paddingTop: 12, borderTop: '0.5px solid var(--border)', fontSize: 15 }}>
            <span className="muted">{lang === 'jp' ? '合計' : 'Total cost'}</span>
            <span style={{ fontWeight: 700, fontFeatureSettings: '"tnum"' }}>{fmt(total)} r</span>
          </div>

          {/* Description */}
          <div className="section-title" style={{ margin: '20px 0 8px', padding: 0 }}>{lang === 'jp' ? '商品説明' : 'Description'}</div>
          <div className="muted" style={{ fontSize: 14, lineHeight: 1.6 }}>
            {lang === 'jp' ? '上質なギフトをポイントで。提携ブランドの公式商品をお届けします。デジタルコードは即時発行、配送商品は3〜5営業日でお届けします。' : 'A premium reward redeemable with your points. Official partner product with instant digital codes or 3–5 day shipping for physical items.'}
          </div>
          <div className="section-title" style={{ margin: '18px 0 8px', padding: 0 }}>{lang === 'jp' ? '主な仕様' : 'Key specifications'}</div>
          <ul className="muted" style={{ fontSize: 14, lineHeight: 1.7, paddingLeft: 18, margin: 0 }}>
            <li>{lang === 'jp' ? '公式正規品' : 'Official authentic product'}</li>
            <li>{lang === 'jp' ? 'ポイント交換専用' : 'Points redemption only'}</li>
            <li>{lang === 'jp' ? '有効期限：発行から12ヶ月' : 'Valid 12 months from issue'}</li>
          </ul>
        </div>
      </div>
      {/* Pinned CTA */}
      <div className="cta-pinned">
        {!afford && <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--red-600)', marginBottom: 8 }}>{lang === 'jp' ? `あと ${fmt(total - DATA.balance)} r 必要です` : `You'll need ${fmt(total - DATA.balance)} r more`}</div>}
        <Btn block disabled={!afford || product.oos} onClick={() => onNav('push', 'checkout', { items: [{ ...product, qty }], direct: true })}>
          {product.oos ? (lang === 'jp' ? '在庫切れ' : 'Unavailable') : L(lang, 'redeemNow')}
        </Btn>
      </div>
      <style>{`.gallery-chev { position: absolute; top: 50%; transform: translateY(-50%); width: 36px; height: 36px; border-radius: 50%; background: rgba(255,255,255,0.85); backdrop-filter: blur(6px); display: grid; place-items: center; color: var(--ink-700); box-shadow: 0 2px 8px rgba(0,0,0,0.1); }`}</style>
    </div>
  );
};

/* ============ CART ============ */
const CartScreen = ({ lang, onBack, cart, setCart, onNav, toast }) => {
  const total = cart.reduce((a, c) => a + c.price * c.qty, 0);
  const afford = DATA.balance >= total;
  const setQty = (id, q) => setCart(cart.map(c => c.id === id ? { ...c, qty: Math.max(1, q) } : c));
  const remove = (id) => { setCart(cart.filter(c => c.id !== id)); toast(lang === 'jp' ? '削除しました' : 'Removed from cart'); };

  return (
    <div className="scr scr-pad-status" style={{ paddingBottom: 0 }}>
      <TopBar title={lang === 'jp' ? 'カート' : 'Cart'} onBack={onBack} lang={lang} />
      {cart.length === 0
        ? <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div className="empty-state">
              <div className="empty-state-icon"><Icon n="cart" s={26} /></div>
              <div className="empty-state-title">{lang === 'jp' ? 'カートは空です' : 'Your cart is empty'}</div>
              <div className="empty-state-body">{lang === 'jp' ? 'マーケットプレイスで商品を探しましょう' : 'Browse the marketplace to find something'}</div>
              <div style={{ marginTop: 18 }}><Btn onClick={onBack}>{lang === 'jp' ? 'マーケットを見る' : 'Browse marketplace'}</Btn></div>
            </div>
          </div>
        : <>
          <div style={{ flex: 1, overflowY: 'auto', paddingTop: 8, paddingBottom: 140 }}>
            {cart.map(c => (
              <div key={c.id} className="cart-row">
                <div className="cart-row-thumb" style={{ background: `linear-gradient(135deg, ${c.img}22, ${c.img}44)` }}><Icon n="gift" s={24} c={c.img} style={{ opacity: 0.5 }} /></div>
                <div className="cart-row-body">
                  <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.3 }}>{lang === 'jp' ? c.nameJp : c.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{c.brand}</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto' }}>
                    <div className="prod-qty">
                      <button onClick={() => setQty(c.id, c.qty - 1)}><Icon n="minus" s={14} /></button>
                      <span>{c.qty}</span>
                      <button onClick={() => setQty(c.id, c.qty + 1)}><Icon n="plus" s={14} /></button>
                    </div>
                    <div style={{ fontWeight: 700, fontFeatureSettings: '"tnum"' }}>{fmt(c.price * c.qty)} r</div>
                  </div>
                </div>
                <button onClick={() => remove(c.id)} style={{ color: 'var(--ink-300)', alignSelf: 'flex-start' }}><Icon n="trash" s={16} /></button>
              </div>
            ))}
          </div>
          <div className="cta-pinned">
            <div className="summary" style={{ margin: '0 0 12px', padding: 14 }}>
              <div className="summary-row"><span className="label">{lang === 'jp' ? '合計ポイント' : 'Total points'}</span><span className="val">{fmt(total)} r</span></div>
              <div className="summary-row"><span className="label">{lang === 'jp' ? '現在の残高' : 'Balance now'}</span><span className="val">{fmt(DATA.balance)} r</span></div>
              <div className="summary-row hero"><span className="label" style={{ fontWeight: 600 }}>{lang === 'jp' ? '交換後の残高' : 'Balance after'}</span><span className="summary-after" style={{ color: afford ? 'var(--brand-600)' : 'var(--red-600)' }}>{fmt(DATA.balance - total)} r</span></div>
            </div>
            {!afford && <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--red-600)', marginBottom: 8 }}>{lang === 'jp' ? '残高が不足しています。商品を減らしてください。' : 'Total exceeds balance — remove some items.'}</div>}
            <Btn block disabled={!afford} onClick={() => onNav('push', 'checkout', { items: cart })}>{L(lang, 'continue')}</Btn>
          </div>
        </>}
    </div>
  );
};

/* ============ WISHLIST ============ */
const WishlistScreen = ({ lang, onBack, fav, onFav, onAdd, onNav, toast }) => {
  const items = DATA.products.filter(p => fav.includes(p.id));
  const [selectMode, setSelect] = uS4(false);
  const [selected, setSelected] = uS4([]);
  return (
    <div className="scr scr-pad-status" style={{ paddingBottom: 0 }}>
      <TopBar title={lang === 'jp' ? 'ウィッシュリスト' : 'Wishlist'} onBack={onBack} lang={lang}
        right={items.length > 0 && <button className="tbar-action" onClick={() => { setSelect(!selectMode); setSelected([]); }}>{selectMode ? (lang === 'jp' ? 'キャンセル' : 'Cancel') : (lang === 'jp' ? '選択' : 'Select')}</button>} />
      {items.length === 0
        ? <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div className="empty-state">
              <div className="empty-state-icon"><Icon n="heart" s={26} /></div>
              <div className="empty-state-title">{lang === 'jp' ? 'まだ何もありません' : 'Nothing here yet'}</div>
              <div className="empty-state-body">{lang === 'jp' ? '気になる商品にハートをタップして保存しましょう' : 'Tap the heart on a product to save it'}</div>
            </div>
          </div>
        : <>
          <div style={{ flex: 1, overflowY: 'auto', paddingTop: 8, paddingBottom: selectMode ? 100 : 30 }}>
            <div className="prod-grid">
              {items.map(p => (
                <div key={p.id} style={{ position: 'relative' }}>
                  {selectMode && <button className="wish-check" onClick={() => setSelected(s => s.includes(p.id) ? s.filter(x => x !== p.id) : [...s, p.id])}>
                    <span className={`checkbox ${selected.includes(p.id) ? 'checked' : ''}`} style={{ width: 24, height: 24, background: selected.includes(p.id) ? 'var(--brand-600)' : 'rgba(255,255,255,0.95)' }}></span>
                  </button>}
                  <ProductTile p={p} lang={lang} fav={true} onFav={() => onFav(p.id)} onAdd={(qty) => onAdd(p, qty)} onOpen={() => !selectMode && onNav('push', 'product', { product: p })} toast={toast} />
                </div>
              ))}
            </div>
          </div>
          {selectMode && <div className="cta-pinned" style={{ display: 'flex', gap: 10 }}>
            <Btn variant="secondary" style={{ flex: 1 }} disabled={!selected.length} onClick={() => { selected.forEach(id => onFav(id)); toast(lang === 'jp' ? '削除しました' : 'Removed'); setSelect(false); setSelected([]); }}>{lang === 'jp' ? '削除' : 'Remove'}</Btn>
            <Btn style={{ flex: 1 }} disabled={!selected.length} onClick={() => { const its = items.filter(p => selected.includes(p.id)).map(p => ({ ...p, qty: 1 })); onNav('push', 'checkout', { items: its }); }}>{lang === 'jp' ? `${selected.length}件を交換` : `Redeem ${selected.length}`}</Btn>
          </div>}
        </>}
      <style>{`.wish-check { position: absolute; top: 8px; left: 8px; z-index: 3; }`}</style>
    </div>
  );
};

/* ============ CHECKOUT (3-step) ============ */
const CheckoutScreen = ({ lang, onBack, items, onComplete, toast }) => {
  const [step, setStep] = uS4(1);
  const [addresses, setAddresses] = uS4(DATA.addresses);
  const [note, setNote] = uS4('');
  const [adding, setAdding] = uS4(false);
  const total = items.reduce((a, c) => a + c.price * c.qty, 0);
  const selectedAddr = addresses.find(a => a.selected);

  return (
    <div className="scr scr-pad-status" style={{ paddingBottom: 0 }}>
      <TopBar title={step === 1 ? (lang === 'jp' ? '注文確認' : 'Review your order') : step === 2 ? (lang === 'jp' ? 'お届け先' : 'Delivery address') : (lang === 'jp' ? '交換の確認' : 'Confirm redemption')}
        onBack={() => step === 1 ? onBack() : setStep(step - 1)} lang={lang} />
      <div className="checkout-steps">
        {[1, 2, 3].map(s => <div key={s} className={`checkout-step ${s <= step ? 'active' : ''}`}></div>)}
      </div>
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 120 }}>
        {step === 1 && (
          <div style={{ padding: '12px 16px' }}>
            {items.map(c => (
              <div key={c.id} className="cart-row" style={{ margin: '0 0 10px' }}>
                <div className="cart-row-thumb" style={{ background: `linear-gradient(135deg, ${c.img}22, ${c.img}44)` }}><Icon n="gift" s={24} c={c.img} style={{ opacity: 0.5 }} /></div>
                <div className="cart-row-body" style={{ justifyContent: 'center' }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{lang === 'jp' ? c.nameJp : c.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{lang === 'jp' ? '数量' : 'Qty'} {c.qty}</div>
                </div>
                <div style={{ fontWeight: 700, alignSelf: 'center', fontFeatureSettings: '"tnum"' }}>{fmt(c.price * c.qty)} r</div>
              </div>
            ))}
            <div className="summary" style={{ margin: '8px 0 0' }}>
              <div className="summary-row"><span className="label">{lang === 'jp' ? '現在の残高' : 'Balance now'}</span><span className="val">{fmt(DATA.balance)} r</span></div>
              <div className="summary-row"><span className="label">{lang === 'jp' ? '交換ポイント' : 'Redemption'}</span><span className="val red">−{fmt(total)} r</span></div>
              <div className="summary-row hero"><span className="label" style={{ fontWeight: 600 }}>{lang === 'jp' ? '交換後の残高' : 'Balance after'}</span><span className="summary-after">{fmt(DATA.balance - total)} r</span></div>
            </div>
          </div>
        )}
        {step === 2 && (
          <div style={{ paddingTop: 8 }}>
            {addresses.map(a => (
              <button key={a.id} className={`addr-tile ${a.selected ? 'selected' : ''}`} style={{ width: 'auto', textAlign: 'left' }} onClick={() => setAddresses(addresses.map(x => ({ ...x, selected: x.id === a.id })))}>
                <span className="addr-tile-radio"></span>
                <div className="addr-tile-body">
                  <div className="addr-tile-name">{a.name}</div>
                  <div className="addr-tile-text">{a.zip} {a.line} · {a.extra}</div>
                  <div className="addr-tile-text">{a.phone}</div>
                </div>
                <div className="addr-tile-actions">
                  <button onClick={(e) => e.stopPropagation()}><Icon n="edit" s={16} /></button>
                </div>
              </button>
            ))}
            {addresses.length < 3 && <button className="add-addr" onClick={() => { toast(lang === 'jp' ? '住所フォームを開きます' : 'Add address form'); }}>
              <Icon n="plus" s={18} /> {lang === 'jp' ? '新しい住所を追加' : 'Add a new address'}
            </button>}
            <div className="field" style={{ marginTop: 14 }}>
              <label className="field-label">{lang === 'jp' ? '配送メモ（任意）' : 'Delivery note (optional)'}</label>
              <textarea className="input" style={{ height: 70, padding: 12, resize: 'none' }} value={note} onChange={e => setNote(e.target.value)} placeholder={lang === 'jp' ? '配達員へのメモ' : 'Note for the courier'}></textarea>
            </div>
          </div>
        )}
        {step === 3 && (
          <div style={{ padding: '12px 16px' }}>
            <div className="section-title" style={{ padding: '0 0 8px' }}>{lang === 'jp' ? '商品' : 'Items'}</div>
            {items.map(c => (
              <div key={c.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 14, borderBottom: '0.5px solid var(--border)' }}>
                <span>{lang === 'jp' ? c.nameJp : c.name} <span className="muted">×{c.qty}</span></span>
                <span style={{ fontWeight: 600 }}>{fmt(c.price * c.qty)} r</span>
              </div>
            ))}
            <div className="section-title" style={{ padding: '14px 0 8px' }}>{lang === 'jp' ? 'お届け先' : 'Delivery to'}</div>
            <div className="muted" style={{ fontSize: 14, lineHeight: 1.5 }}>{selectedAddr?.name} · {selectedAddr?.zip} {selectedAddr?.line}</div>
            {note && <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>{lang === 'jp' ? 'メモ' : 'Note'}: {note}</div>}
            <div className="summary" style={{ margin: '16px 0 0' }}>
              <div className="summary-row"><span className="label">{lang === 'jp' ? '現在の残高' : 'Balance now'}</span><span className="val">{fmt(DATA.balance)} r</span></div>
              <div className="summary-row"><span className="label">{lang === 'jp' ? '交換ポイント' : 'Redemption'}</span><span className="val red">−{fmt(total)} r</span></div>
              <div className="summary-row hero"><span className="label" style={{ fontWeight: 600 }}>{lang === 'jp' ? '交換後の残高' : 'Balance after'}</span><span className="summary-after">{fmt(DATA.balance - total)} r</span></div>
            </div>
            <div className="banner" style={{ marginLeft: 0, marginRight: 0 }}>
              <Icon n="lock" s={18} />
              <div>{lang === 'jp' ? '確定時に生体認証またはPINで確認します。' : 'Your biometric or PIN confirms this redemption.'}</div>
            </div>
          </div>
        )}
      </div>
      <div className="cta-pinned">
        <Btn block disabled={step === 2 && !selectedAddr} onClick={() => step < 3 ? setStep(step + 1) : onComplete({ items, total, addr: selectedAddr })}>
          {step < 3 ? L(lang, 'continue') : (lang === 'jp' ? '交換を確定' : 'Confirm redemption')}
        </Btn>
      </div>
      <style>{`
        .checkout-steps { display: flex; gap: 6px; padding: 8px 20px 4px; }
        .checkout-step { flex: 1; height: 4px; border-radius: 999px; background: var(--ink-100); transition: background 250ms; }
        .checkout-step.active { background: var(--brand-600); }
        .add-addr { display: flex; align-items: center; justify-content: center; gap: 8px; width: calc(100% - 32px); margin: 0 16px; padding: 14px; border: 1.5px dashed var(--border-strong); border-radius: var(--radius-md); color: var(--brand-600); font-weight: 600; font-size: 14px; }
      `}</style>
    </div>
  );
};

/* ============ ORDER CONFIRMED ============ */
const OrderConfirmedScreen = ({ lang, order, onViewStatus, onBackToMarket }) => (
  <div className="scr scr-pad-status" style={{ justifyContent: 'center', position: 'relative', overflow: 'hidden' }}>
    <Confetti />
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', padding: '0 32px' }}>
      <div style={{ width: 80, height: 80, borderRadius: '50%', background: 'var(--green-50)', display: 'grid', placeItems: 'center', marginBottom: 22, animation: 'pop 600ms cubic-bezier(0.2,0.8,0.2,1)' }}>
        <Icon n="check" s={40} c="var(--green-600)" sw={2.6} />
      </div>
      <div className="h2">{lang === 'jp' ? '交換が完了しました' : 'Order confirmed'}</div>
      <div className="muted" style={{ fontSize: 15, marginTop: 10 }}>{lang === 'jp' ? 'ご注文ありがとうございます。' : 'Thank you for your redemption.'}</div>
      <div className="surface" style={{ marginTop: 24, padding: 18, width: '100%', textAlign: 'left' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14 }}><span className="muted">{lang === 'jp' ? '注文ID' : 'Order ID'}</span><span className="mono" style={{ fontWeight: 600 }}>QR-90142</span></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14 }}><span className="muted">{lang === 'jp' ? '使用ポイント' : 'Points spent'}</span><span style={{ fontWeight: 600 }}>{fmt(order.total)} r</span></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14 }}><span className="muted">{lang === 'jp' ? '新しい残高' : 'New balance'}</span><span style={{ fontWeight: 700, color: 'var(--brand-600)' }}>{fmt(DATA.balance - order.total)} r</span></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14 }}><span className="muted">{lang === 'jp' ? 'お届け予定' : 'Est. delivery'}</span><span style={{ fontWeight: 600 }}>2026/06/12</span></div>
      </div>
    </div>
    <div style={{ padding: '12px 20px 28px', display: 'flex', flexDirection: 'column', gap: 10 }}>
      <Btn block onClick={onViewStatus}>{lang === 'jp' ? '注文状況を見る' : 'View order status'}</Btn>
      <Btn block variant="ghost" onClick={onBackToMarket}>{lang === 'jp' ? 'マーケットに戻る' : 'Back to marketplace'}</Btn>
    </div>
    <style>{`@keyframes pop { from { transform: scale(0.4); opacity: 0; } to { transform: scale(1); opacity: 1; } }`}</style>
  </div>
);

/* ============ ORDER STATUS ============ */
const OrderStatusScreen = ({ lang, onBack, order, stage = 2 }) => {
  const steps = lang === 'jp' ? ['処理中', '発送済み', '配達中', '配達完了'] : DATA.orderSteps;
  const times = ['2026/06/08 14:22', '2026/06/09 09:10', '2026/06/12 08:30', ''];
  return (
    <div className="scr scr-pad-status">
      <TopBar title={lang === 'jp' ? '注文状況' : 'Order status'} onBack={onBack} lang={lang} />
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 30 }}>
        <div style={{ padding: '8px 20px 16px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div className="mono" style={{ fontWeight: 700, fontSize: 16 }}>QR-90142</div>
              <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>{lang === 'jp' ? '注文日' : 'Ordered'} 2026/06/08 · {fmt(order?.total || 500)} r</div>
            </div>
            <StatusPill kind="ofd" label={steps[stage]} icon="truck" />
          </div>
        </div>
        <div className="surface" style={{ margin: '0 16px', padding: '18px 4px' }}>
          {steps.map((s, i) => (
            <div key={i} className={`step ${i < stage ? 'done' : i === stage ? 'active' : ''}`}>
              <div className={`step-dot ${i < stage ? 'done' : i === stage ? 'active' : ''}`}>{i < stage ? <Icon n="check" s={12} sw={3} /> : i === stage ? <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff' }}></span> : null}</div>
              <div className="step-body">
                <div className="step-title" style={{ fontWeight: i === stage ? 700 : 500 }}>{s}</div>
                {times[i] && i <= stage && <div className="step-time">{times[i]}</div>}
              </div>
            </div>
          ))}
        </div>
        <div className="section-title">{lang === 'jp' ? '商品' : 'Item'}</div>
        <div className="list" style={{ margin: '0 16px' }}>
          <div className="list-row">
            <div className="cart-row-thumb" style={{ width: 44, height: 44, background: 'linear-gradient(135deg,#1a7a5e22,#1a7a5e44)' }}><Icon n="gift" s={20} c="#1a7a5e" style={{ opacity: 0.6 }} /></div>
            <div className="list-row-body"><div className="list-row-title">Starbucks e-Gift ¥500</div><div className="list-row-sub">{lang === 'jp' ? 'お届け先' : 'To'}: Kita-Aoyama 3-6-7</div></div>
          </div>
        </div>
        <div style={{ padding: '20px 16px' }}>
          <Btn block variant="secondary" icon="phone">{lang === 'jp' ? 'サポートに連絡' : 'Contact support'}</Btn>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { MarketplaceScreen, ScopedMarketScreen, ProductScreen, CartScreen, WishlistScreen, CheckoutScreen, OrderConfirmedScreen, OrderStatusScreen });
