/* ZY console — Shopee 店铺运营 COO · 看店 + 动手(shopee_coo_daily_workday_summary.v1 + 受控写)。
   老板 2026-07-14:通过系统运营整个 Shopee 店。看=只读监督;动手=受控写(系统建议·人拍板·留痕·可回滚)。
   设计来自 Claude Design(ShopeeStoreCooOps),忠实复刻。数据:店铺健康/库存/售后计数读 window.KIT.shopeeDigest
   (sources.js 已注水);商品操作清单现拉 /ops/boss/shopee/product-operation-list(真号供动手);写=确认那一下
   POST 受控端点(execute=true + 前端生成 decision_ref 拍板留痕)。整屏无利润数字;买家 PII 后端已抹。 */
const DSSHOP = window.ZYDesignSystem_d746df;
const SHOPEE_SHOP_ID = '1615189128';

function SS(str) {
  const o = {};
  String(str || '').split(';').forEach((d) => {
    const i = d.indexOf(':'); if (i < 0) return;
    const k = d.slice(0, i).trim(); const v = d.slice(i + 1).trim(); if (!k) return;
    o[k.replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = v;
  });
  return o;
}
function shopeeNum(v) { if (v === null || v === undefined || v === '') return null; const n = Number(v); return Number.isFinite(n) ? n : null; }
function shopeeValue(v) { return Number.isFinite(v) ? v : '—'; }
function shopeeRow(D, key) { return (D && Array.isArray(D.rows) ? D.rows.find((r) => r && r.source_key === key) : null) || {}; }
function shopeeToken() { try { return window.ZY_SESSION_TOKEN || (window.sessionStorage && sessionStorage.getItem('zy_console_token')) || null; } catch (e) { return null; } }
function shopeeMoney(v, c) { const n = shopeeNum(v); return n == null ? '—' : (c || 'MYR') + ' ' + n.toFixed(2); }

// 受控写动作注册表(endpoint 对齐后端;rev=可逆性 pos可撤/warn可再谈/neg不可撤)。
const SHOPEE_ACT = {
  price: { key: 'price_update', endpoint: '/ops/boss/shopee/controlled-actions/price-update', label: '改价', rev: 'pos', kind: 'money', warn: false, note: 'Shopee 改价成功后价格读回来会慢几秒;已提交即算成功,别因读到旧价当失败。' },
  listing: { key: 'listing_change', endpoint: '/ops/boss/shopee/controlled-actions/listing-change', label: '上下架', rev: 'pos', kind: 'none', warn: false, note: '重新上架偶尔需要平台过审。' },
  stock: { key: 'stock_update', endpoint: '/ops/boss/shopee/controlled-actions/stock-update', label: '改库存', rev: 'pos', kind: 'stock', warn: false, note: '' },
  item: { key: 'item_update', endpoint: '/ops/boss/shopee/controlled-actions/item-update', label: '改标题', rev: 'pos', kind: 'title', warn: false, note: '' },
  return_accept: { key: 'return_decision', endpoint: '/ops/boss/shopee/controlled-actions/return-decision', label: '同意退款', rev: 'neg', kind: 'none', warn: true, note: '' },
  return_reject: { key: 'return_decision', endpoint: '/ops/boss/shopee/controlled-actions/return-decision', label: '拒绝并申诉', rev: 'warn', kind: 'reject', warn: false, note: '' },
  chat: { key: 'chat_reply', endpoint: '/ops/boss/shopee/controlled-actions/chat-reply', label: '回复买家', rev: 'neg', kind: 'message', warn: true, note: '' },
};
const SHOPEE_RET_STATUS_CN = { REQUESTED: '申请中', PROCESSING: '处理中', ACCEPTED: '已受理', REFUND_PAID: '已退款', CANCELLED: '已取消', CLOSED: '已关闭', JUDGING: '平台介入中', SELLER_DISPUTE: '卖家申诉' };
const SHOPEE_RET_REASON_CN = { NON_RECEIPT: '没收到货', WRONG_ITEM: '发错货', ITEM_WRONG: '与描述不符', ITEM_MISSING: '少件', ITEM_DAMAGED: '商品破损', CHANGE_MIND: '不想要了', MUTUAL_AGREE: '协商一致', OTHER: '其他原因' };
const SHOPEE_ORD_STATUS_CN = { UNPAID: '待付款', READY_TO_SHIP: '待发货', PROCESSED: '处理中', SHIPPED: '已发货', TO_CONFIRM_RECEIVE: '待收货', COMPLETED: '已完成', CANCELLED: '已取消', IN_CANCEL: '取消中', TO_RETURN: '退货退款' };
const retReasonCn = (c) => SHOPEE_RET_REASON_CN[c] || c || '退货';
const retStatusCn = (c) => SHOPEE_RET_STATUS_CN[c] || c || '';
const ordStatusCn = (c) => SHOPEE_ORD_STATUS_CN[c] || c || '';
function shopeeRevText(rev) { return rev === 'pos' ? '可撤 · 已记旧值,可一键改回' : rev === 'warn' ? '可再谈 · 申诉后仍可继续沟通' : '不可撤 · 发出后无法撤回'; }
function shopeeGenRef() {
  const d = new Date(); const p = (n) => String(n).padStart(2, '0');
  const rnd = Math.random().toString(16).slice(2, 6).toUpperCase();
  return 'DR-' + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '-' + p(d.getHours()) + p(d.getMinutes()) + '-' + rnd;
}
// 受控写:经 /console/api 会话闸(注入内部 key);execute=true 才真写。
async function shopeeWrite(endpoint, body) {
  const token = shopeeToken();
  const res = await fetch('/console/api' + endpoint.slice(4), {
    method: 'POST', credentials: 'same-origin',
    headers: Object.assign({ 'content-type': 'application/json' }, token ? { authorization: 'Bearer ' + token } : {}),
    body: JSON.stringify(body),
  });
  const j = await res.json().catch(() => ({}));
  return { ok: res.ok, body: j };
}

function KitShopee() {
  const { Icon } = DSSHOP;
  const D = (window.KIT && window.KIT.shopeeDigest) || {};
  const oauth = shopeeRow(D, 'oauth_token_readiness');
  const health = shopeeRow(D, 'store_health_readiness');
  const inv = shopeeRow(D, 'inventory_health_readiness');
  const healthReady = health.source_status === 'ready';
  const inventoryReady = inv.source_status === 'ready';
  const h = { rating: healthReady && D.shop_rating != null ? D.shop_rating : null, penalty: healthReady ? shopeeNum(D.penalty_total_count) : null, fulfillFail: healthReady ? shopeeNum(health.fulfillment_failed) : null, serviceFail: healthReady ? shopeeNum(health.custom_service_failed) : null };
  const invv = { healthy: inventoryReady ? shopeeNum(inv.healthy_count) : null, low: inventoryReady ? shopeeNum(D.low_stock_count) : null, soldout: inventoryReady ? shopeeNum(D.sold_out_count) : null, unknown: inventoryReady ? shopeeNum(inv.unknown_count) : null };

  const [products, setProducts] = React.useState({ status: 'loading', rows: [] });
  const [returns, setReturns] = React.useState([]);
  const [orders, setOrders] = React.useState([]);
  const [chats, setChats] = React.useState([]);
  const [drawer, setDrawer] = React.useState(null); // { kind, id }
  const [cf, setCf] = React.useState(null); // { action, kind, id, form, step, decisionRef, busy, error, receipt }

  React.useEffect(() => {
    let live = true;
    const token = shopeeToken();
    const get = (path) => fetch('/console/api/boss/shopee/' + path, { credentials: 'same-origin', headers: token ? { authorization: 'Bearer ' + token } : {} }).then((r) => r.json()).catch(() => ({}));
    get('product-operation-list?shop_id=' + SHOPEE_SHOP_ID + '&limit=50').then((j) => {
      if (!live) return; const d = j && j.data;
      if (d && d.read_status === 'product_operation_list_read') setProducts({ status: 'ready', rows: d.products || [] });
      else setProducts({ status: 'blocked', rows: [], reason: (d && d.read_status) || 'unknown' });
    });
    get('return-operation-list?shop_id=' + SHOPEE_SHOP_ID + '&limit=50').then((j) => { if (live && j && j.data && j.data.read_status === 'return_operation_list_read') setReturns(j.data.returns || []); });
    get('order-operation-list?shop_id=' + SHOPEE_SHOP_ID + '&limit=50').then((j) => { if (live && j && j.data && j.data.read_status === 'order_operation_list_read') setOrders(j.data.orders || []); });
    get('chat-list?shop_id=' + SHOPEE_SHOP_ID + '&limit=50').then((j) => { if (live && j && j.data && j.data.read_status === 'chat_list_read') setChats(j.data.conversations || []); });
    return () => { live = false; };
  }, []);

  // 打开退货/订单抽屉时懒加载完整详情(买家 PII 后端已抹)。
  const [detail, setDetail] = React.useState(null);
  React.useEffect(() => {
    if (!drawer || (drawer.kind !== 'return' && drawer.kind !== 'order')) { setDetail(null); return; }
    let live = true; setDetail({ loading: true });
    const token = shopeeToken();
    const path = drawer.kind === 'return'
      ? 'return-detail?shop_id=' + SHOPEE_SHOP_ID + '&return_sn=' + encodeURIComponent(drawer.id)
      : 'order-detail?shop_id=' + SHOPEE_SHOP_ID + '&order_sn=' + encodeURIComponent(drawer.id);
    fetch('/console/api/boss/shopee/' + path, { credentials: 'same-origin', headers: token ? { authorization: 'Bearer ' + token } : {} })
      .then((r) => r.json()).then((j) => { if (live) setDetail({ loading: false, data: (j && j.data) || null }); })
      .catch(() => { if (live) setDetail({ loading: false, data: null }); });
    return () => { live = false; };
  }, [drawer]);

  React.useEffect(() => { const t = () => { if (window.lucide && window.lucide.createIcons) { try { window.lucide.createIcons(); } catch (e) { /* noop */ } } }; t(); });

  const prod = (id) => products.rows.find((p) => String(p.item_id) === String(id)) || {};
  const chatOf = (id) => chats.find((c) => String(c.conversation_id) === String(id)) || {};
  const openAction = (action, kind, id) => {
    const form = { typed: '' };
    if (kind === 'product') {
      const p = prod(id);
      if (action === 'price') form.newPrice = p.price != null ? String(p.price) : '';
      if (action === 'stock') form.newStock = p.stock != null ? String(p.stock) : '';
      if (action === 'item') { form.newName = p.name || ''; form.newDesc = ''; }
    }
    if (action === 'return_reject') { form.rejectReason = ''; form.rejectText = ''; }
    if (action === 'chat') form.message = '';
    setCf({ action, kind, id, form, step: 'preview', decisionRef: '', busy: false, error: '', receipt: null });
  };
  const setForm = (field, val) => setCf((c) => ({ ...c, form: { ...c.form, [field]: val } }));

  const actionBody = (c, execute, ref) => {
    const f = c.form; const a = c.action;
    const base = { shop_id: SHOPEE_SHOP_ID, execute, decision_ref: ref };
    if (a === 'price') { const p = prod(c.id); return { ...base, item_id: p.item_id, model_id: p.model_id, old_price: p.price, new_price: parseFloat(f.newPrice) }; }
    if (a === 'stock') { const p = prod(c.id); return { ...base, item_id: p.item_id, model_id: p.model_id, old_stock: p.stock, new_stock: parseInt(f.newStock, 10) }; }
    if (a === 'item') { const p = prod(c.id); return { ...base, item_id: p.item_id, old_name: p.name, new_name: f.newName, new_description: f.newDesc || undefined }; }
    if (a === 'listing') { const p = prod(c.id); return { ...base, item_id: p.item_id, list: p.status !== '在售' && p.status !== 'NORMAL' }; }
    if (a === 'return_accept') return { ...base, return_sn: c.id, decision: 'accept' };
    if (a === 'return_reject') return { ...base, return_sn: c.id, decision: 'reject', dispute_reason: 1, dispute_text: (f.rejectReason ? f.rejectReason + '：' : '') + (f.rejectText || '') };
    if (a === 'chat') return { ...base, to_id: chatOf(c.id).to_id, message: f.message };
    return base;
  };

  const confirm = async () => {
    const c = cf; if (!c || c.busy) return;
    const spec = SHOPEE_ACT[c.action]; const ref = shopeeGenRef();
    setCf((x) => ({ ...x, busy: true, error: '' }));
    const { ok, body } = await shopeeWrite(spec.endpoint, actionBody(c, true, ref));
    const data = body && body.data;
    if (ok && body && body.success && data && data.business_write_performed) {
      // 乐观更新本地商品状态(可撤动作记旧值)
      if (['price', 'stock', 'item', 'listing'].includes(c.action)) {
        setProducts((s) => ({ ...s, rows: s.rows.map((p) => {
          if (String(p.item_id) !== String(c.id)) return p;
          if (c.action === 'price') return { ...p, _oldPrice: p.price, price: parseFloat(c.form.newPrice) };
          if (c.action === 'stock') return { ...p, _oldStock: p.stock, stock: parseInt(c.form.newStock, 10) };
          if (c.action === 'item') return { ...p, _oldName: p.name, name: c.form.newName };
          if (c.action === 'listing') return { ...p, status: (p.status === '在售' || p.status === 'NORMAL') ? '已下架' : '在售' };
          return p;
        }) }));
      } else if (c.action === 'return_accept' || c.action === 'return_reject') {
        setReturns((rs) => rs.filter((r) => String(r.return_sn) !== String(c.id))); setDrawer(null);
      } else if (c.action === 'chat') {
        setChats((cs) => cs.filter((x) => String(x.conversation_id) !== String(c.id))); setDrawer(null);
      }
      setCf((x) => ({ ...x, step: 'receipt', decisionRef: data.decision_ref || ref, receipt: data, busy: false }));
    } else {
      setCf((x) => ({ ...x, busy: false, error: (data && data.action_status) || (body && body.message) || '写失败,未改动' }));
    }
  };

  const revert = async () => {
    const c = cf; if (!c) return;
    const p = prod(c.id); const ref = shopeeGenRef();
    let body = null;
    if (c.action === 'price' && p._oldPrice != null) body = { shop_id: SHOPEE_SHOP_ID, execute: true, decision_ref: ref, item_id: p.item_id, model_id: p.model_id, old_price: p.price, new_price: p._oldPrice };
    else if (c.action === 'stock' && p._oldStock != null) body = { shop_id: SHOPEE_SHOP_ID, execute: true, decision_ref: ref, item_id: p.item_id, model_id: p.model_id, old_stock: p.stock, new_stock: p._oldStock };
    else if (c.action === 'item' && p._oldName != null) body = { shop_id: SHOPEE_SHOP_ID, execute: true, decision_ref: ref, item_id: p.item_id, old_name: p.name, new_name: p._oldName };
    else if (c.action === 'listing') body = { shop_id: SHOPEE_SHOP_ID, execute: true, decision_ref: ref, item_id: p.item_id, list: (p.status !== '在售' && p.status !== 'NORMAL') };
    if (!body) { setCf(null); return; }
    setCf((x) => ({ ...x, busy: true }));
    await shopeeWrite(SHOPEE_ACT[c.action].endpoint, body);
    setProducts((s) => ({ ...s, rows: s.rows.map((x) => {
      if (String(x.item_id) !== String(c.id)) return x;
      if (c.action === 'price') return { ...x, price: x._oldPrice };
      if (c.action === 'stock') return { ...x, stock: x._oldStock };
      if (c.action === 'item') return { ...x, name: x._oldName };
      if (c.action === 'listing') return { ...x, status: (x.status === '在售' || x.status === 'NORMAL') ? '已下架' : '在售' };
      return x;
    }) }));
    setCf(null);
  };

  const rules = ['系统只建议,人拍板才写', '每次写先预演', '确认才生成拍板留痕', '绝不自动执行', '不出利润数字', '买家信息不显示'];
  const todoCount = returns.length + chats.length;

  return (
    <div className="view viewfade" data-screen-label="Shopee · 看店+动手">
      <div style={SS('display:flex;flex-direction:column;gap:var(--gap);font-size:14px;')}>

        <div style={SS('display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:11px 14px;background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);')}>
          <span style={SS('display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--fg-2);')}><Icon name="Clock" size={14} color="var(--accent)" />最近核验：<strong>{D.generated_at || '未提供'}</strong></span>
          <span style={SS('display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--fg-2);')}><Icon name="KeyRound" size={14} color="var(--accent)" />授权状态：<strong>{oauth.source_status_cn || '未提供'}</strong></span>
          <span style={SS('font-size:11.5px;color:var(--fg-3);')}>这是核验快照，不把核验时间冒充业务日。</span>
        </div>

        {/* 铁律条 */}
        <div style={SS('display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:11px 14px;background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);')}>
          <span style={SS('display:flex;align-items:center;gap:7px;padding-right:12px;border-right:1px solid var(--border-soft);white-space:nowrap;')}><Icon name="Scale" size={15} color="var(--accent)" /><span style={SS('font-size:12.5px;font-weight:700;font-family:var(--font-display);')}>动手的铁律</span></span>
          {rules.map((r, i) => (<span key={i} style={SS('display:inline-flex;align-items:center;gap:5px;font-size:12px;color:var(--fg-2);')}><Icon name="Check" size={12} color="var(--positive)" />{r}</span>))}
        </div>

        {/* 当前结论 */}
        <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
          <div style={SS('height:3px;background:var(--warning);')} />
          <div style={SS('padding:18px 20px;')}>
            <div style={SS('display:flex;align-items:center;gap:9px;flex-wrap:wrap;margin-bottom:12px;')}>
              <span style={SS('font-family:var(--font-display);font-size:17px;font-weight:700;')}>Shopee 店铺（MY）当前监督状态</span>
              <span style={SS('display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:999px;background:' + (todoCount > 0 ? 'color-mix(in srgb,var(--warning) 16%,var(--surface));color:var(--warning)' : 'color-mix(in srgb,var(--positive) 14%,var(--surface));color:var(--positive)') + ';font-size:12px;font-weight:600;')}><Icon name={todoCount > 0 ? 'CircleAlert' : 'CircleCheckBig'} size={13} />{todoCount > 0 ? '有 ' + todoCount + ' 处待你拍板' : '暂无待拍板事项'}</span>
            </div>
            <div style={SS('display:flex;flex-direction:column;gap:9px;max-width:880px;')}>
              <div style={SS('display:flex;align-items:flex-start;gap:10px;')}>
                <span style={SS('width:20px;height:20px;border-radius:6px;display:grid;place-items:center;background:color-mix(in srgb,var(--warning) 16%,var(--surface));color:var(--warning);flex-shrink:0;margin-top:1px;font-size:11px;font-weight:700;font-family:var(--font-num);')}>1</span>
                <div style={SS('font-size:14px;color:var(--fg);line-height:1.55;')}><strong style={SS('font-weight:600;')}>店铺评分 {h.rating != null ? h.rating + ' 分' : '未提供'}，违规扣分 {shopeeValue(h.penalty)}。</strong><span style={SS('color:var(--fg-2);')}>{healthReady ? ' 请结合发货与客服指标处理。' : ' 店铺健康事实源未就绪，不作原因推断。'}</span></div>
              </div>
              <div style={SS('display:flex;align-items:flex-start;gap:10px;')}>
                <span style={SS('width:20px;height:20px;border-radius:6px;display:grid;place-items:center;background:var(--surface-2);color:var(--fg-3);flex-shrink:0;margin-top:1px;font-size:11px;font-weight:700;font-family:var(--font-num);')}>2</span>
                <div style={SS('font-size:14px;color:var(--fg);line-height:1.55;')}><strong style={SS('font-weight:600;')}>点商品可动手改价 / 上下架 / 改库存 / 改标题。</strong><span style={SS('color:var(--fg-2);')}> 都先预演「会发生啥」,确认那一下才真写、能改回。</span></div>
              </div>
            </div>
          </div>
        </div>

        {/* 商品:可操作行(真实数据) */}
        <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
          <div style={SS('padding:var(--pad);')}>
            <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;flex-wrap:wrap;')}>
              <div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name="Package" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:15px;font-weight:600;')}>商品</span><span style={SS('font-size:12px;color:var(--fg-3);')}>{products.status === 'ready' ? products.rows.length + ' 款 · 点商品可动手' : ''}</span></div>
            </div>
            {products.status === 'loading' && (<div style={SS('font-size:13px;color:var(--fg-3);padding:14px 2px;')}>正在读取商品清单…</div>)}
            {products.status !== 'loading' && products.status !== 'ready' && (<div style={SS('font-size:13px;color:var(--fg-3);padding:14px 2px;line-height:1.6;')}>商品清单暂时读不到（{products.reason || products.status}）。登录后自动带凭证读取;若 token 过期,等每早 07:00 自动刷新或稍后重试。</div>)}
            {products.status === 'ready' && (
              <div style={SS('display:flex;flex-direction:column;gap:8px;')}>
                {products.rows.map((it) => (
                  <div key={it.item_id} onClick={() => setDrawer({ kind: 'product', id: it.item_id })} style={SS('display:flex;align-items:center;gap:12px;padding:11px 13px;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:var(--r-sm);cursor:pointer;')}>
                    <span style={SS('width:38px;height:38px;border-radius:9px;background:var(--surface);border:1px solid var(--border-soft);display:grid;place-items:center;color:var(--fg-4);flex-shrink:0;')}><Icon name="Image" size={16} /></span>
                    <div style={SS('min-width:0;flex:1;')}>
                      <div style={SS('font-size:13.5px;font-weight:600;line-height:1.35;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;')}>{it.name || '(未取到商品名)'}</div>
                      <div style={SS('font-size:11px;color:var(--fg-3);font-family:var(--font-num);')}>{it.item_id}</div>
                    </div>
                    <div style={SS('text-align:right;flex-shrink:0;')}><div style={SS('font-size:14px;font-weight:700;font-family:var(--font-num);')}>{it.price != null ? shopeeMoney(it.price) : '—'}</div><div style={SS('font-size:11px;color:var(--fg-3);')}>库存 {it.stock != null ? it.stock : '—'} · {it.status}</div></div>
                    <Icon name="ChevronRight" size={16} color="var(--fg-4)" />
                  </div>
                ))}
              </div>
            )}
            <div style={SS('font-size:11.5px;color:var(--fg-3);margin-top:11px;line-height:1.5;')}>点任一商品打开操作抽屉:改价 · 上下架 · 改库存 · 改标题,都要先预演再确认。型号库存读不到的商品,改价/改库存会禁用。</div>
          </div>
        </div>

        {/* 网格:售后 / 客服 / 库存 / 店铺健康 / 活动 */}
        <div style={SS('display:grid;gap:var(--gap);grid-template-columns:repeat(auto-fit,minmax(320px,1fr));align-items:start;')}>

          {/* 售后 */}
          <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
            <div style={SS('padding:var(--pad);')}>
              <div style={SS('display:flex;align-items:center;gap:9px;margin-bottom:13px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name="Undo2" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:14.5px;font-weight:600;')}>售后退货</span></div>
              {returns.length > 0 ? (
                <div style={SS('display:flex;flex-direction:column;gap:8px;')}>
                  {returns.map((r) => (
                    <div key={r.return_sn} onClick={() => setDrawer({ kind: 'return', id: r.return_sn })} style={SS('display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:var(--r-sm);cursor:pointer;')}>
                      <div style={SS('min-width:0;flex:1;')}><div style={SS('font-size:12.5px;font-weight:600;')}>{retReasonCn(r.reason)}</div><div style={SS('font-size:10.5px;color:var(--fg-3);')}>{retStatusCn(r.status)}</div></div>
                      <span style={SS('font-size:12.5px;font-family:var(--font-num);color:var(--fg-2);white-space:nowrap;')}>{r.refund_amount != null ? shopeeMoney(r.refund_amount, r.currency) : ''}</span>
                      <Icon name="ChevronRight" size={15} color="var(--fg-4)" />
                    </div>
                  ))}
                  <div style={SS('font-size:11px;color:var(--fg-3);line-height:1.5;margin-top:2px;')}>点开看详情(买家信息已抹),底部可同意退款或拒绝申诉。金额仅展示不算利润。</div>
                </div>
              ) : (
                <div style={SS('display:flex;align-items:center;gap:11px;')}><span style={SS('width:34px;height:34px;border-radius:9px;display:grid;place-items:center;background:color-mix(in srgb,var(--positive) 14%,var(--surface));color:var(--positive);')}><Icon name="Check" size={17} /></span><div><div style={SS('font-size:15px;font-weight:600;')}>这两周没有退货</div><div style={SS('font-size:12px;color:var(--fg-3);')}>是真的没有,不是没读到。</div></div></div>
              )}
            </div>
          </div>

          {/* 客服 */}
          <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
            <div style={SS('padding:var(--pad);')}>
              <div style={SS('display:flex;align-items:center;gap:9px;margin-bottom:13px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name="MessageCircle" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:14.5px;font-weight:600;')}>客服待回</span></div>
              {chats.length > 0 ? (
                <div style={SS('display:flex;flex-direction:column;gap:8px;')}>
                  {chats.map((c) => (
                    <div key={c.conversation_id} onClick={() => setDrawer({ kind: 'chat', id: c.conversation_id })} style={SS('display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:var(--r-sm);cursor:pointer;')}>
                      <span style={SS('width:32px;height:32px;border-radius:50%;background:var(--surface);border:1px solid var(--border-soft);display:grid;place-items:center;color:var(--fg-4);flex-shrink:0;')}><Icon name="UserRound" size={15} /></span>
                      <div style={SS('min-width:0;flex:1;')}><div style={SS('font-size:12.5px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;')}>{c.preview || '(空消息)'}</div><div style={SS('font-size:10.5px;color:var(--fg-3);')}>买家 · 未回 {c.unread}</div></div>
                      <Icon name="ChevronRight" size={15} color="var(--fg-4)" />
                    </div>
                  ))}
                </div>
              ) : (
                <div style={SS('display:flex;align-items:center;gap:11px;')}><span style={SS('width:34px;height:34px;border-radius:9px;display:grid;place-items:center;background:color-mix(in srgb,var(--positive) 14%,var(--surface));color:var(--positive);')}><Icon name="Check" size={17} /></span><div><div style={SS('font-size:15px;font-weight:600;')}>没有待回消息</div><div style={SS('font-size:12px;color:var(--fg-3);')}>回复引擎已就绪,有未回时在此逐条处理。</div></div></div>
              )}
            </div>
          </div>

          {/* 订单 */}
          <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
            <div style={SS('padding:var(--pad);')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:13px;')}><div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name="Receipt" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:14.5px;font-weight:600;')}>订单</span></div><span style={SS('font-size:11px;color:var(--fg-3);')}>点开只看不发货</span></div>
              {orders.length > 0 ? (
                <div style={SS('display:flex;flex-direction:column;gap:8px;')}>
                  {orders.slice(0, 8).map((o) => (
                    <div key={o.order_sn} onClick={() => setDrawer({ kind: 'order', id: o.order_sn })} style={SS('display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:var(--r-sm);cursor:pointer;')}>
                      <div style={SS('min-width:0;flex:1;')}><div style={SS('font-size:12.5px;font-weight:600;font-family:var(--font-num);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;')}>{o.order_sn}</div><div style={SS('font-size:10.5px;color:var(--fg-3);')}>{ordStatusCn(o.status)}</div></div>
                      <Icon name="ChevronRight" size={15} color="var(--fg-4)" />
                    </div>
                  ))}
                </div>
              ) : (<div style={SS('font-size:12.5px;color:var(--fg-3);line-height:1.6;')}>近 15 天暂无订单。</div>)}
              <div style={SS('font-size:11.5px;color:var(--fg-3);margin-top:10px;line-height:1.5;')}>只读详情,买家姓名/电话/地址一律不显示。发货走妙手。</div>
            </div>
          </div>

          {/* 库存 */}
          <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
            <div style={SS('padding:var(--pad);')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;')}><div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name="Boxes" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:14.5px;font-weight:600;')}>库存</span></div><span style={SS('display:inline-flex;align-items:center;gap:5px;font-size:11px;color:var(--positive);font-weight:600;')}><span style={SS('width:7px;height:7px;border-radius:50%;background:var(--positive);')} />充足</span></div>
              <div style={SS('display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--border-soft);border:1px solid var(--border-soft);border-radius:11px;overflow:hidden;')}>
                <div style={SS('background:var(--surface);padding:9px 10px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>充足</div><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-num);color:var(--positive);')}>{shopeeValue(invv.healthy)}</div></div>
                <div style={SS('background:var(--surface);padding:9px 10px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>快没货</div><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-num);')}>{shopeeValue(invv.low)}</div></div>
                <div style={SS('background:var(--surface);padding:9px 10px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>已售罄</div><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-num);')}>{shopeeValue(invv.soldout)}</div></div>
                <div style={SS('background:var(--surface);padding:9px 10px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>没读到</div><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-num);color:var(--fg-3);')}>{shopeeValue(invv.unknown)}</div></div>
              </div>
              <div style={SS('font-size:11.5px;color:var(--fg-3);margin-top:10px;line-height:1.5;')}>改库存在商品操作抽屉里做,同样先预演。</div>
            </div>
          </div>

          {/* 店铺健康 */}
          <div style={SS('background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
            <div style={SS('height:3px;background:var(--warning);')} />
            <div style={SS('padding:var(--pad);')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;')}><div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:color-mix(in srgb,var(--warning) 15%,var(--surface));color:var(--warning);')}><Icon name="HeartPulse" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:14.5px;font-weight:600;')}>店铺健康</span></div><span style={SS('display:inline-flex;align-items:center;gap:4px;padding:2px 9px;border-radius:999px;background:color-mix(in srgb,var(--warning) 16%,var(--surface));color:var(--warning);font-size:11px;font-weight:600;')}>要留意</span></div>
              <div style={SS('display:grid;grid-template-columns:repeat(2,1fr);gap:1px;background:var(--border-soft);border:1px solid var(--border-soft);border-radius:11px;overflow:hidden;')}>
                <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>店铺评分</div><div style={SS('display:flex;align-items:baseline;gap:5px;')}><span style={SS('font-size:22px;font-weight:700;font-family:var(--font-num);color:var(--warning);line-height:1;')}>{h.rating != null ? h.rating : '—'}</span><span style={SS('font-size:11px;color:var(--warning);font-weight:600;')}>偏低</span></div></div>
                <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>违规扣分</div><div style={SS('font-size:22px;font-weight:700;font-family:var(--font-num);color:var(--warning);line-height:1;')}>{shopeeValue(h.penalty)}</div></div>
                <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>发货没赶上</div><div style={SS('font-size:22px;font-weight:700;font-family:var(--font-num);line-height:1;')}>{shopeeValue(h.fulfillFail)}</div></div>
                <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>客服没回好</div><div style={SS('font-size:22px;font-weight:700;font-family:var(--font-num);line-height:1;')}>{shopeeValue(h.serviceFail)}</div></div>
              </div>
              <div style={SS('font-size:11.5px;color:var(--fg-3);margin-top:10px;line-height:1.5;')}>回复客服、准时发货能把分补回来。</div>
            </div>
          </div>

          {/* 活动 待接 */}
          <div style={SS('background:var(--surface);border:1px solid var(--border-soft);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;')}>
            <div style={SS('height:3px;background:var(--fg-4);')} />
            <div style={SS('padding:var(--pad);')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:12px;')}><div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--surface-2);color:var(--fg-3);')}><Icon name="CalendarClock" size={15} /></span><span style={SS('font-family:var(--font-display);font-size:14.5px;font-weight:600;color:var(--fg-2);')}>活动报名</span></div><span style={SS('display:inline-flex;align-items:center;gap:5px;padding:2px 9px;border-radius:999px;background:var(--surface-2);color:var(--fg-3);font-size:11px;font-weight:600;')}><Icon name="Hourglass" size={12} />待接</span></div>
              <div style={SS('font-size:12.5px;color:var(--fg-2);line-height:1.6;')}>报活动就是打折,得先算清成本利润才知道值不值。成本在妙手 ERP（未接）,所以这里<strong style={SS('font-weight:600;color:var(--fg);')}>先不做任何报名操作</strong>。等成本与活动接口定案再单独接。</div>
            </div>
          </div>
        </div>

        <div style={SS('font-size:11.5px;color:var(--fg-3);line-height:1.6;max-width:920px;padding:2px 2px 8px;')}>每一次动手都先预演「会发生啥」,你确认那一下才生成拍板留痕、才真写;系统绝不自动改价/退款/发消息。整屏不出现利润数字;买家姓名/电话/地址一律不显示。</div>
      </div>

      {/* 商品操作抽屉 */}
      {drawer && drawer.kind === 'product' && (() => {
        const p = prod(drawer.id); const canModel = p.model_id != null;
        return (
          <div>
            <div onClick={() => setDrawer(null)} style={SS('position:fixed;inset:0;background:color-mix(in srgb,var(--fg) 32%,transparent);z-index:39;')} />
            <aside style={SS('position:fixed;top:0;right:0;bottom:0;width:min(460px,94vw);background:var(--surface);border-left:1px solid var(--border);box-shadow:var(--shadow-lg);z-index:40;display:flex;flex-direction:column;')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;padding:15px 18px;border-bottom:1px solid var(--border);')}>
                <div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:26px;height:26px;border-radius:7px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name="Package" size={14} /></span><span style={SS('font-family:var(--font-display);font-size:15px;font-weight:700;')}>商品操作</span></div>
                <button onClick={() => setDrawer(null)} style={SS('width:30px;height:30px;border-radius:8px;border:1px solid var(--border);background:var(--surface);color:var(--fg-2);cursor:pointer;display:grid;place-items:center;')}><Icon name="X" size={15} /></button>
              </div>
              <div style={SS('flex:1;overflow-y:auto;padding:18px;')}>
                <div style={SS('font-size:15px;font-weight:600;line-height:1.35;margin-bottom:4px;')}>{p.name || '(未取到商品名)'}</div>
                <div style={SS('font-size:11.5px;color:var(--fg-3);font-family:var(--font-num);margin-bottom:16px;')}>{p.item_id}</div>
                <div style={SS('display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--border-soft);border:1px solid var(--border-soft);border-radius:11px;overflow:hidden;margin-bottom:16px;')}>
                  <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>现价</div><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-num);')}>{p.price != null ? shopeeMoney(p.price) : '—'}</div></div>
                  <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>库存</div><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-num);')}>{p.stock != null ? p.stock : '—'}</div></div>
                  <div style={SS('background:var(--surface);padding:11px 13px;')}><div style={SS('font-size:10.5px;color:var(--fg-3);')}>状态</div><div style={SS('font-size:14px;font-weight:700;color:' + ((p.status === '在售' || p.status === 'NORMAL') ? 'var(--positive)' : 'var(--fg-3)') + ';')}>{p.status}</div></div>
                </div>
                {!canModel && (<div style={SS('font-size:11.5px;color:var(--warning);line-height:1.5;margin-bottom:10px;')}>此商品型号/库存这次没读到,改价与改库存暂不可用(可上下架、改标题)。</div>)}
                <div style={SS('font-size:11.5px;color:var(--fg-3);font-weight:600;margin-bottom:9px;')}>可动手(每个都先预演)</div>
                <div style={SS('display:grid;grid-template-columns:1fr 1fr;gap:9px;')}>
                  {[['price', 'Tag', '改价', canModel], ['listing', 'Power', (p.status === '在售' || p.status === 'NORMAL') ? '下架' : '上架', true], ['stock', 'Boxes', '改库存', canModel], ['item', 'Pencil', '改标题', true]].map(([act, icon, label, enabled]) => (
                    <button key={act} disabled={!enabled} onClick={() => enabled && openAction(act, 'product', p.item_id)} style={SS('display:flex;align-items:center;gap:8px;padding:12px 13px;border:1px solid var(--border);border-radius:11px;background:var(--surface-2);cursor:' + (enabled ? 'pointer' : 'not-allowed') + ';opacity:' + (enabled ? '1' : '.5') + ';text-align:left;')}><Icon name={icon} size={15} color="var(--accent)" /><span style={SS('font-size:13px;font-weight:600;')}>{label}</span></button>
                  ))}
                </div>
              </div>
            </aside>
          </div>
        );
      })()}

      {/* 退货 / 订单 / 客服 详情抽屉 */}
      {drawer && (drawer.kind === 'return' || drawer.kind === 'order' || drawer.kind === 'chat') && (() => {
        const kind = drawer.kind;
        const title = kind === 'return' ? '退货详情' : kind === 'order' ? '订单详情' : '客服会话';
        const dicon = kind === 'return' ? 'Undo2' : kind === 'order' ? 'Receipt' : 'MessageCircle';
        const rd = detail && detail.data && detail.data.return_detail;
        const od = detail && detail.data && detail.data.order_detail;
        const c = kind === 'chat' ? chatOf(drawer.id) : {};
        const loading = detail && detail.loading;
        return (
          <div>
            <div onClick={() => setDrawer(null)} style={SS('position:fixed;inset:0;background:color-mix(in srgb,var(--fg) 32%,transparent);z-index:39;')} />
            <aside style={SS('position:fixed;top:0;right:0;bottom:0;width:min(460px,94vw);background:var(--surface);border-left:1px solid var(--border);box-shadow:var(--shadow-lg);z-index:40;display:flex;flex-direction:column;')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;padding:15px 18px;border-bottom:1px solid var(--border);')}>
                <div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('width:26px;height:26px;border-radius:7px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);')}><Icon name={dicon} size={14} /></span><span style={SS('font-family:var(--font-display);font-size:15px;font-weight:700;')}>{title}</span></div>
                <button onClick={() => setDrawer(null)} style={SS('width:30px;height:30px;border-radius:8px;border:1px solid var(--border);background:var(--surface);color:var(--fg-2);cursor:pointer;display:grid;place-items:center;')}><Icon name="X" size={15} /></button>
              </div>
              <div style={SS('flex:1;overflow-y:auto;padding:18px;')}>
                {loading && (<div style={SS('font-size:13px;color:var(--fg-3);')}>读取详情中…</div>)}
                {kind === 'return' && !loading && (<div style={SS('display:flex;flex-direction:column;gap:11px;')}>
                  <div style={SS('display:flex;justify-content:space-between;gap:12px;padding-bottom:11px;border-bottom:1px solid var(--border-soft);')}><span style={SS('font-size:12px;color:var(--fg-3);')}>退款金额(仅展示)</span><span style={SS('font-size:15px;font-weight:700;font-family:var(--font-num);')}>{rd && rd.refund_amount != null ? shopeeMoney(rd.refund_amount, rd.currency) : '—'}</span></div>
                  <div><div style={SS('font-size:12px;color:var(--fg-3);margin-bottom:3px;')}>退货原因</div><div style={SS('font-size:13.5px;font-weight:600;')}>{retReasonCn(rd && rd.reason)}</div></div>
                  {rd && rd.text_reason && (<div><div style={SS('font-size:12px;color:var(--fg-3);margin-bottom:3px;')}>买家理由(电话/邮箱已抹)</div><div style={SS('font-size:13px;line-height:1.55;color:var(--fg);background:var(--surface-2);border-radius:var(--r-sm);padding:10px 12px;')}>{rd.text_reason}</div></div>)}
                  <div style={SS('display:flex;gap:20px;flex-wrap:wrap;')}><div><div style={SS('font-size:12px;color:var(--fg-3);')}>状态</div><div style={SS('font-size:13.5px;font-weight:600;')}>{retStatusCn(rd && rd.status)}</div></div><div><div style={SS('font-size:12px;color:var(--fg-3);')}>图证</div><div style={SS('font-size:13.5px;font-weight:600;font-family:var(--font-num);')}>{rd ? rd.image_count : 0} 张</div></div></div>
                  {rd && rd.items && rd.items.length > 0 && (<div><div style={SS('font-size:12px;color:var(--fg-3);margin-bottom:5px;')}>退货商品</div>{rd.items.map((ri, i) => (<div key={i} style={SS('display:flex;justify-content:space-between;gap:10px;font-size:13px;background:var(--surface-2);border-radius:var(--r-sm);padding:8px 11px;margin-bottom:6px;')}><span>{ri.name || '(商品)'}</span><span style={SS('font-family:var(--font-num);color:var(--fg-2);')}>×{ri.qty}</span></div>))}</div>)}
                </div>)}
                {kind === 'order' && !loading && (<div style={SS('display:flex;flex-direction:column;gap:11px;')}>
                  <div style={SS('display:flex;justify-content:space-between;gap:12px;padding-bottom:11px;border-bottom:1px solid var(--border-soft);')}><span style={SS('font-size:12px;color:var(--fg-3);')}>订单金额</span><span style={SS('font-size:15px;font-weight:700;font-family:var(--font-num);')}>{od && od.total_amount != null ? shopeeMoney(od.total_amount, od.currency) : '—'}</span></div>
                  <div><div style={SS('font-size:12px;color:var(--fg-3);')}>状态</div><div style={SS('font-size:13.5px;font-weight:600;')}>{ordStatusCn(od && od.status)}</div></div>
                  {od && od.items && od.items.length > 0 && (<div><div style={SS('font-size:12px;color:var(--fg-3);margin-bottom:5px;')}>商品明细({od.item_count} 件)</div>{od.items.map((oi, i) => (<div key={i} style={SS('display:flex;justify-content:space-between;gap:10px;align-items:center;font-size:13px;background:var(--surface-2);border-radius:var(--r-sm);padding:8px 11px;margin-bottom:6px;')}><div style={SS('min-width:0;')}><div style={SS('font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;')}>{oi.name}</div><div style={SS('font-size:11px;color:var(--fg-3);')}>{oi.model || ''} · ×{oi.qty}</div></div><span style={SS('font-family:var(--font-num);color:var(--fg-2);white-space:nowrap;')}>{oi.price != null ? shopeeMoney(oi.price, od.currency) : ''}</span></div>))}</div>)}
                  <div style={SS('display:flex;align-items:flex-start;gap:7px;padding:9px 11px;background:var(--surface-2);border-radius:var(--r-sm);')}><Icon name="Shield" size={13} color="var(--fg-3)" /><span style={SS('font-size:11.5px;color:var(--fg-2);line-height:1.5;')}>买家姓名/电话/地址一律不显示。发货走妙手,这里只看不发货。</span></div>
                </div>)}
                {kind === 'chat' && (<div>
                  <div style={SS('display:flex;align-items:center;gap:9px;margin-bottom:14px;')}><span style={SS('width:30px;height:30px;border-radius:50%;background:var(--surface-2);border:1px solid var(--border-soft);display:grid;place-items:center;color:var(--fg-4);')}><Icon name="UserRound" size={15} /></span><div><div style={SS('font-size:13.5px;font-weight:600;')}>买家(身份已抹)</div><div style={SS('font-size:11px;color:var(--fg-3);')}>未回 {c.unread}</div></div></div>
                  <div style={SS('align-self:flex-start;max-width:85%;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:12px 12px 12px 3px;padding:9px 12px;')}><div style={SS('font-size:13px;line-height:1.5;')}>{c.preview || '(消息)'}</div></div>
                </div>)}
              </div>
              {(kind === 'return' || kind === 'chat') && (
                <div style={SS('flex-shrink:0;padding:13px 18px;border-top:1px solid var(--border);display:flex;gap:9px;')}>
                  {kind === 'return' && (<>
                    <button onClick={() => openAction('return_reject', 'return', drawer.id)} style={SS('flex:1;padding:11px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:13px;font-weight:600;cursor:pointer;')}>拒绝并申诉</button>
                    <button onClick={() => openAction('return_accept', 'return', drawer.id)} style={SS('flex:1;padding:11px;border:1px solid var(--negative);border-radius:10px;background:color-mix(in srgb,var(--negative) 10%,var(--surface));color:var(--negative);font-size:13px;font-weight:600;cursor:pointer;')}>同意退款</button>
                  </>)}
                  {kind === 'chat' && (<button onClick={() => openAction('chat', 'chat', drawer.id)} style={SS('flex:1;padding:11px;border:1px solid var(--accent);border-radius:10px;background:var(--accent-soft);color:var(--accent-ink);font-size:13px;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:7px;')}><Icon name="Send" size={14} />回复买家</button>)}
                </div>
              )}
            </aside>
          </div>
        );
      })()}

      {/* 受控写确认流 */}
      {cf && (() => {
        const spec = SHOPEE_ACT[cf.action]; const p = prod(cf.id); const f = cf.form; const isReceipt = cf.step === 'receipt';
        const kind = spec.kind; const needTyped = spec.warn;
        const typedOk = !needTyped || (f.typed || '').trim() === '确认';
        let filled = true;
        if (kind === 'money') filled = !!(f.newPrice && parseFloat(f.newPrice) > 0);
        else if (kind === 'stock') filled = f.newStock !== '' && parseInt(f.newStock, 10) >= 0;
        else if (kind === 'title') filled = !!(f.newName && f.newName.trim());
        else if (kind === 'reject') filled = !!(f.rejectReason && (f.rejectText || '').trim());
        else if (kind === 'message') filled = !!((f.message || '').trim());
        const canConfirm = typedOk && filled && !cf.busy;
        let baLabel = '', beforeVal = '', afterVal = '', desc = '';
        if (cf.action === 'price') { baLabel = '售价'; beforeVal = shopeeMoney(p.price); afterVal = 'MYR ' + (f.newPrice || '—'); }
        else if (cf.action === 'stock') { baLabel = '库存'; beforeVal = (p.stock != null ? p.stock : '—') + ' 件'; afterVal = (f.newStock || '—') + ' 件'; }
        else if (cf.action === 'listing') { baLabel = '状态'; beforeVal = p.status; afterVal = (p.status === '在售' || p.status === 'NORMAL') ? '已下架' : '在售'; }
        else if (cf.action === 'item') { baLabel = '标题'; beforeVal = p.name || '—'; afterVal = f.newName || '—'; }
        else if (cf.action === 'return_accept') desc = '将同意此退货,退款发给买家。此操作不可撤回。';
        else if (cf.action === 'return_reject') desc = '将向平台申诉此退货,进入平台仲裁。';
        else if (cf.action === 'chat') desc = '将把你写的这段文字直接发给买家。发出后不可撤回。';
        const revColor = spec.rev === 'pos' ? 'var(--positive)' : spec.rev === 'warn' ? 'var(--warning)' : 'var(--negative)';
        return (
          <div style={SS('position:fixed;inset:0;background:color-mix(in srgb,var(--fg) 42%,transparent);z-index:55;display:grid;place-items:center;padding:20px;')}>
            <div style={SS('width:min(540px,96vw);max-height:88vh;background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-lg);display:flex;flex-direction:column;overflow:hidden;')}>
              <div style={SS('display:flex;align-items:center;justify-content:space-between;gap:10px;padding:15px 18px;border-bottom:1px solid var(--border);')}>
                <div style={SS('display:flex;align-items:center;gap:9px;')}><span style={SS('display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:8px;background:var(--accent-soft);color:var(--accent-ink);font-size:11px;font-weight:700;')}><Icon name="ShieldAlert" size={12} />受控动作</span><span style={SS('font-family:var(--font-display);font-size:15px;font-weight:700;')}>{spec.label}</span></div>
                <button onClick={() => setCf(null)} style={SS('width:30px;height:30px;border-radius:8px;border:1px solid var(--border);background:var(--surface);color:var(--fg-2);cursor:pointer;display:grid;place-items:center;')}><Icon name="X" size={15} /></button>
              </div>
              <div style={SS('flex:1;overflow-y:auto;padding:18px;')}>
                {!isReceipt && (<>
                  {spec.warn && (<div style={SS('display:flex;align-items:flex-start;gap:9px;padding:11px 13px;background:color-mix(in srgb,var(--negative) 11%,var(--surface));border:1px solid color-mix(in srgb,var(--negative) 30%,var(--surface));border-radius:var(--r-sm);margin-bottom:14px;')}><Icon name="TriangleAlert" size={16} color="var(--negative)" /><div style={SS('font-size:12.5px;color:var(--negative);line-height:1.5;font-weight:600;')}>此操作不可撤,确认后立即生效、无法收回。</div></div>)}
                  {baLabel && (<div style={SS('display:flex;align-items:stretch;gap:10px;margin-bottom:15px;')}><div style={SS('flex:1;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:11px;padding:12px 14px;')}><div style={SS('font-size:11px;color:var(--fg-3);margin-bottom:4px;')}>{baLabel}（改前）</div><div style={SS('font-size:17px;font-weight:700;font-family:var(--font-num);')}>{beforeVal}</div></div><div style={SS('display:grid;place-items:center;color:var(--accent);')}><Icon name="ArrowRight" size={18} /></div><div style={SS('flex:1;background:var(--accent-soft);border:1px solid var(--accent-line);border-radius:11px;padding:12px 14px;')}><div style={SS('font-size:11px;color:var(--accent-ink);opacity:.8;margin-bottom:4px;')}>{baLabel}（改后）</div><div style={SS('font-size:17px;font-weight:700;font-family:var(--font-num);color:var(--accent-ink);')}>{afterVal}</div></div></div>)}
                  {desc && (<div style={SS('display:flex;align-items:flex-start;gap:9px;padding:12px 14px;background:var(--surface-2);border:1px solid var(--border-soft);border-radius:11px;margin-bottom:15px;')}><Icon name="Info" size={15} color="var(--fg-2)" /><div style={SS('font-size:13.5px;color:var(--fg);line-height:1.55;font-weight:600;')}>{desc}</div></div>)}
                  {kind === 'money' && (<div style={SS('margin-bottom:6px;')}><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>新售价</label><div style={SS('display:flex;align-items:center;gap:8px;')}><span style={SS('font-size:13px;color:var(--fg-3);font-family:var(--font-num);')}>MYR</span><input value={f.newPrice} onChange={(e) => setForm('newPrice', e.target.value)} inputMode="decimal" style={SS('flex:1;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:15px;font-family:var(--font-num);font-weight:700;outline:none;')} /></div></div>)}
                  {kind === 'stock' && (<div style={SS('margin-bottom:6px;')}><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>新可售数量</label><input value={f.newStock} onChange={(e) => setForm('newStock', e.target.value)} inputMode="numeric" style={SS('width:100%;box-sizing:border-box;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:15px;font-family:var(--font-num);font-weight:700;outline:none;')} /></div>)}
                  {kind === 'title' && (<div><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>新标题</label><input value={f.newName} onChange={(e) => setForm('newName', e.target.value)} style={SS('width:100%;box-sizing:border-box;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:14px;outline:none;margin-bottom:11px;')} /><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>新描述（选填）</label><textarea value={f.newDesc} onChange={(e) => setForm('newDesc', e.target.value)} rows={3} placeholder="留空则不改描述" style={SS('width:100%;box-sizing:border-box;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:13px;line-height:1.5;outline:none;resize:vertical;font-family:var(--font-sans);')} /></div>)}
                  {kind === 'reject' && (<div><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>申诉理由</label><select value={f.rejectReason} onChange={(e) => setForm('rejectReason', e.target.value)} style={SS('width:100%;box-sizing:border-box;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:14px;outline:none;margin-bottom:11px;')}><option value="">请选择理由</option><option value="商品无质量问题">商品无质量问题</option><option value="买家已使用/影响二次销售">买家已使用/影响二次销售</option><option value="超出退货时限">超出退货时限</option><option value="其他">其他(见补充)</option></select><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>补充说明(发给平台)</label><textarea value={f.rejectText} onChange={(e) => setForm('rejectText', e.target.value)} rows={3} placeholder="向平台说明为何拒绝退货" style={SS('width:100%;box-sizing:border-box;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:13px;line-height:1.5;outline:none;resize:vertical;font-family:var(--font-sans);')} /></div>)}
                  {kind === 'message' && (<div><label style={SS('display:block;font-size:12px;color:var(--fg-2);font-weight:600;margin-bottom:6px;')}>回复文字(将发给买家)</label><textarea value={f.message} onChange={(e) => setForm('message', e.target.value)} rows={4} placeholder="输入要发送的回复…" style={SS('width:100%;box-sizing:border-box;padding:11px 13px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:14px;line-height:1.5;outline:none;resize:vertical;font-family:var(--font-sans);')} /></div>)}
                  <div style={SS('margin-top:15px;')}><span style={SS('display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;background:color-mix(in srgb,' + revColor + ' 14%,var(--surface));color:' + revColor + ';font-size:12px;font-weight:600;')}><Icon name={spec.rev === 'neg' ? 'Ban' : 'RotateCcw'} size={13} />{shopeeRevText(spec.rev)}</span></div>
                  {spec.note && (<div style={SS('display:flex;align-items:flex-start;gap:7px;margin-top:12px;padding:9px 11px;background:color-mix(in srgb,var(--warning) 10%,var(--surface));border-radius:var(--r-sm);')}><Icon name="Clock" size={13} color="var(--warning)" /><span style={SS('font-size:11.5px;color:var(--fg-2);line-height:1.5;')}>{spec.note}</span></div>)}
                  {needTyped && (<div style={SS('margin-top:14px;padding-top:14px;border-top:1px dashed var(--border);')}><label style={SS('display:block;font-size:12px;color:var(--negative);font-weight:600;margin-bottom:6px;')}>此操作不可撤:请键入「确认」二字以启用执行</label><input value={f.typed} onChange={(e) => setForm('typed', e.target.value)} placeholder="确认" style={SS('width:100%;box-sizing:border-box;padding:10px 13px;border:1px solid var(--negative);border-radius:10px;background:var(--surface);color:var(--fg);font-size:14px;outline:none;')} /></div>)}
                  {cf.error && (<div style={SS('margin-top:13px;padding:10px 12px;background:color-mix(in srgb,var(--negative) 10%,var(--surface));border-radius:var(--r-sm);font-size:12.5px;color:var(--negative);font-weight:600;')}>写失败:{cf.error}(未改动任何东西)</div>)}
                  <div style={SS('margin-top:15px;font-size:11px;font-family:var(--font-num);color:var(--fg-4);')}>endpoint {spec.endpoint} · execute=false 预演 / 确认→execute=true</div>
                </>)}
                {isReceipt && (<div style={SS('display:flex;flex-direction:column;align-items:center;text-align:center;padding:6px 0 4px;')}><span style={SS('width:52px;height:52px;border-radius:50%;background:color-mix(in srgb,var(--positive) 15%,var(--surface));color:var(--positive);display:grid;place-items:center;margin-bottom:12px;')}><Icon name="Check" size={26} /></span><div style={SS('font-size:16px;font-weight:700;font-family:var(--font-display);')}>已提交 · {spec.label}</div><div style={SS('font-size:12.5px;color:var(--fg-2);line-height:1.55;margin-top:6px;max-width:380px;')}>{cf.action === 'price' ? '价格约几秒后刷新(Shopee 读延迟,不是失败)。旧值已记录,可改回。' : spec.rev === 'pos' ? '已记录旧值,如需可点「改回去」。' : spec.rev === 'neg' ? '已生效,此操作不可撤回。' : '申诉已提交,你仍可继续沟通。'}</div><div style={SS('margin-top:16px;width:100%;display:flex;flex-direction:column;gap:8px;')}><div style={SS('display:flex;justify-content:space-between;gap:10px;padding:10px 13px;background:var(--surface-2);border-radius:var(--r-sm);')}><span style={SS('font-size:12px;color:var(--fg-3);')}>是否真写</span><span style={SS('font-size:12.5px;font-weight:700;color:var(--positive);')}>是 · business_write_performed</span></div><div style={SS('display:flex;justify-content:space-between;gap:10px;padding:10px 13px;background:var(--surface-2);border-radius:var(--r-sm);')}><span style={SS('font-size:12px;color:var(--fg-3);')}>拍板留痕 decision_ref</span><span style={SS('font-size:12px;font-weight:700;font-family:var(--font-num);')}>{cf.decisionRef}</span></div></div></div>)}
              </div>
              <div style={SS('flex-shrink:0;padding:13px 18px;border-top:1px solid var(--border);display:flex;gap:9px;justify-content:flex-end;')}>
                {!isReceipt && (<>
                  <button onClick={() => setCf(null)} style={SS('padding:11px 18px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg-2);font-size:13px;font-weight:600;cursor:pointer;')}>取消</button>
                  <button onClick={confirm} disabled={!canConfirm} style={SS('padding:11px 20px;border:1px solid transparent;border-radius:10px;background:' + (canConfirm ? 'var(--accent)' : 'var(--fg-4)') + ';color:var(--surface);font-size:13px;font-weight:700;cursor:' + (canConfirm ? 'pointer' : 'not-allowed') + ';opacity:' + (canConfirm ? '1' : '.6') + ';display:flex;align-items:center;gap:7px;')}><Icon name="ShieldCheck" size={14} />{cf.busy ? '执行中…' : '确认执行'}</button>
                </>)}
                {isReceipt && (<>
                  {spec.rev === 'pos' && (<button onClick={revert} style={SS('padding:11px 18px;border:1px solid var(--border);border-radius:10px;background:var(--surface);color:var(--fg);font-size:13px;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:7px;')}><Icon name="RotateCcw" size={14} />改回去</button>)}
                  <button onClick={() => setCf(null)} style={SS('padding:11px 20px;border:1px solid transparent;border-radius:10px;background:var(--accent);color:var(--surface);font-size:13px;font-weight:700;cursor:pointer;')}>完成</button>
                </>)}
              </div>
            </div>
          </div>
        );
      })()}
    </div>
  );
}

window.KitShopee = KitShopee;
