/* global React */
// Screens part 2 — Cart, Checkout, Pay Result, Orders, Profile

// ============================================================
// 05 CART
// ============================================================
function CartScreen({ onCheckout, onCur }) {
  const { lang } = React.useContext(window.LangContext);
  const { items: cartRaw, store } = window.useCart();
  // 首次空购物车自动塞 3 件 demo (覆盖 3 档口)
  React.useEffect(() => { window.ensureDemoCart && window.ensureDemoCart(); }, []);
  const items = (cartRaw || []).map((ci, idx) => {
    const srcP = (window.PRODUCTS || []).find(pp => pp.id === ci.productId);
    if (!srcP) return null;
    return {
      productId: srcP.id,
      n: window.pickI18n(srcP.nameI18n, lang),
      m: srcP.stall.merchant,
      building: srcP.stall.buildingname,
      layer: srcP.stall.layername,
      stallNo: srcP.stall.stallNo,
      spec: ['奶杏 / M', '米白 / S', '烟灰 / 27'][idx] || '默认',
      p: srcP.priceCny,
      q: ci.qty,
      idx: srcP.img,
      dk: srcP.tags?.includes('DK'),
      sel: true,
    };
  }).filter(Boolean);
  const total = items.filter(i => i.sel).reduce((s, i) => s + i.p * i.q, 0);
  return (
    <div className="appbody" style={{ background: '#FAFAFA', paddingBottom: 80, position: 'relative' }}>
      <div className="app-header">
        <span style={{ width: 28 }} />
        <div className="h-title" style={{ paddingRight: 0 }}>购物车 <span style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, marginLeft: 4 }}>({items.length})</span></div>
        <CurPill onClick={onCur} />
      </div>

      {/* merchant grouping - 按真实档口动态分组 (每个 merchant 一组) */}
      {items.map((it, i) => {
        // 单 merchant 一组 (因为 mock 里 3 件都来自不同档口)
        const groupAnySel = it.sel;
        return (
          <div key={i} style={{ margin: '8px 14px', background: '#fff', borderRadius: 12, overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderBottom: '0.5px solid var(--border-1)' }}>
              <span style={{ width: 16, height: 16, borderRadius: '50%', border: '1.5px solid ' + (groupAnySel ? 'var(--brand)' : 'var(--n-300)'), background: groupAnySel ? 'var(--brand)' : '#fff', display: 'grid', placeItems: 'center' }}>
                {groupAnySel && <Icon name="check" size={10} stroke="#fff" sw={3} />}
              </span>
              <Sinsagom size={20} />
              <span style={{ fontSize: 12, fontWeight: 600 }}>{it.m}</span>
              <span style={{ fontSize: 9, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>· {it.building} {it.layer}-{it.stallNo}</span>
              {it.p >= 300 && <span className="chip" style={{ fontSize: 9, marginLeft: 'auto' }}>满 599 减 50</span>}
            </div>
            <div style={{ display: 'flex', gap: 10, padding: '12px 12px' }}>
              <span style={{ width: 16, height: 16, borderRadius: '50%', border: '1.5px solid ' + (it.sel ? 'var(--brand)' : 'var(--n-300)'), background: it.sel ? 'var(--brand)' : '#fff', display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 26 }}>
                {it.sel && <Icon name="check" size={10} stroke="#fff" sw={3} />}
              </span>
              <div style={{ width: 72, height: 72, borderRadius: 6, background: `url(assets/p${it.idx}.jpg) center/cover`, flexShrink: 0, position: 'relative' }}>
                {it.dk && <span className="chip dk" style={{ position: 'absolute', bottom: 3, right: 3, fontSize: 7, padding: '1px 3px' }}>DK</span>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 500, lineHeight: 1.35, height: 32, overflow: 'hidden' }}>{it.n}</div>
                <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2, background: '#F5F5F5', display: 'inline-flex', padding: '2px 6px', borderRadius: 3 }}>{it.spec}<Icon name="chevd" size={10} stroke="var(--fg-3)" sw={2} /></div>
                <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <PriceBlock cny={it.p} size={14} />
                  <div style={{ display: 'flex', alignItems: 'center', border: '0.5px solid var(--border-2)', borderRadius: 4 }}>
                    <button onClick={() => store.setQty(it.productId, it.q - 1)} style={{ width: 22, height: 22, display: 'grid', placeItems: 'center', background: 'none', border: 'none', cursor: 'pointer' }}><Icon name="minus" size={12} sw={2} stroke="var(--fg-2)" /></button>
                    <span style={{ width: 24, fontSize: 11, textAlign: 'center', fontWeight: 600 }}>{it.q}</span>
                    <button onClick={() => store.setQty(it.productId, it.q + 1)} style={{ width: 22, height: 22, display: 'grid', placeItems: 'center', background: '#F5F5F5', border: 'none', cursor: 'pointer' }}><Icon name="plus" size={12} sw={2} /></button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        );
      })}

      {/* recommend */}
      <div style={{ padding: '14px 14px 4px', fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'baseline', gap: 4 }}>看了又看 <span style={{ fontSize: 9, color: 'var(--fg-3)', fontWeight: 500 }}>YOU MAY LIKE</span></div>
      <div style={{ display: 'flex', gap: 8, padding: '0 14px 12px', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {[2, 7, 11, 5].map((i, k) => (
          <div key={k} style={{ flexShrink: 0, width: 96 }}>
            <div style={{ aspectRatio: 1, borderRadius: 6, background: `url(assets/p${i}.jpg) center/cover` }} />
            <PriceBlock cny={[298, 458, 188, 358][k]} size={12} />
          </div>
        ))}
      </div>

      {/* sticky checkout */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 60, background: '#fff', borderTop: '0.5px solid var(--border-1)', display: 'flex', alignItems: 'center', padding: '0 14px', gap: 12 }}>
        <span style={{ width: 16, height: 16, borderRadius: '50%', border: '1.5px solid var(--brand)', background: 'var(--brand)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          <Icon name="check" size={10} stroke="#fff" sw={3} />
        </span>
        <span style={{ fontSize: 11 }}>全选</span>
        <div style={{ flex: 1, textAlign: 'right' }}>
          <div style={{ fontSize: 9, color: 'var(--fg-3)' }}>合计(2 件)</div>
          <PriceBlock cny={total} size={18} />
        </div>
        <button className="btn primary" style={{ padding: '11px 20px', fontSize: 13, fontWeight: 700 }} onClick={onCheckout}>结算 (2)</button>
      </div>
    </div>
  );
}

// ============================================================
// 06 CHECKOUT — fx lock highlight
// ============================================================
function CheckoutScreen({ onPay, onCur }) {
  const { lang } = React.useContext(window.LangContext);
  const { code } = React.useContext(window.CurContext);
  const { items: cartItemsRaw } = window.useCart();
  const { user, isAuthed } = window.useAuth();
  const [submitting, setSubmitting] = React.useState(false);
  const [submitErr, setSubmitErr] = React.useState('');
  // 解析购物车里的真实商品(从 PRODUCTS 取详情)
  const checkoutItems = (cartItemsRaw || []).map(ci => {
    const p = (window.PRODUCTS || []).find(pp => pp.id === ci.productId);
    if (!p) return null;
    return {
      productId: p.id,
      code: p.code,
      n: window.pickI18n(p.nameI18n, lang),
      spec: '默认 × ' + ci.qty,
      qty: ci.qty,
      p: p.priceCny,
      priceKrw: p.priceKrw,
      img: p.img,
      stall: p.stall,
      nameI18n: p.nameI18n,
    };
  }).filter(Boolean);
  // 按档口分组
  const groupsMap = {};
  for (const it of checkoutItems) {
    const k = it.stall.merchant;
    (groupsMap[k] || (groupsMap[k] = { merchant: it.stall, items: [] })).items.push(it);
  }
  const groups = Object.values(groupsMap);
  const subtotal = checkoutItems.reduce((s, it) => s + it.p * it.qty, 0);
  const couponDiscount = subtotal >= 599 ? 50 : 0;
  const pointDiscount = 12.60;
  const finalTotal = Math.max(0, subtotal - couponDiscount - pointDiscount);
  const cur = window.CURRENCIES[code];

  async function submitOrder() {
    setSubmitErr('');
    if (!isAuthed || user?.isGuest) {
      setSubmitErr('请先登录');
      setTimeout(() => { window.location.hash = '#/login'; }, 600);
      return;
    }
    if (checkoutItems.length === 0) { setSubmitErr('购物车为空'); return; }
    setSubmitting(true);
    try {
      const res = await window.auth.fetch('/h5-orders', {
        method: 'POST',
        body: JSON.stringify({
          items: checkoutItems.map(it => ({
            productId: it.productId, code: it.code, name: it.n, spec: it.spec,
            qty: it.qty, priceCny: it.p, priceKrw: it.priceKrw, img: it.img, stall: it.stall,
          })),
          shipping: {
            name: '李小姐', phone: '13800008866',
            address1: '上海市 浦东新区 张江高科技园区',
            address2: '亮景路 168 弄 8 号 1402 室',
            city: '上海', country: 'CN', postalCode: '201210', isDefault: true,
          },
          fxLock: { currency: code, rate: cur.rate },
          shippingFeeCny: 0,
          couponDiscountCny: couponDiscount,
          pointsDiscountCny: pointDiscount,
          note: '', lang,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) throw new Error(data.error || '下单失败');
      // 下单成功 → 清空购物车 → 跳支付结果页带 orderId
      window.cartStore.clear();
      window.location.hash = '#/pay?orderId=' + data.order.id;
    } catch (e) {
      setSubmitErr(e.message || '下单失败');
    } finally { setSubmitting(false); }
  }
  return (
    <div className="appbody" style={{ background: '#F2F2F2', paddingBottom: 70, position: 'relative' }}>
      <div className="app-header">
        <Icon name="back" size={18} sw={2} />
        <div className="h-title">订单确认</div>
      </div>

      {/* address */}
      <div style={{ margin: '8px 14px 8px', background: '#fff', borderRadius: 10, padding: '14px', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: 'repeating-linear-gradient(90deg, var(--brand) 0 8px, transparent 8px 14px, var(--apm-ink) 14px 22px, transparent 22px 28px)' }} />
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, paddingTop: 4 }}>
          <Icon name="pin" size={18} stroke="var(--brand)" sw={1.8} />
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>李小姐</span>
              <span style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>138 **** 8866</span>
              <span className="chip" style={{ fontSize: 8, padding: '1px 5px' }}>默认</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 4, lineHeight: 1.5 }}>上海市 浦东新区 张江高科技园区<br />亮景路 168 弄 8 号 1402 室</div>
          </div>
          <Icon name="chev" size={14} stroke="var(--fg-3)" />
        </div>
      </div>

      {/* fx lock card */}
      <div style={{ margin: '8px 14px', background: '#0B0B0B', color: '#fff', borderRadius: 10, padding: 14, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -30, top: -30, width: 120, height: 120, borderRadius: '50%', background: 'radial-gradient(circle, rgba(201,163,106,0.4), transparent 70%)' }} />
        <div style={{ position: 'relative' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="globe" size={14} stroke="var(--apm-gold)" sw={1.8} />
            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--apm-gold)', letterSpacing: '0.06em' }}>FX LOCK · 汇率锁定</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8 }}>
            <CurPill onClick={onCur} dark={true} />
            <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.6)', fontFamily: 'var(--font-mono)' }}>1 CNY = 188.412 KRW</span>
          </div>
          <div style={{ marginTop: 8, fontSize: 10, color: 'rgba(255,255,255,0.55)', lineHeight: 1.5 }}>提交订单瞬间锁定汇率,订单详情永久保留<br />支付前若汇率波动 &gt;2% 将弹窗确认</div>
        </div>
      </div>

      {/* items - 按真实档口分组 */}
      {groups.map((g, gi) => (
        <div key={gi} style={{ margin: '8px 14px', background: '#fff', borderRadius: 10, overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 14px', fontSize: 12, fontWeight: 600, borderBottom: '0.5px solid var(--border-1)' }}>
            <Sinsagom size={18} />
            {g.merchant.merchant}
            <span style={{ fontSize: 9, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>· {g.merchant.buildingname} {g.merchant.layername}-{g.merchant.stallNo}</span>
            <span style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--fg-3)' }}>共 {g.items.length} 件</span>
          </div>
          {g.items.map((it, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, padding: '10px 14px', borderTop: i > 0 ? '0.5px solid var(--border-1)' : 'none' }}>
              <div style={{ width: 56, height: 56, borderRadius: 4, background: `url(assets/p${it.idx}.jpg) center/cover`, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{it.n}</div>
                <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{it.spec}</div>
                <PriceBlock cny={it.p} size={13} />
              </div>
            </div>
          ))}
          <div style={{ padding: '10px 14px', borderTop: '0.5px solid var(--border-1)', display: 'flex', justifyContent: 'space-between', fontSize: 11, alignItems: 'center' }}>
            <span style={{ color: 'var(--fg-3)' }}>配送方式</span>
            <span style={{ fontWeight: 600 }}>{g.merchant.buildingname} 直发 · 4-6 天 <span style={{ color: 'var(--fg-3)', marginLeft: 4 }}>免邮</span></span>
          </div>
        </div>
      ))}

      {/* coupon, points, message */}
      <div style={{ margin: '8px 14px', background: '#fff', borderRadius: 10 }}>
        {[
          { k: '优惠券', v: '满 599 减 50', red: true },
          { k: '积分抵扣', v: '可用 1,260 积分 抵 12.60', red: false },
          { k: '订单备注', v: '选填...', red: false, muted: true },
          { k: '发票', v: '不开发票', red: false, muted: true },
        ].map((r, i, arr) => (
          <div key={r.k} style={{ display: 'flex', alignItems: 'center', padding: '12px 14px', borderBottom: i < arr.length - 1 ? '0.5px solid var(--border-1)' : 'none' }}>
            <span style={{ fontSize: 12, color: 'var(--fg-3)', width: 70 }}>{r.k}</span>
            <span style={{ flex: 1, fontSize: 12, color: r.muted ? 'var(--fg-3)' : (r.red ? 'var(--brand)' : 'var(--fg-1)'), fontWeight: r.red ? 600 : 500, textAlign: 'right' }}>{r.v}</span>
            <Icon name="chev" size={12} stroke="var(--fg-3)" />
          </div>
        ))}
      </div>

      {/* pricing breakdown */}
      <div style={{ margin: '8px 14px', background: '#fff', borderRadius: 10, padding: '12px 14px' }}>
        {[
          ['商品总价', subtotal],
          ['运费', 0],
          ['优惠券', -couponDiscount, true],
          ['积分抵扣', -pointDiscount, true],
        ].map((r, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontSize: 11, color: 'var(--fg-2)' }}>
            <span>{r[0]}</span>
            <span style={{ color: r[2] ? 'var(--brand)' : 'var(--fg-1)' }}>{r[1] === 0 ? '免邮' : (r[2] ? '-' : '') + '¥' + Math.abs(r[1]).toFixed(2)}</span>
          </div>
        ))}
        <div style={{ borderTop: '0.5px solid var(--border-1)', marginTop: 8, paddingTop: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontSize: 11, color: 'var(--fg-2)' }}>实付</span>
          <PriceBlock cny={finalTotal} size={20} />
        </div>
      </div>

      {submitErr && (
        <div style={{ margin: '8px 14px', background: '#FEF2F2', color: '#B91C1C', borderRadius: 8, padding: '10px 12px', fontSize: 12 }}>
          {submitErr}
          {submitErr === '请先登录' && <span> — 跳转登录页…</span>}
        </div>
      )}

      {/* sticky pay */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 60, background: '#fff', borderTop: '0.5px solid var(--border-1)', display: 'flex', alignItems: 'center', padding: '0 14px', gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 9, color: 'var(--fg-3)' }}>实付金额 · 提交即锁定汇率</div>
          <PriceBlock cny={finalTotal} size={20} />
        </div>
        <button className="btn primary" style={{ padding: '12px 24px', fontSize: 14, fontWeight: 700, opacity: submitting ? 0.6 : 1 }} onClick={submitOrder} disabled={submitting}>
          {submitting ? '提交中…' : '提交订单'}
        </button>
      </div>
    </div>
  );
}

