﻿// 砍价会话页面
const { useState, useEffect } = React;

function BargainSessionPage() {
  var h = React.createElement;
function svgArrL(c){return h('svg',{width:20,height:20,viewBox:'0 0 24 24',fill:'none',stroke:c||'#334155',strokeWidth:1.875,strokeLinecap:'round',strokeLinejoin:'round'},h('path',{d:'M15 18l-6-6 6-6'}));}

  var pp = NK.Store.get("pageParams") || {};
  var bid = pp.id;
  var _data = useState(null); var data = _data[0], setData = _data[1];
  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _error = useState(''); var error = _error[0], setError = _error[1];
  var _acting = useState(false); var acting = _acting[0], setActing = _acting[1];
  var _counterPrice = useState(''); var counterPrice = _counterPrice[0], setCounterPrice = _counterPrice[1];
  var _reofferPrice = useState(''); var reofferPrice = _reofferPrice[0], setReofferPrice = _reofferPrice[1];
  var _reofferMsg = useState(''); var reofferMsg = _reofferMsg[0], setReofferMsg = _reofferMsg[1];
  var _toast = useState(''); var toast = _toast[0], setToast = _toast[1];
  var _showCounter = useState(false); var showCounter = _showCounter[0], setShowCounter = _showCounter[1];
  var _showReoffer = useState(false); var showReoffer = _showReoffer[0], setShowReoffer = _showReoffer[1];
  var _pollingRef = React.useRef(false);
  var _modifyVisible = useState(false); var modifyVisible = _modifyVisible[0], setModifyVisible = _modifyVisible[1];
  var _modifyPrice = useState(""); var modifyPrice = _modifyPrice[0], setModifyPrice = _modifyPrice[1];
  var _modifyMsg = useState(""); var modifyMsg = _modifyMsg[0], setModifyMsg = _modifyMsg[1];
  var _quickModifyIdx = useState(0); var quickModifyIdx = _quickModifyIdx[0], setQuickModifyIdx = _quickModifyIdx[1];
  var _offerModalMode = useState("modify"); var offerModalMode = _offerModalMode[0], setOfferModalMode = _offerModalMode[1];
  var _msgCount = React.useRef(0);
  var _scrollRef = React.useRef(null);

  function load(silent){
    if (!bid) return;
    if (_pollingRef.current) return;
    if (!silent) setLoading(true);
    _pollingRef.current = true;
    NK.Api.Bargains.detail(bid).then(function(r){
      if (r && r.code === 0) {
        setData(r.data);
        if (!silent) setError('');
        var newCount = (r.data.messages && r.data.messages.length) || 0;
        if (newCount > _msgCount.current) {
          _msgCount.current = newCount;
          setTimeout(function(){
            if (_scrollRef.current) {
              _scrollRef.current.scrollTop = _scrollRef.current.scrollHeight;
            }
          }, 100);
        }
      } else if (!silent) {
        setError((r&&r.message)||'加载失败');
      }
    }).catch(function(){
      if (!silent) setError('网络错误');
    }).finally(function(){
      _pollingRef.current = false;
      if (!silent) setLoading(false);
    });
  }

  useEffect(function(){
    if (!bid) return;
    load();
    var interval = setInterval(function(){ load(true); }, 3000);
    return function(){ clearInterval(interval); };
  }, [bid]);

  React.useEffect(function(){
    if (!toast) return;
    var t = setTimeout(function(){ setToast(''); }, 2000);
    return function(){ clearTimeout(t); };
  }, [toast]);

  // Loading state
  if (loading) return h("div",{style:{background:"#f7f7f7",minHeight:"100vh"}},
    h("div",{style:{position:"sticky",top:0,zIndex:10,background:"#f7f7f7",padding:"16px 16px 8px",display:"flex",alignItems:"center",gap:8}},
      h("div",{onClick:function(){NK.Store.back("home");},style:{padding:4,cursor:"pointer",fontSize:20,color:"#333",lineHeight:1}},svgArrL()),
      h("div",null,h("div",{style:{fontSize:18,fontWeight:700}},"砍价会话"))
    ),
    h("div",{style:{textAlign:"center",padding:40,color:"#999"}},"加载中...")
  );

  // Empty/error state
  if (!data) return h("div",{style:{background:"#f7f7f7",minHeight:"100vh"}},
    h("div",{style:{position:"sticky",top:0,zIndex:10,background:"#f7f7f7",padding:"16px 16px 8px",display:"flex",alignItems:"center",gap:8}},
      h("div",{onClick:function(){NK.Store.back("home");},style:{padding:4,cursor:"pointer",fontSize:20,color:"#333",lineHeight:1}},svgArrL()),
      h("div",null,h("div",{style:{fontSize:18,fontWeight:700}},"砍价会话"))
    ),
    h("div",{style:{textAlign:"center",padding:40}},h("div",{style:{color:"#999"}},error || "暂无数据"))
  );

  var bargain = data.bargain;
  var messages = data.messages || [];
  var role = (NK.Store.get("user") && NK.Store.get("user").id === bargain.buyer_id) ? "buyer" : "seller";
  var statusLabels = { pending:"等待卖家回复", awaiting_payment:"等待买家支付", accepted:"已生成待支付订单", rejected:"卖家已拒绝", countered:"卖家已还价", buyer_accepted:"买家已接受", paid_success:"砍价成功", cancelled:"已取消", expired:"已过期" };
  var statusColors = { pending:"#fa8c16", awaiting_payment:"#1677ff", accepted:"#fa8c16", rejected:"#ff7875", countered:"#1677ff", buyer_accepted:"#52c41a", paid_success:"#52c41a", cancelled:"#999", expired:"#999" };
  var coverImg = bargain.coverImage || '';


  // Compute modification count and latest buyer offer index
  var modCount = 0;
  var latestBuyerOfferIdx = -1;
  messages.forEach(function(m, idx){
    if (m.sender_role === "buyer" && m.message_type === "reoffer") modCount++;
    if (m.sender_role === "buyer" && (m.message_type === "offer" || m.message_type === "reoffer")) latestBuyerOfferIdx = idx;
  });
  var latestSellerCounterIdx = -1;
  messages.forEach(function(m, idx){ if(m.sender_role === "seller" && m.message_type === "counter") latestSellerCounterIdx = idx; });
  var hasSellerCounter = latestSellerCounterIdx >= 0;
  function doAction(fn, label){
    if (acting) return;
    setActing(true); setError('');
    fn().then(function(r){
      if (r && r.code === 0){ setToast(label + "成功"); load(); setShowCounter(false); setShowReoffer(false); }
      else setError((r&&r.message)||'操作失败');
    }).catch(function(){ setError('网络错误'); }).finally(function(){ setActing(false); });
  }

  function sellerAccept(){ doAction(function(){ return NK.Api.Bargains.accept(bid); }, "已同意"); }
  function sellerReject(){ doAction(function(){ return NK.Api.Bargains.reject(bid); }, "已拒绝"); }
  function sellerCounter(){
    var cp = parseFloat(counterPrice);
    if (isNaN(cp) || cp <= parseFloat(bargain.offer_price) || cp > parseFloat(bargain.original_price)) {
      setError('请输入有效的还价金额'); return;
    }
    doAction(function(){ return NK.Api.Bargains.counter(bid, {counterPrice: cp}); }, "已还价");
  }
  function buyerAccept(){ doAction(function(){ return NK.Api.Bargains.buyerAccept(bid); }, "已接受"); }
  function buyerPay(){
    if (acting) return;
    setActing(true); setError("");
    NK.Api.Bargains.pay(bid).then(function(r){
      if (r && r.code === 0){
        NK.Store.navigate("payment",{orderId:r.data.orderId});
      } else setError((r&&r.message)||'操作失败');
    }).catch(function(){ setError('网络错误'); }).finally(function(){ setActing(false); });
  }
  function buyerCancel(){ doAction(function(){ return NK.Api.Bargains.cancel(bid); }, "已取消"); }
  function buyerReoffer(){
    var rp = parseFloat(reofferPrice);
    if (isNaN(rp) || rp <= 0 || rp >= parseFloat(bargain.original_price)) {
      setError('请输入有效的出价金额'); return;
    }
    doAction(function(){ return NK.Api.Bargains.reoffer(bid, {offerPrice: rp, message: reofferMsg}); }, "提交中");
  }

  var quickModifyMsgs = [
    '很喜欢这个号，您看这个价格方便出吗？',
    '朋友，价格跟预期有差距，能砍点价不？',
    '诚心想买，如果这个价格可以我就直接拍下。',
    '预算有限，您看还能再优惠一点吗？'
  ];
  var sellerQuickMsgs = [
    "\u8FD9\u4E2A\u4EF7\u683C\u5DF2\u7ECF\u5F88\u6709\u8BDA\u610F\u4E86\uFF0C\u54B1\u4EEC\u5404\u9000\u4E00\u6B65\u5427~",
    "\u53F7\u51B5\u548C\u914D\u7F6E\u90FD\u4E0D\u9519\uFF0C\u8FD9\u4E2A\u4EF7\u683C\u6210\u4EA4\u6211\u4E5F\u6BD4\u8F83\u80FD\u63A5\u53D7\u3002",
    "\u8001\u677F\u4F60\u597D\uFF0C\u8FD9\u4E2A\u4EF7\u683C\u518D\u8BA9\u4E00\u70B9\u5C31\u6BD4\u8F83\u96BE\u4E86\uFF0C\u53EF\u4EE5\u8003\u8651\u4E00\u4E0B~",
    "\u8FD9\u4E2A\u53F7\u6295\u5165\u4E0D\u5C11\uFF0C\u8FD9\u4E2A\u8FD8\u4EF7\u5DF2\u7ECF\u6BD4\u8F83\u63A5\u8FD1\u6211\u7684\u5FC3\u7406\u4EF7\u4E86\u3002",
    "\u5982\u679C\u4F60\u80FD\u5C3D\u5FEB\u4ED8\u6B3E\uFF0C\u8FD9\u4E2A\u4EF7\u683C\u6211\u53EF\u4EE5\u4F18\u5148\u7ED9\u4F60\u7559\u7740\u3002"
  ];
  function cycleModifyMsg(){
    var pool = offerModalMode === "sellerCounter" ? sellerQuickMsgs : quickModifyMsgs;
    var next = (quickModifyIdx + 1) % pool.length;
    setQuickModifyIdx(next);
    setModifyMsg(pool[next]);
  }
  function openModifyModal(){
    setOfferModalMode("modify");
    setModifyPrice(String(Math.floor(Number(bargain.offer_price)||0)));
    setModifyMsg(quickModifyMsgs[0]);
    setQuickModifyIdx(0);
    setModifyVisible(true);
  }
  function closeModifyModal(){
    setModifyVisible(false);
  }
  function openReofferModal(){
    setOfferModalMode("reoffer");
    setModifyPrice(String(Math.floor(Number(bargain.counter_price||bargain.offer_price)||0)));
    setModifyMsg(quickModifyMsgs[0]);
    setQuickModifyIdx(0);
    setModifyVisible(true);
  }
  function openSellerCounterModal(){
    setOfferModalMode("sellerCounter");
    setModifyPrice(String(Math.floor(Number(bargain.offer_price||bargain.counter_price)||0)));
    setModifyMsg(sellerQuickMsgs[0]);
    setQuickModifyIdx(0);
    setModifyVisible(true);
  }
  function confirmModifyOffer(){
    if (acting) return;
    var rp = parseFloat(modifyPrice);
    var op = parseFloat(bargain.original_price);
    if (isNaN(rp) || rp <= 0 || rp >= op) {
      setError('请输入有效的出价金额'); return;
    }
    setActing(true); setError('');
    if (offerModalMode === "sellerCounter") {
      if (bargain.status !== "pending") { setError("\u5F53\u524D\u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF08\u72B6\u6001\uFF1A" + bargain.status + "\uFF09"); setActing(false); return; }
      NK.Api.Bargains.counter(bid, {counterPrice: Math.round(rp*100)/100, message: modifyMsg}).then(function(r){
        if (r && r.code === 0){
          setToast('已提交还价'); setModifyVisible(false); load();
        } else setError((r&&r.message)||'操作失败');
      }).catch(function(){ setError('网络错误'); }).finally(function(){ setActing(false); });
    } else {
      NK.Api.Bargains.reoffer(bid, {offerPrice: Math.round(rp*100)/100, message: modifyMsg}).then(function(r){
        if (r && r.code === 0){
          setToast('已提交新出价'); setModifyVisible(false); load();
        } else setError((r&&r.message)||'操作失败');
      }).catch(function(){ setError('网络错误'); }).finally(function(){ setActing(false); });
    }
  }

  // Render a single message bubble
  function renderMsg(m, i){
    var isMine = m.sender_role === role;
    var isSystem = m.sender_role === "system";
    var isOffer = m.message_type === "offer" || m.message_type === "reoffer";
    var isCounter = m.message_type === "counter";
    var senderLabel = m.sender_role === "buyer" ? "买家" : "卖家";
    var senderColor = m.sender_role === "buyer" ? "#1677ff" : "#fa8c16";
    var tagText = isOffer ? "出价" : (isCounter ? "还价" : "");
    // Show modify button only on buyer's own offer messages when bargain is pending
    var isStale = isMine && isOffer && i !== latestBuyerOfferIdx;
    var showModify = isMine && isOffer && bargain.status === "pending" && i === latestBuyerOfferIdx && modCount < 2 && !hasSellerCounter;
    // System: centered
    if (isSystem) {
      return h("div",{key:i,style:{display:"flex",justifyContent:"center",padding:"4px 0"}},
        h("div",{style:{fontSize:11,color:"#999",background:"#f0f0f0",padding:"4px 14px",borderRadius:10}},m.content)
      );
    }

    // My messages: right-aligned
    if (isMine) {
      var isRead = role === "buyer" ? !!m.seller_read_at : !!m.buyer_read_at;
      return h("div",{key:i,style:{display:"flex",flexDirection:"column",alignItems:"flex-end",padding:"6px 16px"}},
        h("div",{style:{width:260,minWidth:260,maxWidth:260,background:"#fff",borderRadius:"16px 16px 4px 16px",padding:"14px 16px",paddingRight:58,boxShadow:"0 1px 3px rgba(0,0,0,0.06)",border:"1px solid #f0f0f0",position:"relative",overflow:"hidden"}},
          // Label + price on same line
          h("div",{style:{display:"flex",alignItems:"baseline",gap:6,marginBottom:6}},
            h("span",{style:{fontSize:14,fontWeight:600,color:senderColor}},senderLabel + (tagText ? tagText : "")),
            m.price ? h("span",{style:{fontSize:14,fontWeight:700,color:isStale?"#ccc":"#f12c20"}},"￥" + Number(m.price).toFixed(2)) : null
          ),
          h("div",{style:{fontSize:13,color:"#555",lineHeight:1.5,wordBreak:"break-word",marginBottom:showModify?8:0}},(m.sender_role==="seller"&&isCounter?"\u8FD9\u4E2A\u771F\u4E0D\u9519\uFF0C\u5404\u9000\u4E00\u6B65\u5427":"\u5976\u53CB\u4F60\u597D\uFF01\u8FD9\u4E2A\u4EF7\u683C\u53EF\u4EE5\u51FA\u561B")),
          isStale ? h("img",{src:"/official/assets/yisixiao.jpg",style:{position:"absolute",right:8,top:6,width:50,opacity:0.68,transform:"rotate(-12deg)",pointerEvents:"none"}}) : null,
          showModify ? h("button",{onClick:function(){openModifyModal();},style:{display:"flex",alignItems:"center",justifyContent:"center",minWidth:96,height:34,borderRadius:10,border:"1px solid #1677ff",background:"#fff",color:"#1677ff",fontSize:14,fontWeight:600,cursor:"pointer",margin:"12px auto 0"}},"修改价格") : null
        ));
    }

    // Other party: left-aligned
    var showCounterActions = isCounter && role === "buyer" && bargain.status === "countered" && i === latestSellerCounterIdx;
    var showSellerActions = isOffer && role === "seller" && bargain.status === "pending" && i === latestBuyerOfferIdx;
    return h("div",{key:i,style:{display:"flex",justifyContent:"flex-start",padding:"6px 16px"}},
      h("div",{style:{width:260,minWidth:260,maxWidth:260,background:"#fff",borderRadius:"16px 16px 16px 4px",padding:"14px 16px",boxShadow:"0 1px 3px rgba(0,0,0,0.06)",border:"1px solid #f0f0f0"}},
        // Label + price on same line
        h("div",{style:{display:"flex",alignItems:"baseline",gap:6,marginBottom:(m.content||showCounterActions)?6:0}},
          h("span",{style:{fontSize:14,fontWeight:600,color:senderColor}},senderLabel + (tagText ? tagText : "")),
          m.price ? h("span",{style:{fontSize:14,fontWeight:700,color:"#f12c20"}},"￥" + Number(m.price).toFixed(2)) : null
        ),
        m.content ? h("div",{style:{fontSize:13,color:"#555",lineHeight:1.5,wordBreak:"break-word",marginBottom:(showCounterActions||showSellerActions)?8:0}},(m.sender_role==="seller"&&isCounter)?"\u8FD9\u4E2A\u771F\u4E0D\u9519\uFF0C\u5404\u9000\u4E00\u6B65\u5427":m.content) : null,
        showCounterActions ? h("div",{style:{display:"flex",gap:10}},
          h("button",{onClick:function(){openReofferModal();},style:{flex:1,height:34,borderRadius:10,border:"1px solid #1677ff",background:"#fff",color:"#1677ff",fontSize:13,fontWeight:600,cursor:"pointer"}},"\u7EE7\u7EED\u51FA\u4EF7"),
          h("button",{onClick:function(){buyerCancel();},style:{flex:1,height:34,borderRadius:10,border:"1px solid #e0e0e0",background:"#fff",color:"#999",fontSize:13,cursor:"pointer"}},"\u53D6\u6D88\u780D\u4EF7")
        ) : null,
        showSellerActions ? h("div",{style:{display:"flex",gap:8}},
          h("button",{onClick:function(){openSellerCounterModal();},style:{flex:1,height:34,borderRadius:10,border:"1px solid #1677ff",background:"#fff",color:"#1677ff",fontSize:13,fontWeight:600,cursor:"pointer"}},"\u7EE7\u7EED\u8FD8\u4EF7"),
          h("button",{onClick:function(){sellerReject();},style:{flex:1,height:34,borderRadius:10,border:"1px solid #d9d9d9",background:"#fff",color:"#666",fontSize:13,fontWeight:600,cursor:"pointer"}},"\u62D2\u7EDD\u51FA\u4EF7")
        ) : null
      )
    );
  }

  return h("div",{style:{display:"flex",flexDirection:"column",height:"100vh",background:"#f7f7f7"}},

    // === Header ===
    h("div",{style:{flexShrink:0,position:"sticky",top:0,zIndex:10,background:"#f7f7f7",padding:"16px 16px 8px",display:"flex",alignItems:"center",gap:8}},
      h("div",{onClick:function(){NK.Store.back("home");},style:{padding:4,cursor:"pointer",fontSize:20,color:"#333",lineHeight:1}},svgArrL()),
      h("div",null,
        h("div",{style:{fontSize:19,fontWeight:600,color:"#1a1a1a"}},"发起砍价" + (bargain.product_no ? " -- " + String(bargain.product_no).trim() : " -- 编号待补齐")),
        h("div",{style:{fontSize:13,color:statusColors[bargain.status]||"#999",marginTop:1}},statusLabels[bargain.status]||bargain.status)
      )
      ),
    h("div",{style:{height:3,background:"#bfdbfe",margin:"0 -16px"}}),
    // === Fixed top section (product + rules) ===
    h("div",{style:{flexShrink:0}},

      // Product card
      h("div",{onClick:function(){NK.Store.navigate("detail",{id:bargain.account_id});},style:{margin:"12px 16px 12px",padding:"12px",background:"#fff",borderRadius:16,display:"flex",gap:12,alignItems:"center",boxShadow:"0 1px 3px rgba(0,0,0,0.04)",cursor:"pointer"}},
        h("div",{style:{width:80,height:80,borderRadius:12,overflow:"hidden",flexShrink:0,background:"#f0f0f0"}},
          coverImg ? h("img",{src:coverImg,style:{width:"100%",height:"100%",objectFit:"cover"},onError:function(e){e.target.style.display="none"}}) : h("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:24,color:"#ccc"}},"☆")
        ),
        h("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",justifyContent:"center",gap:4}},
          h("div",{style:{fontSize:15,fontWeight:700,color:"#1a1a1a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},bargain.title),
          h("div",{style:{fontSize:12,color:"#999"}},bargain.server || ""),
          h("div",{style:{fontSize:18,fontWeight:700,color:"#f12c20"}},"￥ " + Number(bargain.original_price).toFixed(2))
        )
      ),

      // Rules card
      h("div",{style:{margin:"0 16px 12px",padding:"12px 14px",background:"#fff7df",border:"1px solid #f6e2a8",borderRadius:14,boxShadow:"0 1px 3px rgba(0,0,0,0.04)",position:"relative",overflow:"hidden"}},
        h("div",{style:{position:"absolute",top:-12,right:-12,width:48,height:48,background:"rgba(255,152,0,0.06)",borderRadius:"50%",pointerEvents:"none"}}),
        h("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:6}},
          h("div",{style:{width:18,height:18,borderRadius:4,background:"#fff3e0",display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,color:"#e65100",fontWeight:700}},"?"),
          h("div",{style:{fontSize:13,fontWeight:700,color:"#1a1a1a"}},"砍价公约")
        ),
        h("div",{style:{fontSize:12,color:"#999",lineHeight:1.6}},"方块号仓倡导买卖双方基于诚信原则合理议价。系统严厉打击恶意砍价行为，违规者将面临交易限制。为保障卖家权益，砍价成功后请于5小时内完成支付，感谢您的配合！")
      )
    ),

    // === Scrollable messages area ===
    h("div",{ref:_scrollRef,style:{flex:1,overflowY:"auto",padding:"0 0 16px"}},
      h("div",{style:{padding:"4px 0 8px"}},
        bargain.created_at ? h("div",{style:{textAlign:"center",marginBottom:12}},
          h("div",{style:{fontSize:13,color:"#999"}},(new Date(bargain.created_at)).toTimeString().slice(0,5)),
          h("div",{style:{fontSize:13,color:"#aaa",marginTop:4}},"\u4E70\u5BB6\u53D1\u8D77\u780D\u4EF7")
        ) : null,
        messages.length > 0
          ? messages.reduce(function(acc,m,i){ acc.push(renderMsg(m,i)); if((m.message_type==="offer"||m.message_type==="reoffer")&&m.content&&m.content!=="\u4E70\u5BB6\u7EE7\u7EED\u51FA\u4EF7"){var oa=m.sender_role===role?"flex-end":"flex-start";acc.push(h("div",{key:"msg_"+i,style:{display:"flex",justifyContent:oa,padding:"2px 16px 6px"}},h("div",{style:{maxWidth:220,background:"#fff1f3",borderRadius:12,padding:"10px 12px",fontSize:13,color:"#555",lineHeight:"19px",wordBreak:"break-word",border:"1px solid #ffd6df"}},m.content)));} if(m.message_type==="counter"&&m.content&&m.content.length>0&&m.content!=="\u5356\u5BB6\u8FD8\u4EF7"){var ca=m.sender_role===role?"flex-end":"flex-start";acc.push(h("div",{key:"msg2_"+i,style:{display:"flex",justifyContent:ca,padding:"2px 16px 6px"}},h("div",{style:{maxWidth:220,background:"#fff1f3",borderRadius:12,padding:"10px 12px",fontSize:13,color:"#555",lineHeight:"19px",wordBreak:"break-word",border:"1px solid #ffd6df"}},m.content)));} if(m.sender_role===role&&m.price){var isRead=role==="buyer"?!!m.seller_read_at:!!m.buyer_read_at;var ra=m.sender_role===role?"flex-end":"flex-start";acc.push(h("div",{key:"read_"+i,style:{display:"flex",justifyContent:ra,padding:"0 16px 4px"}},h("div",{style:{fontSize:12,color:isRead?"#999":"#ff8a00"}},isRead?"\u5DF2\u8BFB":"\u672A\u8BFB")));} return acc; },[])
          : h("div",{style:{textAlign:"center",padding:24,color:"#bbb",fontSize:13}},"\u6682\u65E0\u6D88\u606F")
      ),

      // Error display
      error && h("div",{style:{padding:"6px 16px",fontSize:12,color:"#f12c20",textAlign:"center"}},error)
    ),

    // === Bottom action bar ===
    h("div",{style:{flexShrink:0,background:"#f7f7f7",padding:"8px 16px 16px"}},

      // Seller: pending
      role === "seller" && bargain.status === "pending" && h("div",null,
        h("button",{onClick:sellerAccept,disabled:acting,style:{width:"100%",padding:14,borderRadius:10,border:"none",background:"#52c41a",color:"#fff",fontSize:16,fontWeight:600,cursor:acting?"not-allowed":"pointer"}},"\u540C\u610F\u51FA\u4EF7")
      ),

      // Buyer: countered - agree to counter, pay
      role === "buyer" && bargain.status === "countered" && h("div",null,
        h("button",{onClick:buyerAccept,disabled:acting,style:{width:"100%",padding:14,borderRadius:10,border:"none",background:"#b7eb8f",color:"#135200",fontSize:16,fontWeight:600,cursor:acting?"not-allowed":"pointer"}},"\u540C\u610F\u51FA\u4EF7\uFF0C\u70B9\u51FB\u4ED8\u6B3E")
      ),

      // Seller: countered - waiting for buyer
      role === "seller" && bargain.status === "countered" && h("div",null,
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:42,background:"#fff1f0",color:"#ff4d4f",borderRadius:12,fontSize:14,fontWeight:600}},"\u5DF2\u8FD8\u4EF7\uFF0C\u7B49\u5F85\u4E70\u5BB6\u56DE\u590D")
      ),

      // Buyer: pending
      role === "buyer" && bargain.status === "pending" && h("div",null,
        h("div",{style:{width:"100%",padding:13,borderRadius:10,background:"#fff1f0",color:"#ff4d4f",fontSize:14,fontWeight:600,textAlign:"center"}},"等待卖家回复")
      ),

      // Buyer: awaiting_payment / accepted
      role === "buyer" && (bargain.status === "awaiting_payment" || bargain.status === "accepted") && h("div",null,
        bargain.status === "awaiting_payment" && h("div",{style:{fontSize:13,color:"#1677ff",marginBottom:8,textAlign:"center"}},"已达成砍价，请在 2 小时内完成支付"),
        h("button",{onClick:buyerPay,disabled:acting,style:{width:"100%",padding:14,borderRadius:10,border:"none",background:"#1677ff",color:"#fff",fontSize:16,fontWeight:600,cursor:acting?"not-allowed":"pointer"}},"去支付 ￥" + (bargain.final_price ? Number(bargain.final_price).toFixed(2) : "0.00"))
      ),

      // Seller: awaiting_payment / accepted
      role === "seller" && (bargain.status === "awaiting_payment" || bargain.status === "accepted") && h("div",null,
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:42,background:"#eef6ff",color:"#1677ff",borderRadius:12,fontSize:14,fontWeight:600,margin:"0 16px"}},"已确认还价，等待买家支付")
      ),

      // paid_success
      bargain.status === "paid_success" && bargain.order_id && h("div",null,
        h("div",{style:{textAlign:"center",fontSize:16,color:"#52c41a",fontWeight:600,padding:"4px 0",marginBottom:8}},"砍价成功"),
        h("button",{onClick:function(){ NK.Store.navigate("tradeRoom",{orderId:bargain.order_id}); },style:{width:"100%",padding:14,borderRadius:10,border:"none",background:"#1677ff",color:"#fff",fontSize:16,fontWeight:600,cursor:"pointer"}},"前往交易群")
      ),
      bargain.status === "paid_success" && !bargain.order_id && h("div",null,
        h("div",{style:{textAlign:"center",fontSize:16,color:"#52c41a",fontWeight:600,padding:14}},"砍价成功")
      ),

      // Terminal states
      (bargain.status === "rejected" || bargain.status === "cancelled" || bargain.status === "expired") && h("div",null,
        h("div",{style:{textAlign:"center",fontSize:13,color:"#999",padding:14}},statusLabels[bargain.status])
      )
    ),


    // === Modify offer modal ===
    modifyVisible && h("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,zIndex:200,display:"flex",flexDirection:"column",justifyContent:"flex-end"}},
      // Overlay
      h("div",{onClick:closeModifyModal,style:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.42)"}}),
      // Bottom sheet
      h("div",{style:{position:"relative",width:"100%",maxWidth:430,left:"50%",right:"auto",transform:"translateX(-50%)",background:"#fff",borderTopLeftRadius:18,borderTopRightRadius:18,padding:"18px 16px 22px",maxHeight:"78vh",overflowY:"auto",boxShadow:"0 -8px 30px rgba(0,0,0,0.15)"}},
        // Title + close
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14}},
          h("div",{style:{fontSize:18,fontWeight:700,color:"#1a1a1a"}},(offerModalMode==="modify"?"\u4FEE\u6539\u51FA\u4EF7":(offerModalMode==="sellerCounter"?"\u5356\u5BB6\u8FD8\u4EF7":"\u7EE7\u7EED\u51FA\u4EF7"))),
          h("div",{onClick:closeModifyModal,style:{width:28,height:28,borderRadius:"50%",background:"#f0f0f0",display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,color:"#999",cursor:"pointer"}},"×")
        ),
        // Price info row
        h("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:12,fontSize:14}},
          h("div",null,h("span",{style:{color:"#999"}},(offerModalMode==="sellerCounter"?"\u6211\u7684\u8FD8\u4EF7 ":"\u6211\u7684\u51FA\u4EF7 ")),h("span",{style:{color:"#f12c20",fontWeight:700}},"￥" + Number(bargain.offer_price||0).toFixed(2))),
          h("div",null,h("span",{style:{color:"#999"}},"商品原价 "),h("span",{style:{color:"#f12c20",fontWeight:700}},"￥" + Number(bargain.original_price||0).toFixed(2)))
        ),
        // Price input
        h("div",{style:{marginBottom:12}},
          h("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",placeholder:"请输入￥" + Math.floor(Number(bargain.original_price)*0.7) + "~￥" + (Math.floor(Number(bargain.original_price))-1) + "之间的出价",value:modifyPrice,onChange:function(e){var v=e.target.value.replace(/\D/g,"");setModifyPrice(v);},style:{width:"100%",height:46,padding:"0 14px",border:"1px solid #e0e0e0",borderRadius:12,fontSize:18,fontWeight:700,color:"#333",textAlign:"center",outline:"none",boxSizing:"border-box"}})
        ),
        // Message area (read-only with cycle)
        h("div",{style:{marginBottom:16,padding:"0 12px",background:"#fafaf5",borderRadius:12,display:"flex",alignItems:"center",justifyContent:"space-between",height:44,boxSizing:"border-box"}},
          h("div",{style:{fontSize:12,color:"#555",flex:1,minWidth:0,wordBreak:"break-word",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},modifyMsg || (offerModalMode==="sellerCounter"?"\u9009\u53E5\u8BDD\uFF0C\u66F4\u597D\u5546\u91CF~":"\u64A9\u53E5\u8BDD\uFF0C\u66F4\u597D\u8C08~")),
          h("div",{onClick:cycleModifyMsg,style:{fontSize:11,color:"#1677ff",cursor:"pointer",flexShrink:0,marginLeft:8,userSelect:"none"}},"换句话")
        ),
        // Error
        error && h("div",{style:{color:"#ff4d4f",fontSize:12,textAlign:"center",marginBottom:8}},error),
        // Confirm button
        h("button",{onClick:confirmModifyOffer,disabled:acting,style:{width:"100%",height:48,borderRadius:12,border:"none",background:acting?"#f5c89a":"#f59aaa",color:"#fff",fontSize:16,fontWeight:600,cursor:acting?"not-allowed":"pointer"}},"确认")
      )
    ),
    // Toast
    toast && h("div",{style:{position:"fixed",top:60,left:"50%",transform:"translateX(-50%)",background:"rgba(0,0,0,0.75)",color:"#fff",padding:"10px 24px",borderRadius:20,fontSize:14,zIndex:9999}},toast)
  );
}

window.NK = window.NK || {};
NK.BargainSessionPage = BargainSessionPage;
