﻿// 我的钱包页面 v2 - 克制蓝 + 设置项风格
const { useState, useEffect } = React;

function WalletPage() {
  var _w = useState(null); var wallet = _w[0], setWallet = _w[1];
  var _l = useState(true); var loading = _l[0], setLoading = _l[1];
  var _profile = useState(null); var profile = _profile[0], setProfile = _profile[1];
  var _uq = useState(false); var uq = _uq[0], suq = _uq[1];
  var _er = useState(''); var er = _er[0], ser = _er[1];

  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 defaultWallet = { balance: 0, frozenAmount: 0, totalIncome: 0, totalWithdraw: 0 };

  function loadWallet() {
    setLoading(true);
    return NK.Api.Wallet.info().then(function(r) {
      if (r && r.code === 0) { setWallet(r.data); } else { setWallet(defaultWallet); }
    }).catch(function() { setWallet(defaultWallet); })
    .finally(function() { setLoading(false); });
  }

  useEffect(function() {
    if (!NK.Store.isLoggedIn()) return;
    loadWallet();
    NK.Api.User.profile().then(function(r) {
      if (r && r.code === 0 && r.data) setProfile(r.data);
    }).catch(function() {});

  }, []);

  function upImg(key) {
    var inp = document.createElement('input'); inp.type = 'file'; inp.accept = 'image/jpeg,image/png,image/webp';
    inp.onchange = function() {
      var file = inp.files[0];
      if (!file) return;
      if (file.size > 5 * 1024 * 1024) { ser('图片不超过5MB'); return; }
      suq(true); ser('');
      NK.Api.Upload.image(file).then(function(r) {
        if (r && r.code === 0 && r.data) {
          var url = r.data.url || r.data.image_url || '';
          if (url) {
            var upd = {}; upd[key] = url;
            if (profile) {
              upd.wechat_qr = profile.wechat_qr || '';
              upd.alipay_qr = profile.alipay_qr || '';
              upd.alipay_account = profile.alipay_account || '';
              upd.nickname = profile.nickname || '';
              upd.avatar = profile.avatar || '';
            }
            upd[key] = url;
            return NK.Api.User.updateProfile(upd);
          }
        } else { ser((r && r.message) || '上传失败'); return Promise.reject(); }
      }).then(function(r2) {
        if (r2 && r2.code === 0) {
          var p2 = Object.assign({}, profile, {}); p2[key] = url; setProfile(p2);
        }
      }).catch(function(e) { if (e) ser('保存失败'); })
      .finally(function() { suq(false); });
    };
    inp.click();
  }

  if (!NK.Store.isLoggedIn()) {
    return h('div',{className:'detail-page'},h('div',{className:'empty-state',style:{paddingTop:80}},h('div',{style:{fontSize:48,marginBottom:12}},'\uD83D\uDD12'),h('div',null,'请先登录'),h('div',{style:{color:'#1677ff',marginTop:12,cursor:'pointer',fontSize:14},onClick:function(){NK.Store.navigate('login')}},'去登录')));
  }

  var w = wallet || defaultWallet;
  var p = profile || {};

  // Split balance into integer + decimal
  var renderBalance = function(amount) {
    var n = Number(amount) || 0;
    var s = n.toFixed(2);
    var dot = s.indexOf('.');
    var intPart = s.substring(0, dot);
    var decPart = s.substring(dot);
    return h('span', null,
      h('span', null, '\u00A5'),
      h('span', {style:{fontWeight:700}}, intPart),
      h('span', {style:{fontSize:18,fontWeight:400,opacity:.55}}, decPart)
    );
  };

  // Stat item - lightweight symbols
  var statItem = function(symbol, label, val) {
    return h('div',{className:'wallet-item'},
      symbol ? h('div',{style:{fontSize:10,color:'rgba(255,255,255,.35)',marginBottom:4,letterSpacing:1}}, symbol) : null,
      h('div',{className:'wallet-item-label'},label),
      h('div',{className:'wallet-item-val'},'\u00A5' + (Number(val)||0).toFixed(2))
    );
  };

  // Settings row - like iOS settings
  var settingRow = function(label, sub, imgUrl, onClick, showArrow) {
    return h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'14px 0',cursor:onClick?'pointer':'default',borderBottom:'1px solid #F1F5F9'},onClick:onClick||undefined},
      h('div',{style:{display:'flex',alignItems:'center',gap:10,flex:1,minWidth:0}},
        imgUrl ? h('img',{src:imgUrl,style:{width:36,height:36,borderRadius:8,objectFit:'cover',flexShrink:0,border:'1px solid #F1F5F9'}}) : null,
        h('div',{style:{minWidth:0}},
          h('div',{style:{fontSize:14,color:'#334155',fontWeight:500}},label),
          sub ? h('div',{style:{fontSize:11,color:'#94A3B8',marginTop:2,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}},sub) : null
        )
      ),
      showArrow !== false ? h('span',{style:{fontSize:16,color:'#C2C9D2',flexShrink:0,marginLeft:8}},'\u203A') : null
    );
  };

  // QR setting row
  var qrRow = function(label, key, imgUrl) {
    return settingRow(
      label,
      imgUrl ? '\u5DF2\u8BBE\u7F6E' : '\u672A\u8BBE\u7F6E',
      imgUrl || null,
      function(){ upImg(key); },
      true
    );
  };

  return h('div',{className:'detail-page'},
    h('div',{className:'back-header'},
      h('div',{className:'bbtn',onClick:function(){NK.Store.back('mine')}},svgArrL()),
      h('div',{className:'btitle'},'\u6211\u7684\u94B1\u5305')
    ),
    loading ? h('div',{className:'empty-state',style:{paddingTop:80}},h('div',null,'\u52A0\u8F7D\u4E2D...')) :
    h('div',{style:{padding:14}},

      // Balance card
      h('div',{className:'wallet-card'},
        h('div',{className:'wallet-balance-label'},'\u53EF\u7528\u4F59\u989D'),
        h('div',{className:'wallet-balance'},renderBalance(w.balance)),
        h('div',{className:'wallet-grid'},
          statItem('','冻结金额',w.frozenAmount),
          statItem('','累计收入',w.totalIncome),
          statItem('','累计提现',w.totalWithdraw)
        )
      ),

      // Quick actions
      h('div',{className:'wallet-actions-row'},
        h('button',{className:'wallet-btn primary',onClick:function(){alert('\u5145\u503C\u529F\u80FD\u6B63\u5728\u63A5\u5165\u4E2D\uFF0C\u5982\u9700\u5145\u503C\u8BF7\u8054\u7CFB\u5BA2\u670D')}},
          h('span',{style:{fontSize:16}},'\uFF0B'),' \u5145\u503C'
        ),
        h('button',{className:'wallet-btn outline',onClick:function(){alert('\u63D0\u73B0\u529F\u80FD\u6B63\u5728\u63A5\u5165\u4E2D\uFF0C\u5982\u9700\u63D0\u73B0\u8BF7\u8054\u7CFB\u5BA2\u670D')}},
          h('span',{style:{fontSize:16}},'\u2212'),' \u63D0\u73B0'
        )
      ),

      // Payment settings card
      h('div',{style:{marginTop:12,background:'#fff',borderRadius:12,padding:'4px 16px',boxShadow:'0 1px 3px rgba(0,0,0,0.04)'}},
        h('div',{style:{fontSize:14,fontWeight:600,color:'#1F2937',padding:'14px 0',borderBottom:'1px solid #F1F5F9'}},'\u6536\u6B3E\u8BBE\u7F6E'),
        qrRow('\u5FAE\u4FE1\u6536\u6B3E\u7801','wechat_qr',p.wechat_qr),
        qrRow('\u652F\u4ED8\u5B9D\u6536\u6B3E\u7801','alipay_qr',p.alipay_qr),
        // Alipay account - special row with inline edit
        h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'14px 0'}},
          h('div',{style:{minWidth:0,flex:1}},
            h('div',{style:{fontSize:14,color:'#334155',fontWeight:500}},'\u652F\u4ED8\u5B9D\u8D26\u6237'),
            h('input',{style:{width:'100%',marginTop:4,padding:0,border:'none',outline:'none',fontSize:13,color:p.alipay_account?'#334155':'#94A3B8',background:'transparent'},value:p.alipay_account||'',placeholder:'\u624B\u673A\u53F7/\u90AE\u7BB1\uFF0C\u9009\u586B',onChange:function(e){
              var upd = Object.assign({}, p, {alipay_account: e.target.value});
              setProfile(upd);
            },onBlur:function(e){
              var upd = {}; upd.alipay_account = e.target.value;
              if (p) { upd.wechat_qr = p.wechat_qr || ''; upd.alipay_qr = p.alipay_qr || ''; upd.nickname = p.nickname || ''; upd.avatar = p.avatar || ''; }
              NK.Api.User.updateProfile(upd);
            }})
          ),
          h('span',{style:{fontSize:16,color:'#C2C9D2',flexShrink:0,marginLeft:8}},'\u203A')
        )
      ),

      // Transaction records
      h('div',{style:{marginTop:12,background:'#fff',borderRadius:12,padding:'16px',boxShadow:'0 1px 3px rgba(0,0,0,0.04)'}},
        h('div',{style:{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:2}},
          h('div',{style:{fontSize:14,fontWeight:600,color:'#1F2937'}},'\u94B1\u5305\u660E\u7EC6'),
          h('span',{style:{fontSize:12,color:'#3B82F6',cursor:'pointer',fontWeight:500},onClick:function(){NK.Store.navigate('walletTransactions')}},'\u5168\u90E8 \u203A')
        ),
        h('div',{style:{textAlign:'center',padding:'24px 0 0'}},
          h('div',{style:{width:40,height:40,borderRadius:12,background:'#F8FAFC',display:'inline-flex',alignItems:'center',justifyContent:'center',marginBottom:10,border:'1px solid #F1F5F9'}},
            h('span',{style:{fontSize:16,color:'#94A3B8',fontWeight:400}},'\u00A5')
          ),
          h('div',{style:{color:'#94A3B8',fontSize:13}},'\u6682\u65E0\u94B1\u5305\u660E\u7EC6'),
          h('div',{style:{color:'#94A3B8',fontSize:11,marginTop:4,paddingBottom:4}},'\u4EA4\u6613\u6536\u5165\u3001\u63D0\u73B0\u8BB0\u5F55\u5C06\u663E\u793A\u5728\u8FD9\u91CC')
        )
      )
    )
  );
}

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