﻿// BargainListPage - Stitch v2
const { useState, useEffect } = React;

function BargainListPage() {
  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 initialRole = pp.role || 'buyer';
  var _activeRole = useState(initialRole); var activeRole = _activeRole[0], setActiveRole = _activeRole[1];
  var _list = useState([]); var list = _list[0], setList = _list[1];
  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _error = useState(''); var error = _error[0], setError = _error[1];

  var statusConfig = {
    pending: { label: '等待卖家回复', bg: '#fff7ed', color: '#f97316' },
    accepted: { label: '已同意出价', bg: '#dcfce7', color: '#16a34a' },
    rejected: { label: '已拒绝', bg: '#fee2e2', color: '#dc2626' },
    countered: { label: '卖家已还价', bg: '#e0f2fe', color: '#0284c7' },
    buyer_accepted: { label: '已达成', bg: '#dcfce7', color: '#16a34a' },
    awaiting_payment: { label: '待支付', bg: '#dbeafe', color: '#2563eb' },
    paid_success: { label: '已支付', bg: '#dcfce7', color: '#16a34a' },
    cancelled: { label: '已取消', bg: '#f1f5f9', color: '#64748b' },
    expired: { label: '已过期', bg: '#f1f5f9', color: '#64748b' }
  };

  if (!NK.Store.isLoggedIn()) {
    return h('div',{style:{background:'#F8FAFC',minHeight:'100vh'}},
      h('div',{style:{background:'#fff',padding:'0 16px',height:52,display:'flex',alignItems:'center',justifyContent:'center',position:'sticky',top:0,zIndex:40,boxShadow:'0 1px 3px rgba(0,0,0,0.04)'}},
        h('div',{style:{fontSize:17,fontWeight:700,color:'#1E293B'}},'砍价消息')
      ),
      h('div',{style:{textAlign:'center',paddingTop:100,color:'#94A3B8'}},'请先登录')
    );
  }

  useEffect(function(){
    setLoading(true); setError('');
    var api = activeRole === 'buyer' ? NK.Api.Bargains.buyerList() : NK.Api.Bargains.sellerList();
    api.then(function(r){
      if (r && r.code === 0) setList(r.data.list || []);
      else setError((r&&r.message)||'加载失败');
    }).catch(function(){ setError('网络错误'); }).finally(function(){ setLoading(false); });
  }, [activeRole]);

  function switchRole(role){ if(role !== activeRole) setActiveRole(role); }

  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'});
  }

  function summaryText(b){
    var role = activeRole;
    if (b.status === 'pending') return role === 'buyer' ? '等待卖家回复' : '买家等待你回复';
    if (b.status === 'countered') return role === 'buyer' ? ('卖家还价 ¥' + Number(b.counter_price||0).toFixed(2)) : '已还价，等待买家回复';
    if (b.status === 'awaiting_payment') return role === 'buyer' ? '待支付' : '等待买家支付';
    var cfg = statusConfig[b.status];
    return cfg ? cfg.label : b.status;
  }

  return h('div',{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(){NK.Store.back('messages');},style:{width:32,height:32,display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',fontSize:20,color:'#475569',flexShrink:0}},svgArrL()),
      h('div',{style:{position:'absolute',left:'50%',transform:'translateX(-50%)',width:242,height:32,background:'#F1F5F9',borderRadius:10,padding:2,display:'flex'}},
        ['buyer','seller'].map(function(role){
          var isActive = activeRole === role;
          return h('div',{
            key:role,
            onClick:function(){switchRole(role);},
            style:{
              flex:1,display:'flex',alignItems:'center',justifyContent:'center',borderRadius:8,fontSize:13,fontWeight:isActive?700:600,cursor:'pointer',
              background:isActive?'#2563EB':'transparent',
              color:isActive?'#fff':'#475569',
              boxShadow:isActive?'0 1px 3px rgba(37,99,235,0.3)':'none',
              transition:'all 0.2s ease'
            }
          },role==='buyer'?'我是买家':'我是卖家');
        })
      )
    ),

    h('div',{style:{flex:1,overflowY:'auto',paddingTop:4}},
      loading ? h('div',{style:{textAlign:'center',padding:40,color:'#94A3B8',fontSize:14}},'加载中...') :
      error && list.length === 0 ? h('div',{style:{textAlign:'center',padding:40}},
        h('div',{style:{color:'#94A3B8',fontSize:14,marginBottom:12}},error),
        h('div',{onClick:function(){switchRole(activeRole);},style:{display:'inline-block',padding:'8px 20px',borderRadius:8,background:'#2563EB',color:'#fff',fontSize:13,fontWeight:600,cursor:'pointer'}},'重试')
      ) :
      list.length === 0 ? h('div',{style:{display:'flex',flexDirection:'column',alignItems:'center',paddingTop:80}},
        h('div',{style:{fontSize:40,marginBottom:12,opacity:0.4}},'📋'),
        h('div',{style:{fontSize:15,color:'#94A3B8'}},activeRole==='buyer'?'暂无我发起的砍价':'暂无别人砍我的商品')
      ) :
      h('div',null,list.map(function(b){
        var cover = b.coverImage || '';
        var price = activeRole === 'buyer' ? (b.counter_price || b.offer_price) : (b.offer_price || b.counter_price);
        var title = b.title || '商品';
        return h('div',{
          key:b.id,
          onClick:function(){NK.Store.navigate('bargainSession',{id:b.id});},
          style:{margin:'0 16px 14px',padding:20,minHeight:152,background:'#fff',borderRadius:20,cursor:'pointer',boxShadow:'0 6px 18px rgba(15,23,42,0.06)',display:'flex',alignItems:'center',transition:'box-shadow 0.2s'}
        },
          // Thumbnail - 112x112
          cover ? h('img',{src:cover,style:{width:112,minWidth:112,height:112,borderRadius:10,objectFit:'cover'},onError:function(e){e.target.style.display='none';}}) : h('div',{style:{width:112,minWidth:112,height:112,borderRadius:10,background:'#F1F5F9',display:'flex',alignItems:'center',justifyContent:'center',fontSize:32,color:'#CBD5E1'}},'📦'),
          // Middle content
          h('div',{style:{flex:1,minWidth:0,marginLeft:16,display:'flex',flexDirection:'column',justifyContent:'space-between',alignSelf:'stretch'}},
            // Title
            h('div',{style:{fontSize:15,fontWeight:700,color:'#1E293B',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',lineHeight:'22px',marginBottom:4}},title),
            // Product public number
            h('div',{style:{fontSize:12,color:'#94A3B8',marginBottom:6}},b.product_no ? String(b.product_no).trim() : '编号待补齐'),
            // Original price
            h('div',{style:{fontSize:12,color:'#94A3B8',marginBottom:4}},'原价 ¥' + Number(b.original_price||0).toFixed(2)),
            // Summary
            h('div',{style:{fontSize:13,color:'#64748B',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}},summaryText(b))
          ),
          // Right side: status badge + price + time
          h('div',{style:{display:'flex',flexDirection:'column',alignItems:'flex-end',justifyContent:'space-between',alignSelf:'stretch',marginLeft:12,minWidth:80}},
            // Status badge
            h('span',{style:{fontSize:11,padding:'3px 10px',borderRadius:999,background:(statusConfig[b.status]||{}).bg||'#f1f5f9',color:(statusConfig[b.status]||{}).color||'#64748b',fontWeight:600,letterSpacing:'0.02em',marginBottom:6}},(statusConfig[b.status]||{}).label||b.status),
            // Price
            price ? h('div',{style:{fontSize:20,fontWeight:800,color:'#DC2626',letterSpacing:'-0.02em',marginBottom:4}},'¥' + Number(price).toFixed(2)) : null,
            // Time
            h('span',{style:{fontSize:12,color:'#CBD5E1'}},fmtTime(b.updated_at||b.created_at))
          )
        );
      }))
    )
  );
}

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