﻿// MessagesPage - redesigned v2

const { useState, useEffect, useRef } = React;

var h = React.createElement;

var MSG_STATUS_MAP = {
  10: '订单待支付，请尽快完成支付',
  20: '交易已创建，请双方确认交易',
  30: '正在验号中，请按流程完成账号验证',
  40: '验号已通过，等待发起换绑',
  50: '正在换绑中，请及时提交验证码',
  60: '交易进入审核期，请等待',
  70: '等待买家确认交易完成',
  80: '交易已完成，款项已结算',
  90: '交易已暂停，等待平台处理',
  100: '订单正在平台仲裁中',
  110: '平台已完成退款处理',
  120: '订单已取消'
};

var PAGE_BG = '#F8FAFC';

function MessagesPage() {


  var _orders = useState([]); var orders = _orders[0], setOrders = _orders[1];
  var _allConvs = useState([]); var allConvs = _allConvs[0], setAllConversations = _allConvs[1];
  var _notices = useState([]); var notices = _notices[0], setNotices = _notices[1];
  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _initLoading = useState(true); var initLoading = _initLoading[0], setInitLoading = _initLoading[1];
  var _showNotices = useState(false); var showNotices = _showNotices[0], setShowNotices = _showNotices[1];
  var _supportConversations = useState([]); var supportConversations = _supportConversations[0], setSupportConversations = _supportConversations[1];
  var _buyerBoosterConversations = useState([]); var buyerBoosterConversations = _buyerBoosterConversations[0], setBuyerBoosterConversations = _buyerBoosterConversations[1];
  var _escortServiceConversations = useState([]); var escortServiceConversations = _escortServiceConversations[0], setEscortServiceConversations = _escortServiceConversations[1];
  var _imLoading = useState(false); var imLoading = _imLoading[0], setImLoading = _imLoading[1];
  var imRefreshTimerRef = useRef(null);
  var msgPageSocketCleanupRef = useRef(null);
  var msgPageRefreshInFlightRef = useRef(false);
  var _presaleAftersaleConv = useState(null); var presaleAftersaleConv = _presaleAftersaleConv[0], setPresaleAftersaleConv = _presaleAftersaleConv[1];

  function loadImConversations() {
    if (!NK.Api.Im) return;
    setImLoading(true);
    NK.Api.Im.conversations({}).then(function(res) {
      if (res.code === 0) {
        var all = res.data || [];
        // Find presale-service or support type as presale entry (first)
        var presaleConvs = all.filter(function(c) { return c.type === 'presale_service' || c.type === 'support' || c.type === 'escort_consult'; });
        var escortServiceConvs = all.filter(function(c) { return c.type === 'escort_presale' || c.type === 'escort_random_presale' || c.type === 'escort_order'; });
        var buyerBoosterConvs = all.filter(function(c) {
          return c.type === 'buyer_booster' && c.current_member_role === 'buyer';
        });
        setSupportConversations(presaleConvs);
        setEscortServiceConversations(escortServiceConvs);
        setBuyerBoosterConversations(buyerBoosterConvs);
        // Find aftersale-service as aftersale entry
        var aftersaleConvs = all.filter(function(c) { return c.type === 'aftersale_service' || c.type === 'account_after_sale' || c.type === 'escort_after_sale'; });
        setPresaleAftersaleConv(aftersaleConvs.length > 0 ? aftersaleConvs[0] : null);
      } else {
        setSupportConversations([]);
        setEscortServiceConversations([]);
        setBuyerBoosterConversations([]);
        setPresaleAftersaleConv(null);
      }
    }).catch(function() { setSupportConversations([]); setEscortServiceConversations([]); setBuyerBoosterConversations([]); setPresaleAftersaleConv(null); }).finally(function() { setImLoading(false); });
  }
  function initMsgPageSocket() {
    if (typeof NK.UserImSocket === "undefined") return;
    var token = (NK.Api && NK.Api.getToken) ? NK.Api.getToken() : "";
    if (!token) return;
    NK.UserImSocket.connect(token);

    if (msgPageSocketCleanupRef.current) {
      msgPageSocketCleanupRef.current();
      msgPageSocketCleanupRef.current = null;
    }

    var offConvUpdated = NK.UserImSocket.on("im:conversation_updated", function() {
      if (msgPageRefreshInFlightRef.current) return;
      msgPageRefreshInFlightRef.current = true;
      loadImConversations();
    });

    var offUnreadUpdated = NK.UserImSocket.on("im:unread_updated", function() {
      if (msgPageRefreshInFlightRef.current) return;
      msgPageRefreshInFlightRef.current = true;
      loadImConversations();
    });

    msgPageSocketCleanupRef.current = function() {
      offConvUpdated();
      offUnreadUpdated();
    };

    if (NK.UserImSocket.isConnected()) {
      msgPageRefreshInFlightRef.current = true;
      loadImConversations();
    }
  }

  function fetchAll() {

    if (!NK.Store.isLoggedIn()) { setInitLoading(false); setLoading(false); return; }
    setLoading(true);
    try {
      var results = Promise.allSettled([
        NK.Api.Orders.myBuy({ page: 1, pageSize: 50 }),
        NK.Api.Orders.mySell({ page: 1, pageSize: 50 }),
        NK.Api.Accounts.my({ page: 1, pageSize: 50 }),
        NK.Api.Bargains.buyerList(),
        NK.Api.Bargains.sellerList()
      ,
      // [COMMENTED OUT conversations buyer]

      // [COMMENTED OUT conversations booster]
        NK.Api.Booster.userDynamicMessages()]);
      results.then(function (r) {
        var orderMap = {};
        [r[0], r[1]].forEach(function (x) {
          if (x.status === 'fulfilled' && x.value.code === 0) {
            (x.value.data.list || []).forEach(function (o) {
              if (!orderMap[o.id]) orderMap[o.id] = o;
            });
          }
        });
        var merged = Object.values(orderMap);
        merged.sort(function (a, b) {
          var ta = a.update_time || a.create_time || '';
          var tb = b.update_time || b.create_time || '';
          return tb.localeCompare(ta);
        });
        setOrders(merged);

        // Merge bargains into conversations
        var bargainItems = [];
        [r[3], r[4]].forEach(function (x) {
          if (x.status === 'fulfilled' && x.value.code === 0) {
            (x.value.data.list || []).forEach(function (b) {
              var role = b.buyer_id === (NK.Store.get('user') || {}).id ? 'buyer' : 'seller';
              var summary = '';
              if (b.status === 'pending') summary = '买家出价 ¥' + Number(b.offer_price).toFixed(2) + '，等待卖家回复';
              else if (b.status === 'accepted') summary = '卖家已同意出价，请尽快支付';
              else if (b.status === 'rejected') summary = '卖家已拒绝本次出价';
              else if (b.status === 'countered') summary = '卖家还价 ¥' + Number(b.counter_price).toFixed(2) + '，等待确认';
              else if (b.status === 'buyer_accepted') summary = '已达成，请尽快支付';
              else if (b.status === 'cancelled') summary = '砍价已取消';
              else if (b.status === 'expired') summary = '砍价已过期';
              else summary = '砍价状态: ' + b.status;
              bargainItems.push({
                id: 'bargain-' + b.id,
                type: 'bargain',
                bargainId: b.id,
                accountId: b.account_id,
                title: b.title || '',
                coverImage: b.coverImage || '',
                originalPrice: b.original_price,
                offerPrice: b.offer_price,
                counterPrice: b.counter_price,
                status: b.status,
                summary: summary,
                time: b.updated_at || b.created_at,
                role: role
              });
            });
          }
        });
        // Merge bargain items into orders (as conversation items)
        var allConvs = merged.map(function(o) {
          return Object.assign({}, o, { type: 'order', time: o.update_time || o.create_time || '' });
        }).concat(bargainItems);
        allConvs.sort(function(a, b) { return (b.time || '').localeCompare(a.time || ''); });
        setAllConversations(allConvs);

        var sysNotices = [];
        merged.forEach(function (o) {
          var s = o.status;
          if (s === 80 || s === 110 || s === 120) {
            sysNotices.push({
              id: 'order-' + o.id,
              type: s === 80 ? 'done' : s === 110 ? 'refund' : 'cancel',
              text: MSG_STATUS_MAP[s],
              title: o.title || ('订单#' + (o.order_no || o.id)),
              time: o.update_time || o.create_time,
              orderId: o.id
            });
          }
        });

        if (r[2].status === 'fulfilled' && r[2].value.code === 0) {
          (r[2].value.data.list || []).forEach(function (p) {
            var s = p.status;
            if (s === 0) {
              sysNotices.push({
                id: 'prod-' + p.id + '-pending',
                type: 'pending',
                text: '商品"' + p.title + '"已提交审核，请等待平台处理',
                title: '发布待审核',
                time: p.create_time,
                productId: p.id
              });
            } else if (s === 1) {
              sysNotices.push({
                id: 'prod-' + p.id + '-approved',
                type: 'approved',
                text: '你的账号"' + p.title + '"已审核通过并上架',
                title: '审核通过',
                time: p.update_time || p.create_time,
                productId: p.id
              });
            } else if (s === 2) {
              sysNotices.push({
                id: 'prod-' + p.id + '-rejected',
                type: 'rejected',
                text: '你的账号"' + p.title + '"审核未通过' + (p.audit_reason ? ('，原因：' + p.audit_reason) : ''),
                title: '审核拒绝',
                time: p.update_time || p.create_time,
                productId: p.id
              });
            }
          });
        }
        // Merge dynamic interaction notifications
        try {
          var dynResults = r[r.length - 1];
          if (dynResults.status === 'fulfilled' && dynResults.value.code === 0) {
            (dynResults.value.data.list || []).forEach(function(dm) {
              sysNotices.push({
                id: 'dyn-' + dm.id,
                type: dm.type || 'dynamic_reply',
                title: '动态互动通知',
                text: (dm.fromUserName || '用户') + ' 回复了你的评论：' + (dm.content || ''),
                subText: '动态：' + (dm.dynamicTitle || dm.dynamicContent || '-'),
                time: dm.createdAt,
                dynamicId: dm.dynamicId,
                commentId: dm.commentId,
                fromUserName: dm.fromUserName
              });
            });
          }
        } catch(e) {}
        sysNotices.sort(function (a, b) { return (b.time || '').localeCompare(a.time || ''); });
        setNotices(sysNotices);
      }).catch(function (e) { console.error("[MessagesPage] escort/bargain processing error:", e); }).finally(function () { setLoading(false); setInitLoading(false); });
    } catch (e) { setLoading(false); setInitLoading(false); }
  }

  React.useEffect(function () {

    loadImConversations();
  }, []);

  React.useEffect(function () {

    fetchAll();
  }, []);

  // Watchdog: force stop loading after 5 seconds
  
  // Auto-refresh IM conversations every 5s
  React.useEffect(function() {
    function doRefresh() {
      msgPageRefreshInFlightRef.current = false;
      loadImConversations();
    }
    doRefresh();
    imRefreshTimerRef.current = setInterval(doRefresh, 5000);

    initMsgPageSocket();

    return function() {
      if (imRefreshTimerRef.current) {
        clearInterval(imRefreshTimerRef.current);
        imRefreshTimerRef.current = null;
      }
      if (msgPageSocketCleanupRef.current) {
        msgPageSocketCleanupRef.current();
        msgPageSocketCleanupRef.current = null;
      }
    };
  }, []);
  React.useEffect(function () {

    var watchdogTimer = setTimeout(function () {

      setLoading(false);
      setInitLoading(false);
    }, 5000);

    return function () {
      clearTimeout(watchdogTimer);
    };
  }, []);

  function fmtTime(t) {
    if (!t) return '';
    var d = new Date(t);
    var now = new Date();
    var diff = now - d;
    if (diff < 60000) return '刚刚';
    if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
    if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
    if (diff < 172800000) return '昨天';
    return d.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
  }

  // Not logged in
  if (!NK.Store.isLoggedIn()) {
    return h('div', { className: 'detail-page', style: { background: PAGE_BG } },
      h('div', { className: 'back-header' },
        h('div', { className: 'btitle', style: { flex: 1, textAlign: 'center' } }, '消息')
      ),
      h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', paddingTop: 100 } },
        h('div', { style: { width: 64, height: 64, borderRadius: '50%', background: '#e6f4ff', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 } },
          h('span', { style: { fontSize: 28 } }, '🔒')
        ),
        h('div', { style: { fontSize: 15, color: '#999' } }, '请先登录后查看消息')
      )
    );
  }

  
  // Error state - show before loading so errors are visible
  


  // Safe array guards
  var safeAllConvs = Array.isArray(allConvs) ? allConvs : [];
  var safeSupportConversations = Array.isArray(supportConversations) ? supportConversations : [];
  var safeBuyerBoosterConversations = Array.isArray(buyerBoosterConversations) ? buyerBoosterConversations : [];
  var safeEscortServiceConversations = Array.isArray(escortServiceConversations) ? escortServiceConversations : [];
  var safeNotices = Array.isArray(notices) ? notices : [];

  // Avatar colors for trade messages
  var suijiImages = ['/official/assets/xiaoxi/suiji/yisixiao.jpg', '/official/assets/xiaoxi/suiji/2bb8038f59745bb02a454275c8a94f36.jpg', '/official/assets/xiaoxi/suiji/495751aad8783a2191f413111c345698.jpg', '/official/assets/xiaoxi/suiji/49f01631b1832d2bd5aa25662aed5fe6.jpg', '/official/assets/xiaoxi/suiji/58a193b900fb5284268ffe5d9588c77a.jpg', '/official/assets/xiaoxi/suiji/e6f52c9786e710e2c01b06b59f554080.jpg', '/official/assets/xiaoxi/suiji/f5fa3b1dbfef6b9038d06f63058d974f.jpg'];
  function stableIcon(id, idx) { var hash = 0; var str = String(id || idx); for (var i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i); hash |= 0; } return suijiImages[Math.abs(hash) % suijiImages.length]; }

  // System notices standalone page
  if (showNotices) {
    return h('div', { className: 'detail-page', style: { display: 'flex', flexDirection: 'column', height: '100vh', background: '#F8FAFC' } },
      h('div', { style: { flexShrink: 0, background: '#fff', padding: '0 16px', height: 52, display: 'flex', alignItems: 'center', position: 'relative', boxShadow: '0 1px 2px rgba(0,0,0,0.04)' } },
        h('div', { onClick: function(){ setShowNotices(false); }, style: { width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', fontSize: 20, color: '#475569', flexShrink: 0 } }, NK.BackIcon ? NK.BackIcon({size:22,color:'#475569'}) : '←'),
        h('div', { style: { position: 'absolute', left: '50%', transform: 'translateX(-50%)', fontSize: 17, fontWeight: 700, color: '#1E293B' } }, '系统通知')
      ),
      h('div', { style: { flex: 1, overflowY: 'auto', padding: '12px' } },
        notices.length === 0 ?
          h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 80 } },
            h('div', { style: { width: 72, height: 72, borderRadius: '50%', background: '#F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 } },
              h('span', { style: { fontSize: 32 } }, '🔔')
            ),
            h('div', { style: { fontSize: 15, fontWeight: 600, color: '#1E293B', marginBottom: 6 } }, '暂无系统通知'),
            h('div', { style: { fontSize: 12, color: '#94A3B8' } }, '审核结果和完成订单会在这里通知')
          ) :
          h('div', null, notices.map(function (n) {
            var typeColors = {
              done: { bg: '#e6ffe6', icon: '✅' },
              refund: { bg: '#fff0e6', icon: '💰' },
              cancel: { bg: '#f0f0f0', icon: '❌' },
              pending: { bg: '#fffbe6', icon: '📋' },
              approved: { bg: '#e6f4ff', icon: '🌟' },
              rejected: { bg: '#ffe6e6', icon: '⚠️' },
              dynamic_reply: { bg: '#e8f4fd', icon: '💬' },
            };
            var tc = typeColors[n.type] || { bg: '#f0f0f0', icon: '📌' };
            var hasClick = n.orderId || n.productId || n.dynamicId;
            return h('div', {
              key: n.id,
              onClick: hasClick ? function () {
                if (n.orderId) NK.Store.navigate('tradeRoom', { orderId: n.orderId, source: 'messages' });
                else if (n.productId) NK.Store.navigate('myProductDetail', { productId: n.productId });
              } : null,
              style: { display: 'flex', alignItems: 'center', padding: '16px', marginBottom: 10, background: '#fff', borderRadius: 16, cursor: hasClick ? 'pointer' : 'default', boxShadow: '0 2px 8px rgba(30,41,59,0.04)' }
            },
              h('div', { style: { width: 42, height: 42, borderRadius: '50%', background: tc.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } },
                h('span', { style: { fontSize: 18 } }, tc.icon)
              ),
              h('div', { style: { flex: 1, overflow: 'hidden', marginLeft: 12 } },
                h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 } },
                  h('div', { style: { fontSize: 14, fontWeight: 600, color: '#1E293B', flex: 1 } }, n.title),
                  h('span', { style: { fontSize: 11, color: '#94A3B8', flexShrink: 0, marginLeft: 8 } }, fmtTime(n.time))
                ),
                h('div', null,
                  h('div', { style: { fontSize: 13, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, n.text),
                  n.subText ? h('div', { style: { fontSize: 11, color: '#94A3B8', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, n.subText) : null
                )
              )
            );
          }))
      )
    );
  }

  return h('div', { className: 'detail-page', style: { background: PAGE_BG, minHeight: '100vh' } },
    // Header - clean with shadow
    h('div', { style: { background: '#fff', padding: '0 16px', height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'sticky', top: 50, zIndex: 99, boxShadow: '0 1px 3px rgba(0,0,0,0.04)' } },
      h('div', { style: { fontSize: 17, fontWeight: 700, color: '#222' } }, '消息')
    ),

    // Bargain entry card - Stitch
    h('div', { style: { padding: '14px 16px 6px' } },
      h('div', {
        onClick: function () { NK.Store.navigate('bargainList', { role: 'buyer' }); },
        style: { display: 'flex', alignItems: 'center', padding: '16px', background: '#fff', borderRadius: 16, cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)', marginBottom: 12 }
      },
        h('div', { style: { width: 46, height: 46, borderRadius: 10, overflow: 'hidden', flexShrink: 0 } },
          h('img', { src: '/official/assets/xiaoxi/kanjia.jpg', alt: '', style: { width: '100%', height: '100%', objectFit: 'cover' }, onError: function(e) { e.target.style.display = 'none'; e.target.parentElement.style.background = '#2563EB'; } })
        ),
        h('div', { style: { flex: 1, overflow: 'hidden', marginLeft: 14 } },
          h('div', { style: { fontSize: 15, fontWeight: 700, color: '#1E293B', marginBottom: 3 } }, '砍价消息'),
          h('div', { style: { fontSize: 12, color: '#64748B', lineHeight: '17px' } }, '查看我发起和收到的砍价')
        ),
        h('div', { style: { fontSize: 22, color: '#64748B', fontWeight: 700, flexShrink: 0, marginLeft: 6 } }, '›')
      )
    ),

    // System notice entry card
    h('div', { style: { padding: '0 16px 6px' } },
      h('div', {
        onClick: function () { setShowNotices(true); },
        style: { display: 'flex', alignItems: 'center', padding: '16px', background: '#fff', borderRadius: 16, cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)', marginBottom: 12 }
      },
        h('div', { style: { width: 46, height: 46, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 } },
          h('img', { src: '/official/assets/xiaoxi/xiti.jpg', alt: '', style: { width: '100%', height: '100%', objectFit: 'cover' }, onError: function(e) { e.target.style.display = 'none'; e.target.parentElement.style.background = '#FEF3C7'; } })
        ),
        h('div', { style: { flex: 1, overflow: 'hidden', marginLeft: 14 } },
          h('div', { style: { fontSize: 15, fontWeight: 700, color: '#1E293B', marginBottom: 3 } }, '系统通知'),
          h('div', { style: { fontSize: 12, color: '#64748B', lineHeight: '17px' } }, '查看商品、订单、交易和平台通知')
        ),
        )
      ),

    // Existing platform/escort support conversations and aftersale entry
    h('div', { style: { padding: '0 16px 6px' } },
      safeSupportConversations.length > 0 ? h('div', {
        onClick: function () {
          var conversation = safeSupportConversations[0];
          NK.Store.navigate('supportChat', {
            conversationId: conversation.conversation_id || conversation.id,
            conversationData: conversation
          });
        },
        style: { display: 'flex', alignItems: 'center', padding: '16px', background: '#fff', borderRadius: 16, cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)', marginBottom: 10 }
      },
        h('div', { style: { width: 46, height: 46, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: '#e6f4ff', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
          h('span', { style: { fontSize: 20 } }, '\u{1F4AC}')
        ),
        h('div', { style: { flex: 1, overflow: 'hidden', marginLeft: 14 } },
          h('div', { style: { fontSize: 15, fontWeight: 700, color: '#1E293B', marginBottom: 4 } }, '\u5BA2\u670D\u5C0F\u5F3A \u00B7 \u62A4\u822A\u670D\u52A1'),
          h('div', { style: { fontSize: 12, color: '#64748B', lineHeight: '17px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
            safeSupportConversations.length > 0 && safeSupportConversations[0].last_message
              ? safeSupportConversations[0].last_message
              : '\u62A4\u822A\u670D\u52A1\u95EE\u9898\u53EF\u4EE5\u54A8\u8BE2\u5C0F\u5F3A'
          )
        ),
        h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between', flexShrink: 0, marginLeft: 10, minHeight: 46, gap: 4 } },
          h('span', { style: { fontSize: 11, color: '#94A3B8', flexShrink: 0, lineHeight: 1 } },
            safeSupportConversations.length > 0 && safeSupportConversations[0].last_message_at
              ? fmtTime(safeSupportConversations[0].last_message_at) : ''
          ),
          safeSupportConversations.length > 0 && safeSupportConversations[0].unread_count > 0
            ? h('div', { style: { background: '#ff4d4f', color: '#fff', fontSize: 10, borderRadius: 10, padding: '1px 6px', minWidth: 18, textAlign: 'center', lineHeight: '16px' } },
              safeSupportConversations[0].unread_count > 99 ? '99+' : String(safeSupportConversations[0].unread_count))
            : null,
          h('div', { style: { fontSize: 20, color: '#64748B', fontWeight: 700, lineHeight: 1 } }, '\u203A')
        )
      ) : null,
      // Aftersale entry - only if has conversations
      presaleAftersaleConv && presaleAftersaleConv.conversation_id ? h('div', {
        onClick: function () { NK.Store.navigate('supportChat', { conversationId: presaleAftersaleConv.conversation_id, source: 'aftersale' }); },
        style: { display: 'flex', alignItems: 'center', padding: '16px', background: '#fff', borderRadius: 16, cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)', marginBottom: 12 }
      },
        h('div', { style: { width: 46, height: 46, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: '#f0fdf4', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
          h('span', { style: { fontSize: 20 } }, '\u{1F91D}')
        ),
        h('div', { style: { flex: 1, overflow: 'hidden', marginLeft: 14 } },
          h('div', { style: { fontSize: 15, fontWeight: 700, color: '#1E293B', marginBottom: 4 } }, '\u5BA2\u670D\u5C0F\u5F3A \u00B7 \u552E\u540E\u5BA2\u670D'),
          h('div', { style: { fontSize: 12, color: '#64748B', lineHeight: '17px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
            presaleAftersaleConv.last_message
              ? presaleAftersaleConv.last_message
              : '\u6709\u8BA2\u5355\u95EE\u9898\u53EF\u4EE5\u8054\u7CFB\u5C0F\u5F3A\u5904\u7406'
          )
        ),
        h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between', flexShrink: 0, marginLeft: 10, minHeight: 46, gap: 4 } },
          h('span', { style: { fontSize: 11, color: '#94A3B8', flexShrink: 0, lineHeight: 1 } },
            presaleAftersaleConv.last_message_at
              ? fmtTime(presaleAftersaleConv.last_message_at) : ''
          ),
          presaleAftersaleConv.unread_count > 0
            ? h('div', { style: { background: '#ff4d4f', color: '#fff', fontSize: 10, borderRadius: 10, padding: '1px 6px', minWidth: 18, textAlign: 'center', lineHeight: '16px' } },
              presaleAftersaleConv.unread_count > 99 ? '99+' : String(presaleAftersaleConv.unread_count))
            : null,
          h('div', { style: { fontSize: 20, color: '#64748B', fontWeight: 700, lineHeight: 1 } }, '\u203A')
        )
      ) : null,
    ),
    safeEscortServiceConversations.length > 0 ? h('div', { style: { padding: '0 16px 6px' } },
      h('div', { style: { fontSize: 13, fontWeight: 700, color: '#475569', margin: '2px 2px 8px' } }, '护航服务咨询'),
      safeEscortServiceConversations.map(function(c) {
        var convId = Number(c.conversation_id || c.id || 0);
        var title = c.display_title || c.title || (c.type === 'escort_random_presale' ? '客服小强' : '护航服务');
        var avatar = c.avatar || c.peer_avatar || '';
        var lastMessage = c.last_message_type === 'image' ? '[图片]' : (c.last_message || '暂无消息');
        return h('div', {
          key: 'escort-im-' + convId,
          onClick: function() {
            if (!convId) { alert('会话参数无效，请刷新后重试'); return; }
            NK.Store.navigate('supportChat', { conversationId: convId, conversationData: c });
          },
          style: { display: 'flex', alignItems: 'center', padding: '14px 16px', marginBottom: 10, background: '#fff', borderRadius: 14, border: '1px solid #DCEBE8', cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)' }
        },
          avatar ? h('img', { src: avatar, alt: '', style: { width: 46, height: 46, borderRadius: '50%', objectFit: 'cover', flexShrink: 0, background: '#E2E8F0' } }) : h('div', { style: { width: 46, height: 46, borderRadius: '50%', flexShrink: 0, background: '#DDF4F1', color: '#0F766E', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 700 } }, String(title).charAt(0)),
          h('div', { style: { flex: 1, minWidth: 0, marginLeft: 12 } },
            h('div', { style: { fontSize: 15, fontWeight: 700, color: '#1E293B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, title),
            h('div', { style: { marginTop: 3, fontSize: 12, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, (c.source_label || '护航服务咨询') + ' · ' + lastMessage)
          ),
          h('span', { style: { fontSize: 11, color: '#94A3B8', flexShrink: 0, marginLeft: 8 } }, fmtTime(c.last_message_at || c.updated_at))
        );
      })
    ) : null,
    safeBuyerBoosterConversations.length > 0 ? h('div', { style: { padding: '0 16px 6px' } },
      h('div', { style: { fontSize: 13, fontWeight: 700, color: '#475569', margin: '2px 2px 8px' } }, '打手私信'),
      safeBuyerBoosterConversations.map(function(c) {
        var convId = Number(c.conversation_id || c.id);
        var peerName = c.peer_nickname || c.display_title || c.title || '打手';
        var peerAvatar = c.peer_avatar || c.avatar || '';
        var latestOrder = c.latestOrder || null;
        var orderId = Number(c.orderId || (latestOrder && latestOrder.orderId));
        var boosterId = Number(c.boosterUserId || c.booster_user_id);
        var unreadCount = Number(c.unread_count || 0);
        var lastMessage = c.last_message_type === 'image' ? '[图片]' : (c.last_message || '暂无消息');
        return h('div', {
          key: 'buyer-booster-' + (c.conversation_id || c.id || peerName),
          onClick: function() {
            if (!convId || isNaN(convId)) { alert('会话参数无效，请刷新后重试'); return; }
            var chatParams = {
              conversationId: convId,
              boosterUserId: boosterId || null,
              latestOrder: latestOrder,
              role: 'buyer',
              source: 'messages'
            };
            if (orderId && !isNaN(orderId)) chatParams.orderId = orderId;
            NK.Store.navigate('escortOrderChat', chatParams);
          },
          style: { display: 'flex', alignItems: 'center', padding: '14px 16px', marginBottom: 10, background: '#fff', borderRadius: 14, border: '1px solid #E8EEF3', cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)' }
        },
          peerAvatar
            ? h('img', { src: peerAvatar, alt: '', style: { width: 46, height: 46, borderRadius: '50%', objectFit: 'cover', flexShrink: 0, background: '#E2E8F0' }, onError: function(e) { e.target.style.display = 'none'; } })
            : h('div', { style: { width: 46, height: 46, borderRadius: '50%', flexShrink: 0, background: '#DDF4F1', color: '#0F766E', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 700 } }, String(peerName || '?').charAt(0)),
          h('div', { style: { flex: 1, minWidth: 0, marginLeft: 12 } },
            h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 4 } },
              h('div', { style: { flex: 1, minWidth: 0, fontSize: 15, fontWeight: 700, color: '#1E293B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, peerName),
              h('span', { style: { flexShrink: 0, fontSize: 11, color: '#94A3B8' } }, fmtTime(c.last_message_at || c.updated_at))
            ),
            h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
              h('div', { style: { flex: 1, minWidth: 0, fontSize: 13, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, lastMessage),
              unreadCount > 0 ? h('span', { style: { flexShrink: 0, minWidth: 18, height: 18, padding: '0 5px', borderRadius: 9, background: '#EF4444', color: '#fff', fontSize: 10, lineHeight: '18px', textAlign: 'center' } }, unreadCount > 99 ? '99+' : String(unreadCount)) : null
            )
          )
        );
      })
    ) : null,
    // Content area
    h('div', { style: { padding: '0 12px' } },

      
// Trade messages
      (!Array.isArray(allConvs) || allConvs.length === 0) ?
          h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 60, paddingBottom: 40 } },
            h('div', { style: { width: 72, height: 72, borderRadius: '50%', background: '#e6f4ff', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 } },
              h('span', { style: { fontSize: 32 } }, '💬')
            ),
            h('div', { style: { fontSize: 15, fontWeight: 600, color: '#1E293B', marginBottom: 6 } }, '暂无交易消息'),
            h('div', { style: { fontSize: 12, color: '#bbb' } }, '发布商品或购买后这里会有消息'),
            h('div', {
              style: { marginTop: 16, padding: '8px 24px', borderRadius: 20, background: '#1677ff', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' },
              onClick: function () { NK.Store.navigate('home'); }
            }, '去首页逛逛')
          ) :
          h('div', null, (Array.isArray(allConvs) ? allConvs : []).filter(function(o) { return o.type !== 'bargain'; }).map(function (o, idx) {
            var isBuy = o.buyer_id === (NK.Store.get('user') || {}).id || false;
            var iconSrc = stableIcon(o.id, idx);
            return h('div', {
              key: o.id,
              onClick: function () { if (o.type === 'bargain') { NK.Store.navigate('bargainSession', { id: o.bargainId }); } else { NK.Store.navigate('tradeRoom', { orderId: o.id, source: 'messages' }); } },
              style: {
                display: 'flex', alignItems: 'center', padding: '16px', marginBottom: 10, background: '#fff',
                borderRadius: 16, cursor: 'pointer', boxShadow: '0 2px 8px rgba(30,41,59,0.04)',
                transition: 'box-shadow .2s'
              }
            },
              h('div', { style: { width: 44, height: 44, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 } },
                h('img', { src: iconSrc, alt: '', style: { width: '100%', height: '100%', objectFit: 'cover' }, onError: function(e) { e.target.style.display = 'none'; e.target.parentElement.style.background = '#e6f4ff'; } })
              ),
              h('div', { style: { flex: 1, overflow: 'hidden', marginLeft: 12 } },
                h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 } },
                  h('div', { style: { fontSize: 15, fontWeight: 600, color: '#1E293B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 } },
                    (o.type === 'bargain' ? '砍价会话｜' + (o.title || '') : '交易客服-订单' + (o.order_no || ('#' + o.id)))
                  ),
                  h('span', { style: { fontSize: 11, color: '#94A3B8', flexShrink: 0, marginLeft: 8 } }, fmtTime(o.update_time || o.create_time))
                ),
                h('div', { style: { fontSize: 13, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
                  (o.type === 'bargain' ? o.summary : MSG_STATUS_MAP[o.status] || ('订单状态: ' + o.status))
                ),
                h('div', { style: { fontSize: 11, color: '#94A3B8', marginTop: 3 } },
                  (o.type === 'bargain' ? (o.role === 'buyer' ? '我发起的砍价' : '收到的砍价') : (isBuy ? '我买到的' : '我卖出的') + ' · ' + (o.title || '')))
              ),
              null
            );
          })),

      // Loading overlay for refresh
      loading && !initLoading ?
        h('div', { style: { textAlign: 'center', padding: 12, color: '#94A3B8', fontSize: 12 } }, '刷新中...') : null
    )
  );
}

window.NK = window.NK || {};
NK.MessagesPage = MessagesPage;