// ============================================================
// 07 PAY RESULT
// ============================================================
function PayResultScreen({ onOrders }) {
  const { code } = React.useContext(CurContext);
  return (
    <div className="appbody" style={{ background: '#fff', display: 'flex', flexDirection: 'column' }}>
      <div className="app-header">
        <Icon name="back" size={18} sw={2} />
        <div className="h-title">支付结果</div>
      </div>

      <div style={{ padding: '32px 24px 16px', textAlign: 'center', background: 'linear-gradient(180deg, var(--brand-soft) 0%, #fff 100%)' }}>
        <div style={{ width: 64, height: 64, borderRadius: '50%', margin: '0 auto', background: 'var(--brand)', display: 'grid', placeItems: 'center', boxShadow: '0 10px 24px var(--brand-soft)' }}>
          <Icon name="check" size={32} stroke="#fff" sw={2.4} />
        </div>
        <div style={{ marginTop: 14, fontSize: 18, fontFamily: 'var(--font-display)', fontWeight: 800, letterSpacing: '-0.02em' }}>支付成功</div>
        <div style={{ marginTop: 4, fontSize: 11, color: 'var(--fg-3)' }}>订单代下中 · 预计 2 分钟内进入备货</div>
        <PriceBlock cny={663.40} size={26} />
      </div>

      {/* progress */}
      <div style={{ padding: '14px 18px', borderTop: '0.5px solid var(--border-1)' }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-3)', letterSpacing: '0.06em' }}>ORDER PIPELINE</div>
        <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 0 }}>
          {[
            { l: '支付成功', s: '刚刚', done: true },
            { l: '订单已锁定汇率', s: '1 CNY = 188 KRW · 永久保留', done: true },
            { l: '正在向批发系统下单', s: 'apM 东大门 · 代下进行中…', done: false, active: true },
            { l: '商家备货 / DK 验真', s: '预计 4-6 天', done: false },
            { l: '签收完成 · 确认收货', s: '+1,326 积分', done: false },
          ].map((s, i, arr) => (
            <div key={i} style={{ display: 'flex', gap: 10, position: 'relative', paddingBottom: i < arr.length - 1 ? 14 : 0 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <span style={{ width: 20, height: 20, borderRadius: '50%', background: s.done ? 'var(--brand)' : (s.active ? '#fff' : '#F5F5F5'), border: s.active ? '2px solid var(--brand)' : 'none', display: 'grid', placeItems: 'center', flexShrink: 0, position: 'relative' }}>
                  {s.done && <Icon name="check" size={11} stroke="#fff" sw={3} />}
                  {s.active && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--brand)', animation: 'pulse-night 1.2s var(--ease) infinite' }} />}
                </span>
                {i < arr.length - 1 && <span style={{ flex: 1, width: 1.5, background: s.done ? 'var(--brand)' : 'var(--border-2)', minHeight: 18 }} />}
              </div>
              <div style={{ paddingTop: 1, paddingBottom: 4, flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: s.active || s.done ? 600 : 500, color: s.done ? 'var(--fg-1)' : (s.active ? 'var(--brand)' : 'var(--fg-3)') }}>{s.l}</div>
                <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{s.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* recommended */}
      <div style={{ padding: '8px 14px 14px', background: '#FAFAFA', flex: 1 }}>
        <div style={{ fontSize: 12, fontWeight: 700, padding: '10px 0' }}>顺手添加 · 同店满 599 减 50</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          {[3, 8, 12].map((i, k) => (
            <div key={k} style={{ background: '#fff', borderRadius: 8, overflow: 'hidden', border: '0.5px solid var(--border-1)' }}>
              <div style={{ aspectRatio: 1, background: `url(assets/p${i}.jpg) center/cover` }} />
              <div style={{ padding: '6px 8px 8px' }}>
                <PriceBlock cny={[228, 198, 358][k]} size={11} />
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding: '12px 14px 18px', display: 'flex', gap: 10, borderTop: '0.5px solid var(--border-1)', background: '#fff' }}>
        <button className="btn ghost block">返回首页</button>
        <button className="btn dark block" onClick={onOrders}>查看订单</button>
      </div>
    </div>
  );
}

// ============================================================
// 08 ORDERS LIST + DETAIL (combo)
// ============================================================
function OrdersScreen({ onCur }) {
  const tabs = ['全部', '待付款', '代下中', '待收货', '已完成'];
  const { isAuthed, user } = window.useAuth();
  const [serverOrders, setServerOrders] = React.useState(null); // null=loading, []=empty, [...]=有数据
  const [fetchErr, setFetchErr] = React.useState('');

  React.useEffect(() => {
    if (!isAuthed || user?.isGuest) { setServerOrders([]); return; }
    let alive = true;
    window.auth.fetch('/h5-orders?limit=20').then(r => r.json()).then(d => {
      if (!alive) return;
      if (d.ok) setServerOrders(d.items || []);
      else { setServerOrders([]); setFetchErr(d.error || '加载失败'); }
    }).catch(e => {
      if (!alive) return;
      setServerOrders([]); setFetchErr(e.message || '加载失败');
    });
    return () => { alive = false; };
  }, [isAuthed, user?.id]);

  // 把后端订单转成 UI 渲染需要的形态
  const orders = (serverOrders || []).map(o => {
    const items = Array.isArray(o.itemsJson) ? o.itemsJson : [];
    const firstStall = items[0]?.stall || {};
    const statusMap = {
      pending: { text: '待付款', key: 'proxying' },
      paid: { text: '代下中 · 进行中', key: 'proxying' },
      shipped: { text: '已发货', key: 'shipped' },
      done: { text: '已完成', key: 'done' },
      cancelled: { text: '已取消', key: 'done' },
    };
    const sm = statusMap[o.status] || { text: o.status, key: 'done' };
    return {
      no: o.orderNo,
      shop: firstStall.merchant || '未知商家',
      building: firstStall.building || '',
      layer: firstStall.layer || '',
      items: items.map(it => ({ idx: it.img || 1, n: it.name, spec: it.spec })),
      status: sm.text,
      statusKey: sm.key,
      total: Number(o.totalCny || 0),
      date: new Date(o.createdAt).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }),
      fx: o.fxLockJson?.currency ? `1 ${o.fxLockJson.currency} = ${o.fxLockJson.rate}` : '',
      tag: o.trackingNo ? 'truck' : (o.status === 'paid' ? 'live' : null),
      tagText: o.trackingNo ? `${o.trackingCarrier || '快递'} ${o.trackingNo}` : '',
    };
  });

  return (
    <div className="appbody" style={{ background: '#F2F2F2' }}>
      <div className="app-header">
        <Icon name="back" size={18} sw={2} />
        <div className="h-title">我的订单</div>
        <CurPill onClick={onCur} />
      </div>

      <div style={{ display: 'flex', background: '#fff', padding: '0 6px', borderBottom: '0.5px solid var(--border-1)', position: 'sticky', top: 40, zIndex: 5 }}>
        {tabs.map((t, i) => (
          <div key={t} style={{ flex: 1, textAlign: 'center', padding: '10px 0', position: 'relative', fontSize: 12, fontWeight: i === 0 ? 700 : 500, color: i === 0 ? 'var(--fg-1)' : 'var(--fg-2)' }}>
            {t}
            {i === 0 && <span style={{ position: 'absolute', bottom: 4, left: '50%', transform: 'translateX(-50%)', width: 18, height: 2, background: 'var(--brand)', borderRadius: 2 }} />}
          </div>
        ))}
      </div>

      <div style={{ padding: '8px 0' }}>
        {serverOrders === null && (
          <div style={{ padding: '40px 14px', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>加载中…</div>
        )}
        {serverOrders !== null && (!isAuthed || user?.isGuest) && (
          <div style={{ margin: '20px 14px', background: '#fff', borderRadius: 12, padding: 24, textAlign: 'center' }}>
            <div style={{ fontSize: 14, color: 'var(--fg-2)' }}>请先登录查看订单</div>
            <a href="#/login" className="btn primary" style={{ marginTop: 14, display: 'inline-block', textDecoration: 'none', padding: '10px 24px' }}>去登录</a>
          </div>
        )}
        {serverOrders !== null && isAuthed && !user?.isGuest && orders.length === 0 && (
          <div style={{ margin: '20px 14px', background: '#fff', borderRadius: 12, padding: 32, textAlign: 'center' }}>
            <div style={{ fontSize: 32 }}>🛍️</div>
            <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 6 }}>还没有订单</div>
            <a href="#/home" className="btn ghost" style={{ marginTop: 12, display: 'inline-block', textDecoration: 'none', padding: '8px 20px', fontSize: 12 }}>去逛逛</a>
            {fetchErr && <div style={{ marginTop: 8, fontSize: 11, color: '#B91C1C' }}>{fetchErr}</div>}
          </div>
        )}
        {orders.map((o, oi) => (
          <div key={o.no} style={{ background: '#fff', margin: '8px 14px', borderRadius: 10, overflow: 'hidden' }}>
            {/* head */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderBottom: '0.5px solid var(--border-1)' }}>
              <Sinsagom size={20} />
              <span style={{ fontSize: 12, fontWeight: 600, flex: 1 }}>{o.shop}</span>
              <span style={{ fontSize: 10, color: o.statusKey === 'shipped' ? 'var(--brand)' : (o.statusKey === 'proxying' ? '#F59E0B' : 'var(--fg-3)'), fontWeight: 600 }}>{o.status}</span>
            </div>

            {/* items */}
            <div style={{ display: 'flex', gap: 8, padding: '12px 14px', overflowX: 'auto', scrollbarWidth: 'none' }}>
              {o.items.map((it, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
                  <div style={{ width: 64, height: 64, borderRadius: 4, background: `url(assets/p${it.idx}.jpg) center/cover`, position: 'relative' }}>
                    {oi === 0 && i === 0 && <span className="chip dk" style={{ position: 'absolute', bottom: 2, right: 2, fontSize: 7, padding: '1px 3px' }}>DK</span>}
                  </div>
                  {o.items.length === 1 && (
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 500, lineHeight: 1.35, maxWidth: 140 }}>{it.n}</div>
                      <div style={{ fontSize: 9, color: 'var(--fg-3)', marginTop: 2 }}>{it.spec}</div>
                    </div>
                  )}
                </div>
              ))}
              {o.items.length > 1 && (
                <div style={{ flex: 1, textAlign: 'right', alignSelf: 'center', fontSize: 10, color: 'var(--fg-3)' }}>共 {o.items.length} 件</div>
              )}
            </div>

            {/* tag rows */}
            {o.tag === 'truck' && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, margin: '0 14px 10px', padding: '8px 10px', background: '#FAFAFA', borderRadius: 6, fontSize: 10 }}>
                <Icon name="truck" size={13} stroke="var(--brand)" />
                <span style={{ color: 'var(--fg-2)' }}>{o.tagText}</span>
                <span style={{ marginLeft: 'auto', color: 'var(--fg-3)' }}>已揽收 · 苏州</span>
              </div>
            )}
            {o.tag === 'live' && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, margin: '0 14px 10px', padding: '8px 10px', background: '#FFF8E6', borderRadius: 6, fontSize: 10 }}>
                <Icon name="globe" size={13} stroke="var(--apm-gold)" />
                <span style={{ color: 'var(--fg-2)' }}>正在向 apM 东大门下单</span>
                <span style={{ marginLeft: 'auto' }}><span className="nightband" style={{ fontSize: 8 }}><i />SEOUL 23:14</span></span>
              </div>
            )}

            {/* foot */}
            <div style={{ display: 'flex', alignItems: 'center', padding: '10px 14px', borderTop: '0.5px solid var(--border-1)' }}>
              <div style={{ flex: 1, fontSize: 9, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>
                {o.no} · {o.date}
                {o.fx && <span style={{ marginLeft: 4 }}>· FX {o.fx}</span>}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <span style={{ fontSize: 9, color: 'var(--fg-3)' }}>实付</span>
                <PriceBlock cny={o.total} size={14} />
              </div>
            </div>

            <div style={{ display: 'flex', gap: 6, padding: '0 14px 12px', justifyContent: 'flex-end' }}>
              {o.statusKey === 'shipped' && <button className="btn ghost" style={{ padding: '6px 14px', fontSize: 11 }}>查看物流</button>}
              {o.statusKey === 'proxying' && <button className="btn ghost" style={{ padding: '6px 14px', fontSize: 11, color: '#F59E0B', borderColor: '#F59E0B' }}>处理详情</button>}
              {o.statusKey === 'done' && <><button className="btn ghost" style={{ padding: '6px 14px', fontSize: 11 }}>申请售后</button><button className="btn primary" style={{ padding: '6px 14px', fontSize: 11 }}>立即评价 +50 积分</button></>}
              {o.statusKey === 'shipped' && <button className="btn primary" style={{ padding: '6px 14px', fontSize: 11 }}>确认收货</button>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// 09 PROFILE — me page
// ============================================================
function ProfileScreen({ onCur }) {
  const { code } = React.useContext(CurContext);
  return (
    <div className="appbody" style={{ background: '#F2F2F2' }}>
      {/* hero head */}
      <div style={{ position: 'relative', padding: '32px 18px 56px', background: 'linear-gradient(135deg, #1A1A1A 0%, #0B0B0B 60%, var(--brand-deep) 100%)', color: '#fff', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -20, top: -20, width: 180, height: 180, borderRadius: '50%', background: 'url(assets/sinsagom-1.jpg) center/cover', opacity: 0.6 }} />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: `url(assets/p4.jpg) center/cover`, border: '2px solid var(--apm-gold)' }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontFamily: 'var(--font-display)', fontWeight: 700 }}>李 · LISA</div>
            <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
              <span className="chip" style={{ background: 'var(--apm-gold)', color: '#000', fontSize: 9 }}>LUXE 会员</span>
              <span className="chip night" style={{ fontSize: 9 }}>夜枭买手</span>
            </div>
          </div>
          <Icon name="settings" size={18} stroke="#fff" sw={1.6} />
        </div>

        <div style={{ display: 'flex', gap: 20, marginTop: 14, position: 'relative' }}>
          {[
            { n: '12', l: '收藏' },
            { n: '8', l: '足迹' },
            { n: '4', l: '收货地址' },
          ].map(s => (
            <div key={s.l}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 700 }}>{s.n}</div>
              <div style={{ fontSize: 9, opacity: 0.7, letterSpacing: '0.04em' }}>{s.l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* points card overlay */}
      <div style={{ margin: '-44px 14px 0', background: '#fff', borderRadius: 12, padding: 14, boxShadow: '0 6px 18px rgba(0,0,0,0.06)', position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.06em', fontWeight: 600 }}>POINTS · 返利积分</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 28, color: 'var(--brand)', marginTop: 2, letterSpacing: '-0.02em' }}>3,260</div>
          </div>
          <button className="btn dark" style={{ padding: '8px 14px', fontSize: 11 }}>立即兑换 →</button>
        </div>
        <div style={{ marginTop: 10, padding: '8px 10px', background: '#FAFAFA', borderRadius: 6, display: 'flex', gap: 6, alignItems: 'center', fontSize: 10, color: 'var(--fg-2)' }}>
          <Icon name="coin" size={13} stroke="var(--apm-gold)" />
          下单 +1,326 即将到账 · 7 天后可用
        </div>
      </div>

      {/* order shortcuts */}
      <div style={{ margin: '10px 14px', background: '#fff', borderRadius: 12, padding: '14px 4px' }}>
        <div style={{ padding: '0 10px 10px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 13, fontWeight: 700 }}>我的订单</span>
          <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>查看全部 ›</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)' }}>
          {[
            { l: '待付款', i: 'coin', n: 0 },
            { l: '代下中', i: 'live', n: 1 },
            { l: '待收货', i: 'truck', n: 1 },
            { l: '待评价', i: 'star', n: 1 },
            { l: '退/售后', i: 'chat', n: 0 },
          ].map(t => (
            <div key={t.l} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, fontSize: 10, color: 'var(--fg-2)', position: 'relative' }}>
              <Icon name={t.i} size={20} sw={1.5} />
              {t.n > 0 && <span style={{ position: 'absolute', top: -4, right: '28%', fontSize: 8, fontWeight: 700, background: 'var(--brand)', color: '#fff', padding: '0 4px', minWidth: 12, height: 12, borderRadius: 999, display: 'grid', placeItems: 'center', lineHeight: 1, border: '1.5px solid #fff' }}>{t.n}</span>}
              {t.l}
            </div>
          ))}
        </div>
      </div>

      {/* offline stores */}
      <div style={{ margin: '10px 14px', background: '#fff', borderRadius: 12, padding: '14px' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
          <span style={{ fontSize: 13, fontWeight: 700 }}>线下店 · APM HOUR</span>
          <span style={{ fontSize: 10, color: 'var(--fg-3)' }}>5 家 · 上海</span>
        </div>
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', scrollbarWidth: 'none' }}>
          {[
            { l: '新天地', s: 'XINTIANDI', img: 'assets/p2.jpg' },
            { l: 'EKA · 成水洞', s: 'EKA', img: 'assets/p7.jpg' },
            { l: 'iAPM · 仁寺洞', s: 'iAPM', img: 'assets/p10.jpg' },
            { l: 'COEX', s: 'COEX', img: 'assets/p3.jpg' },
          ].map(s => (
            <div key={s.l} style={{ flexShrink: 0, width: 96 }}>
              <div style={{ aspectRatio: '4/5', borderRadius: 6, background: `url(${s.img}) center/cover`, position: 'relative', overflow: 'hidden' }}>
                <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, transparent 60%, rgba(0,0,0,0.7))' }} />
                <div style={{ position: 'absolute', bottom: 6, left: 6, right: 6, color: '#fff' }}>
                  <div style={{ fontSize: 11, fontWeight: 700 }}>{s.l}</div>
                  <div style={{ fontSize: 8, opacity: 0.7, letterSpacing: '0.06em' }}>{s.s}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* settings list */}
      <div style={{ margin: '10px 14px 24px', background: '#fff', borderRadius: 12, overflow: 'hidden' }}>
        {[
          { i: 'globe', l: '语言 / 币种', v: '简体中文 · ' + code, click: onCur },
          { i: 'pin', l: '收货地址', v: '4 个' },
          { i: 'qr', l: 'DK 验真历史', v: '12 次' },
          { i: 'live', l: 'AI 直播订阅', v: '已订阅 3 个直播间' },
          { i: 'chat', l: '客服 · 服务中心', v: 'apM Luxe 7F · 20:00–05:00' },
        ].map((r, i, arr) => (
          <div key={r.l} onClick={r.click} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '13px 14px', borderBottom: i < arr.length - 1 ? '0.5px solid var(--border-1)' : 'none', cursor: r.click ? 'pointer' : 'default' }}>
            <Icon name={r.i} size={16} sw={1.5} stroke="var(--fg-2)" />
            <span style={{ fontSize: 12, flex: 1 }}>{r.l}</span>
            <span style={{ fontSize: 10, color: 'var(--fg-3)' }}>{r.v}</span>
            <Icon name="chev" size={12} stroke="var(--fg-3)" />
          </div>
        ))}
      </div>

      <div style={{ padding: '0 0 24px', textAlign: 'center', fontSize: 9, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>
        © APM KOREA CO.,LTD · 110111-2441387<br />SINCE 1999 · SEOUL DONGDAEMUN
      </div>
    </div>
  );
}

Object.assign(window, { CartScreen, CheckoutScreen, PayResultScreen, OrdersScreen, ProfileScreen });
