// 移动端首页 - 商品列表 + 4个筛选面板（v4：修复筛选逻辑 + 前端过滤排序）
const { useState, useEffect, useCallback } = React;

const SERVERS = [
  '绽放之花','无尽之海','遗忘之境','生命之树',
  '狂野之原','轻云之月','飘渺之峰','暗涌之泉','应许之地',
  '参天之树','拉普达','铭心之界'
];

const SORT_OPTIONS = [
  { value:'',          label:'综合排序' },
  { value:'newest',    label:'最近发布' },
  { value:'price_desc',label:'价格由高到低' },
  { value:'price_asc', label:'价格由低到高' },
];

const LEGENDARY_TIERS = ['五阶传说','四阶传说','三阶传说'];
const LEGENDARY_TYPES = [
  '长枪','龙爪','战刃','短匕','刺剑','火铳','短剑','圆盾',
  '镰刀','提灯','星仪','命盘','法杖','奶杖','法典','长弓','箭袋'
];
const MOUNT_FLY = ['四飞','六飞','八飞'];
const MOUNT_ZODIAC = [
  '天秤座','天蝎座','射手座','摩羯座','水瓶座',
  '处女座','双鱼座','白羊座','金牛座','双子座','巨蟹座'
];
const UNLOCK_T = ['T4','T5','T6','T7','T8'];
const UNLOCK_PROFS = ['战士','输出','法师'];
const UNLOCK_PARTS = {
  '战士': ['头盔','胸甲','腿甲','战靴','短剑','圆盾','长枪','龙爪'],
  '输出': ['头饰','护胸','护腿','便鞋','战刃','短匕','火铳','短剑','刺剑','长弓','箭袋'],
  '法师': ['兜帽','法袍','长裤','软鞋','镰刀','提灯','星仪','命盘','法杖','法典']
};

function emptyLegendary() { var o={}; LEGENDARY_TIERS.forEach(function(t){o[t]=[];}); return o; }
function emptyUnlock() { var o={}; UNLOCK_T.forEach(function(t){o[t]={profs:{'战士':[],'输出':[],'法师':[]}};}); return o; }
function cloneObj(src) { return JSON.parse(JSON.stringify(src)); }

function HomePage() {
  // --- 数据 ---
  var _products = useState([]); var products = _products[0]; var setProducts = _products[1];
  var _total = useState(0); var total = _total[0]; var setTotal = _total[1];
  var _page = useState(1); var page = _page[0]; var setPage = _page[1];
  var _loading = useState(false); var loading = _loading[0]; var setLoading = _loading[1];
  var _initLoading = useState(true); var initLoading = _initLoading[0]; var setInitLoading = _initLoading[1];
  var _noMore = useState(false); var noMore = _noMore[0]; var setNoMore = _noMore[1];
  var pageSize = 50; // 大 pageSize 保证前端过滤完整

  var _keyword = useState(''); var keyword = _keyword[0]; var setKeyword = _keyword[1];
  var _searchText = useState(''); var searchText = _searchText[0]; var setSearchText = _searchText[1];

  var _activePanel = useState(null); var activePanel = _activePanel[0]; var setActivePanel = _activePanel[1];
  var _server = useState(''); var server = _server[0]; var setServer = _server[1];
  var _minPrice = useState(''); var minPrice = _minPrice[0]; var setMinPrice = _minPrice[1];
  var _maxPrice = useState(''); var maxPrice = _maxPrice[0]; var setMaxPrice = _maxPrice[1];
  var _bannerIdx = useState(0); var bannerIdx = _bannerIdx[0]; var setBannerIdx = _bannerIdx[1];
  var _sortValue = useState(''); var sortValue = _sortValue[0]; var setSortValue = _sortValue[1];
  // Banner ads - auto sliding
  var BANNERS = [
    { title: '\u65B9\u5757\u53F7\u4ED3', subtitle: '\u5B89\u5168\u00B7\u4FBF\u6377\u00B7\u53EF\u9760', color: '#1677ff', icon: '\uD83C\uDFDB' },
    { title: '\u591A\u79CD\u8D26\u53F7\u7C7B\u578B', subtitle: '\u4F20\u8BF4\u88C5\u5907\u00B7\u5750\u9A91\u00B7\u89E3\u9501\u53F7', color: '#722ed1', icon: '\u2694\uFE0F' },
    { title: '\u5B89\u5168\u4EA4\u6613\u4FDD\u969C', subtitle: '\u5E73\u53F0\u62C5\u4FDD\u00B7\u6362\u7ED1\u5B89\u5168\u00B7\u7EA0\u7EB7\u4EF2\u88C1', color: '#389e0d', icon: '\uD83D\uDD12' },
  ];
  useEffect(function(){
    if (BANNERS.length <= 1) return;
    var timer = setInterval(function(){
      setBannerIdx(function(i){ return (i + 1) % BANNERS.length; });
    }, 3000);
    return function(){ clearInterval(timer); };
  }, []);

  var _sortLabel = useState('综合排序'); var sortLabel = _sortLabel[0]; var setSortLabel = _sortLabel[1];
  var _draft = useState({}); var draft = _draft[0]; var setDraft = _draft[1];

  var _legSaved = useState(emptyLegendary); var legSaved = _legSaved[0]; var setLegSaved = _legSaved[1];
  var _mountFly = useState(''); var mountFly = _mountFly[0]; var setMountFly = _mountFly[1];
  var _mountZodiac = useState([]); var mountZodiac = _mountZodiac[0]; var setMountZodiac = _mountZodiac[1];
  var _mountZodiacAny = useState(false); var mountZodiacAny = _mountZodiacAny[0]; var setMountZodiacAny = _mountZodiacAny[1];
  var _unlSaved = useState(emptyUnlock); var unlSaved = _unlSaved[0]; var setUnlSaved = _unlSaved[1];

  // --- 是否有筛选条件 ---
  var hasServer = !!server;
  var hasPrice = !!(minPrice||maxPrice);
  var hasSort = !!sortValue;
  var hasEquip = (function(){
    var has=false;
    LEGENDARY_TIERS.forEach(function(t){if(legSaved[t]&&legSaved[t].length)has=true;});
    if(mountFly||mountZodiac.length)has=true;
    UNLOCK_T.forEach(function(t){var td=unlSaved[t];if(td&&td.profs){UNLOCK_PROFS.forEach(function(p){if(td.profs[p]&&td.profs[p].length)has=true;});}});
    return has;
  })();

  // ==================== 前端过滤 ====================
  var doFilter = useCallback(function(list) {
    if (!hasEquip && sortLabel==='综合排序') return list;
    var filtered = list;
    if (hasEquip) {
      filtered = list.filter(function(p) {
        return NK.ConfigUtil.matchEquip(p, legSaved, {flyCount:mountFly,zodiacs:mountZodiac}, unlSaved);
      });
    }
    return filtered;
  }, [hasEquip, legSaved, mountFly, mountZodiac, unlSaved, sortLabel]);

  // ==================== 已选筛选标签 ====================
  var renderFilterTags = function(){
    var tags = [];

    // 服务器
    if (server) {
      tags.push({ id: 'server', label: server, onRemove: function(){ setServer(''); } });
    }

    // 价格区间
    if (minPrice || maxPrice) {
      var priceLabel = '';
      if (minPrice && maxPrice) priceLabel = '\uFFE5' + minPrice + '-\uFFE5' + maxPrice;
      else if (minPrice) priceLabel = '\uFFE5' + minPrice + '\u4EE5\u4E0A';
      else if (maxPrice) priceLabel = '\uFFE5' + maxPrice + '\u4EE5\u4E0B';
      tags.push({ id: 'price', label: priceLabel, onRemove: function(){ setMinPrice(''); setMaxPrice(''); } });
    }

    // 综合筛选/排序
    if (sortValue && sortLabel && sortLabel !== '\u7EFC\u5408\u6392\u5E8F') {
      tags.push({ id: 'sort', label: sortLabel, onRemove: function(){ setSortValue(''); setSortLabel('\u7EFC\u5408\u6392\u5E8F'); } });
    }

    // 配置筛选 - 传说装备
    LEGENDARY_TIERS.forEach(function(t){
      if (legSaved[t] && legSaved[t].length > 0) {
        var lbl = t + '\u2265' + legSaved[t].length + '\u4EF6';
        tags.push({ id: 'leg-'+t, label: lbl, onRemove: function(){
          setLegSaved(function(prev){
            var n = cloneObj(prev); n[t] = []; return n;
          });
        }});
      }
    });

    // 配置筛选 - 坐骑飞行
    if (mountFly) {
      tags.push({ id: 'mountfly', label: mountFly, onRemove: function(){ setMountFly(''); } });
    }

    // 配置筛选 - 星座
    mountZodiac.forEach(function(z, zi){
      tags.push({ id: 'zodiac-'+zi, label: z, onRemove: function(){
        setMountZodiac(function(prev){ return prev.filter(function(x){ return x !== z; }); });
      }});
    });

    // 配置筛选 - 一件即可
    if (mountZodiacAny && mountZodiac.length > 0) {
      tags.push({ id: 'zodiacAny', label: '\u4E00\u4EF6\u5373\u53EF', onRemove: function(){ setMountZodiacAny(false); } });
    }

    // 配置筛选 - 解锁
    UNLOCK_T.forEach(function(t){
      var td = unlSaved[t];
      if (!td || !td.profs) return;
      UNLOCK_PROFS.forEach(function(p){
        var parts = td.profs[p];
        if (!parts || parts.length === 0) return;
        var lbl = t + ' ' + p + ' \u002B' + parts.length + '\u4EF6';
        tags.push({ id: 'unl-'+t+'-'+p, label: lbl, onRemove: function(){
          setUnlSaved(function(prev){
            var n = cloneObj(prev);
            if (n[t] && n[t].profs && n[t].profs[p]) n[t].profs[p] = [];
            return n;
          });
        }});
      });
    });

    if (tags.length === 0) return null;

    var h = React.createElement;

    return h('div',{style:{background:'#fff',padding:'6px 12px 8px',display:'flex',flexWrap:'nowrap',overflowX:'auto',overflowY:'hidden',gap:6,whiteSpace:'nowrap',WebkitOverflowScrolling:'touch',scrollbarWidth:'none',msOverflowStyle:'none'}},
      tags.map(function(tag){
        return h('div',{
          key: tag.id,
          style:{display:'inline-flex',alignItems:'center',height:26,padding:'0 9px',borderRadius:13,background:'#d8e2ff',border:'1px solid #1A73E8',color:'#1A73E8',fontSize:12,fontWeight:500,whiteSpace:'nowrap',flexShrink:0,lineHeight:'26px'}
        },
          tag.label,
          h('span',{
            onClick: function(e){ e.stopPropagation(); tag.onRemove(); },
            style:{marginLeft:4,width:15,height:15,borderRadius:'50%',background:'rgba(26,115,232,0.12)',color:'#1A73E8',display:'inline-flex',alignItems:'center',justifyContent:'center',fontSize:10,cursor:'pointer',flexShrink:0}
          }, '\u00D7')
        );
      })
    );
  };

    // ==================== 数据加载 ====================
  var fetchProducts = useCallback(async function(p, append) {
    var currentPage = p || 1;
    setLoading(true);
    try {
      var params = { page: currentPage, pageSize: pageSize };
      if (keyword.trim()) params.keyword = keyword.trim();
      if (server) params.server = server;
      if (minPrice) params.minPrice = Number(minPrice);
      if (maxPrice) params.maxPrice = Number(maxPrice);
      if (sortValue) params.sort = sortValue;
      var res = await NK.Api.Accounts.list(params);
      if (res.code === 0) {
        var raw = res.data.list || [];
        var filtered = doFilter(raw);
        setProducts(append ? function(prev){return prev.concat(filtered);} : filtered);
        setTotal(res.data.total || 0);
        setPage(currentPage);
        setNoMore(raw.length < pageSize);
      }
    } catch(e) {}
    finally { setLoading(false); setInitLoading(false); }
  }, [keyword, server, minPrice, maxPrice, sortValue, pageSize, doFilter]);

  // ==================== 触发数据加载 ====================
  // 当后端筛选参数变化时自动触发 fetch
  useEffect(function(){ fetchProducts(1, false); }, [fetchProducts]);

  // 当纯前端筛选变化时重新过滤已有数据
  useEffect(function(){
    // 只在初始化完成后响应前端筛选
    if (initLoading) return;
    // 重新请求第一页
    fetchProducts(1, false);
  }, [hasEquip, sortLabel]);

  var handleSearch = function(){ setKeyword(searchText); };

  // 滚动加载更多
  useEffect(function(){
    function onScroll(){
      if (loading || noMore || activePanel) return;
      var h = window.innerHeight || document.documentElement.clientHeight;
      var bottom = document.documentElement.getBoundingClientRect().bottom;
      if (bottom <= h + 200) fetchProducts(page + 1, true);
    }
    window.addEventListener('scroll', onScroll, {passive:true});
    return function(){ window.removeEventListener('scroll', onScroll); };
  }, [loading, noMore, page, activePanel]);

  // ==================== 面板操作 ====================
  var openPanel = function(name){
    if (activePanel === name) { setActivePanel(null); return; }
    var d = {};
    if (name === 'server') d.server = server;
    if (name === 'price') { d.minPrice = minPrice; d.maxPrice = maxPrice; }
    if (name === 'sort')  { d.sort = sortValue; d.sortLabel = sortLabel; }
    if (name === 'equipment') {
      d.eqTab = 'legendary'; d.legTab = '五阶传说';
      d.legendary = cloneObj(legSaved);
      d.mountFly = mountFly; d.mountZodiac = mountZodiac.slice(); d.mountZodiacAny = mountZodiacAny;
      d.unlockTab = 'T4'; d.unlockProf = '战士';
      d.unlock = cloneObj(unlSaved);
    }
    setDraft(d); setActivePanel(name);
  };

  var closePanel = function(){ setActivePanel(null); };

  var applyPanel = function(){
    if (activePanel === 'server') {
      setServer(draft.server||''); setActivePanel(null);
    } else if (activePanel === 'price') {
      var min = draft.minPrice||''; var max = draft.maxPrice||'';
      if (min && max && Number(min) > Number(max)) { alert('最低价不能大于最高价'); return; }
      setMinPrice(min); setMaxPrice(max); setActivePanel(null);
    } else if (activePanel === 'sort') {
      setSortValue(draft.sort||''); setSortLabel(draft.sortLabel||'综合排序'); setActivePanel(null);
    } else if (activePanel === 'equipment') {
      setLegSaved(cloneObj(draft.legendary||emptyLegendary()));
      setMountFly(draft.mountFly||''); setMountZodiac(draft.mountZodiac||[]); setMountZodiacAny(draft.mountZodiacAny||false);
      setUnlSaved(cloneObj(draft.unlock||emptyUnlock()));
      setActivePanel(null);
    }
  };

  var resetPanel = function(){
    if (activePanel === 'server') setDraft(function(p){return Object.assign({},p,{server:''});});
    else if (activePanel === 'price') setDraft(function(p){return Object.assign({},p,{minPrice:'',maxPrice:''});});
    else if (activePanel === 'sort') setDraft(function(p){return Object.assign({},p,{sort:'',sortLabel:'综合排序'});});
    else if (activePanel === 'equipment') setDraft(function(p){return Object.assign({},p,{eqTab:'legendary',legTab:'五阶传说',legendary:emptyLegendary(),mountFly:'',mountZodiac:[],mountZodiacAny:false,unlockTab:'T4',unlockProf:'战士',unlock:emptyUnlock()});});
  };

  var resetEqTab = function(tab){
    if (tab === 'legendary') setDraft(function(p){return Object.assign({},p,{legendary:emptyLegendary(),legTab:'五阶传说'});});
    else if (tab === 'mount') setDraft(function(p){return Object.assign({},p,{mountFly:'',mountZodiac:[],mountZodiacAny:false});});
    else if (tab === 'unlock') setDraft(function(p){return Object.assign({},p,{unlock:emptyUnlock(),unlockTab:'T4',unlockProf:'战士'});});
  };

  // ==================== 辅助 ====================
  var getCover = function(p){
    if (p.coverImage && p.coverImage.image_url) return p.coverImage.image_url;
    if (p.images && p.images.length > 0 && p.images[0].image_url) return p.images[0].image_url;
    return null;
  };
  var fmtPrice = function(p){ var v = Number(p); return '¥' + (Number.isFinite(v) ? v.toFixed(2) : '0.00'); };

  // ==================== 渲染 ====================
  return React.createElement('div',null,
    React.createElement('div',{className:'home-search-bar'},
      React.createElement('input',{type:'text',placeholder:'🔍  搜索游戏账号...',value:searchText,onChange:function(e){setSearchText(e.target.value);},onKeyDown:function(e){if(e.key==='Enter')handleSearch();}})
    ),
    BANNERS.length > 0 && React.createElement('div',{className:'home-banner'},
      BANNERS.map(function(b,i){
        return React.createElement('div',{key:i,className:'banner-slide'+(i===bannerIdx?' active':'')},
          React.createElement('div',{className:'banner-bg',style:{background:'linear-gradient(135deg,'+b.color+','+b.color+'dd)'}},
            React.createElement('span',{className:'banner-icon'},b.icon),
            React.createElement('div',{className:'banner-text'},
              React.createElement('div',{className:'banner-title'},b.title),
              React.createElement('div',{className:'banner-subtitle'},b.subtitle)
            )
          )
        );
      }),
      BANNERS.length > 1 && React.createElement('div',{className:'banner-dots'},
        BANNERS.map(function(_,i){return React.createElement('span',{key:i,className:'banner-dot'+(i===bannerIdx?' active':'')});})
      )
    ),
    
    React.createElement('div',{className:'home-filter-bar'},
      mkFilterBtn('server','服务器',hasServer,activePanel),
      mkFilterBtn('price','价格区间',hasPrice,activePanel),
      mkFilterBtn('equipment','配置筛选',hasEquip,activePanel),
      mkFilterBtn('sort',hasSort?sortLabel:'综合筛选',hasSort,activePanel)
    ),
    renderFilterTags(),
    initLoading
      ? React.createElement('div',{className:'page-loading'},
          React.createElement('div',{className:'spinner'}),
          React.createElement('div',{style:{color:'#999',fontSize:14}},'加载中...'))
      : products.length===0
        ? React.createElement('div',{className:'empty-state'},
            React.createElement('div',{className:'eicon'},'📦'),
            React.createElement('div',null,'暂无商品'),
            React.createElement('div',{style:{fontSize:12,marginTop:4}},'试试调整筛选条件'))
        : React.createElement('div',{className:'product-list'},
            products.map(function(p){
              var cover = getCover(p);
              var cfg = NK.ConfigUtil.parse(p);
              var leg = NK.ConfigUtil.legendary(cfg);
              var mt = NK.ConfigUtil.mountText(cfg);
              var un = NK.ConfigUtil.unlock(cfg);
              var legColored = NK.ConfigUtil.legendaryColored(cfg);
              var pn = p.product_no ? String(p.product_no).trim() : null;
              return React.createElement('div',{key:p.id,className:'product-card',onClick:function(){NK.Store.navigate('detail',{id:p.id});}},
                // Cover image - full width
                React.createElement('div',{className:'pc-img'},
                  cover ? React.createElement('img',{src:cover,alt:p.title||'',onError:function(e){e.target.style.display='none';}}) : React.createElement('div',{className:'pc-img-empty'},'\uD83C\uDFAE')
                ),
                // Text body
                React.createElement('div',{className:'pc-body'},
                  // Title with product_no
                  React.createElement('div',{className:'pc-title'},(pn ? '\u3010'+pn+'\u3011' : '')+(p.title||'\u672A\u77E5\u5546\u54C1')),
                  // Server + T8 unlock
                  React.createElement('div',{className:'pc-meta-row'},
                    p.server && React.createElement('span',{className:'pc-server'},p.server),
                    un && React.createElement('span',{className:'pc-unlock-tag'},un)
                  ),
                  // Equipment summary row
                  (leg||mt) && React.createElement('div',{className:'pc-config-row'},
                    leg && React.createElement('span',{className:'pc-leg-tag'},
                      React.createElement('img',{src:'/assets/items/jian.png',className:'pc-icon',onError:function(e){e.target.style.display='none';}}),
                      (legColored||[]).map(function(item,i){
                        if (item.color) return React.createElement('span',{key:i,style:{color:item.color,fontWeight:700}},item.text);
                        return React.createElement('span',{key:i,style:{color:'#999'}},item.text);
                      })
                    ),
                    mt && React.createElement('span',{className:'pc-mount-tag',style:{color: mt.indexOf('\u516B')>=0 ? '#ff4d4f' : mt.indexOf('\u516D')>=0||mt.indexOf('\u4E03')>=0 ? '#fa8c16' : mt.indexOf('\u56DB')>=0||mt.indexOf('\u4E94')>=0 ? '#722ed1' : '#389e0d'}},
                      React.createElement('img',{src:'/assets/items/long.png',className:'pc-icon',onError:function(e){e.target.style.display='none';}}),
                      mt
                    )
                  ),
                  // Price + views
                  React.createElement('div',{className:'pc-bottom-row'},
                    React.createElement('span',{className:'pc-price'},fmtPrice(p.price)),
                    React.createElement('span',{className:'pc-views'},'\uD83D\uDC41 '+(p.view_count||0))
                  )
                )
              );
            }),
            loading && React.createElement('div',{style:{textAlign:'center',padding:16,color:'#999',fontSize:13}},'加载中...'),
            noMore && total>pageSize && React.createElement('div',{style:{textAlign:'center',padding:16,color:'#ccc',fontSize:12}},'— 没有更多了 —')
          ),
    activePanel==='server' && renderServerPanel(),
    activePanel==='price' && renderPricePanel(),
    activePanel==='sort' && renderSortPanel(),

    React.createElement('div', {
      className: 'home-publish-fab',
      onClick: function() {
  var isApp = document.body.classList.contains('is-app-client');
  var hasUni = !!window.uni;
  var hasPM = !!(window.uni && typeof window.uni.postMessage === 'function');
  console.log('[HomePage] publish click isApp=' + isApp + ' hasUni=' + hasUni + ' hasPostMessage=' + hasPM);
  if (isApp) {
    NK.Store.navigate('publish');
    return;
  }
  NK.Store.navigate('publish');
},
      title: '\u53D1\u5E03\u8D26\u53F7'
    },
      React.createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: 34, height: 34, viewBox: '0 0 24 24', fill: 'none', stroke: '#ffffff', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', className: 'lucide lucide-plus-icon lucide-plus' },
        React.createElement('path', { d: 'M5 12h14' }),
        React.createElement('path', { d: 'M12 5v14' })
      )
    ),
    activePanel==='equipment' && renderEquipPanel()
  );

  function mkFilterBtn(key,label,hasVal,active){
    return React.createElement('div',{className:'fbar-btn'+(active===key?' open':''),onClick:function(){openPanel(key);}},
      label, hasVal?React.createElement('span',{className:'fbar-dot'}):null,
      React.createElement('span',{className:'fbar-arrow'},active===key?' ▴':' ▾')
    );
  }

  function renderServerPanel(){
    return React.createElement('div',{className:'filter-overlay',onClick:closePanel},
      React.createElement('div',{className:'filter-panel',onClick:function(e){e.stopPropagation();}},
        React.createElement('div',{className:'fp-header'},
          React.createElement('div',{className:'fp-title'},'服务器'),
          React.createElement('div',{onClick:closePanel,style:{fontSize:20,cursor:'pointer',color:'#999'}},'✕')
        ),
        React.createElement('div',{className:'fp-body'},
          React.createElement('div',{className:'tag-grid'},
            React.createElement('div',{className:'tag-item tag-all'+(!draft.server?' selected':''),
              style:{width:'100%',textAlign:'center',fontSize:14,fontWeight:600,
                background:!draft.server?'#1677ff':'#f5f5f5',color:!draft.server?'#fff':'#666',borderRadius:20,marginBottom:4},
              onClick:function(){setDraft(function(p){return Object.assign({},p,{server:''});});}},'全部'),
            SERVERS.map(function(s){return React.createElement('div',{key:s,className:'tag-item col2'+(draft.server===s?' selected':''),
              onClick:function(){setDraft(function(p){return Object.assign({},p,{server:s});});}},s);})
          )
        ),
        React.createElement('div',{className:'fp-footer'},
          React.createElement('button',{className:'reset-btn',onClick:resetPanel},'重置'),
          React.createElement('button',{className:'confirm-btn',onClick:applyPanel},'确定')
        )
      )
    );
  }

  function renderPricePanel(){
    return React.createElement('div',{className:'filter-overlay',onClick:closePanel},
      React.createElement('div',{className:'filter-panel',onClick:function(e){e.stopPropagation();}},
        React.createElement('div',{className:'fp-header'},
          React.createElement('div',{className:'fp-title'},'价格区间'),
          React.createElement('div',{onClick:closePanel,style:{fontSize:20,cursor:'pointer',color:'#999'}},'✕')
        ),
        React.createElement('div',{className:'fp-body'},
          React.createElement('div',{className:'price-row',style:{overflow:'hidden'}},
            React.createElement('input',{type:'number',placeholder:'最低价',value:draft.minPrice||'',onChange:function(e){setDraft(function(p){return Object.assign({},p,{minPrice:e.target.value});});},style:{width:'45%'}}),
            React.createElement('span',{style:{flexShrink:0}},' — '),
            React.createElement('input',{type:'number',placeholder:'最高价',value:draft.maxPrice||'',onChange:function(e){setDraft(function(p){return Object.assign({},p,{maxPrice:e.target.value});});},style:{width:'45%'}})
          )
        ),
        React.createElement('div',{className:'fp-footer'},
          React.createElement('button',{className:'reset-btn',onClick:resetPanel},'重置'),
          React.createElement('button',{className:'confirm-btn',onClick:applyPanel},'确定')
        )
      )
    );
  }

  function renderSortPanel(){
    return React.createElement('div',{className:'filter-overlay',onClick:closePanel},
      React.createElement('div',{className:'filter-panel',onClick:function(e){e.stopPropagation();}},
        React.createElement('div',{className:'fp-header'},
          React.createElement('div',{className:'fp-title'},'综合筛选'),
          React.createElement('div',{onClick:closePanel,style:{fontSize:20,cursor:'pointer',color:'#999'}},'✕')
        ),
        React.createElement('div',{className:'fp-body'},
          React.createElement('div',{className:'sort-radio-list'},
            SORT_OPTIONS.map(function(opt,idx){
              var isSel = (draft.sort||'')===opt.value;
              return React.createElement('div',{key:idx,
                className:'sort-radio-item'+(isSel?' sel':''),
                onClick:function(){setDraft(function(p){return Object.assign({},p,{sort:opt.value,sortLabel:opt.label});});}},
                React.createElement('span',{className:'sort-radio-circle'},
                  isSel && React.createElement('span',{className:'sort-radio-dot'})
                ),
                React.createElement('span',{className:'sort-radio-label'},opt.label)
              );
            })
          )
        ),
        React.createElement('div',{className:'fp-footer'},
          React.createElement('button',{className:'reset-btn',onClick:resetPanel},'重置'),
          React.createElement('button',{className:'confirm-btn',onClick:applyPanel},'确定')
        )
      )
    );
  }

  function renderEquipPanel(){
    var tab = draft.eqTab||'legendary';
    var h = React.createElement;
    var sidebarTabs = [
      {key:'legendary',label:'传说装备'},
      {key:'mount',label:'传说坐骑'},
      {key:'unlock',label:'装备解锁'}
    ];
    return h('div',{className:'filter-overlay',onClick:closePanel},
      h('div',{className:'filter-panel equip-panel',onClick:function(e){e.stopPropagation();}},
        h('div',{className:'fp-header'},
          h('div',{className:'fp-title'},'配置筛选'),
          h('div',{onClick:closePanel,style:{fontSize:20,cursor:'pointer',color:'#999'}},'✕')
        ),
        h('div',{style:{flex:1,display:'flex',overflow:'hidden'}},
          // Left sidebar
          h('div',{className:'equip-sidebar'},
            sidebarTabs.map(function(st){
              return h('div',{key:st.key,
                className:'equip-sidebar-item'+(tab===st.key?' active':''),
                onClick:function(){setDraft(function(p){return Object.assign({},p,{eqTab:st.key});});}
              }, st.label);
            })
          ),
          // Right content area
          h('div',{className:'equip-content'},
            tab==='legendary'&&renderLegendaryBody(),
            tab==='mount'&&renderMountBody(),
            tab==='unlock'&&renderUnlockBody()
          )
        ),
        h('div',{className:'fp-footer equip-footer'},
          h('button',{className:'equip-reset-btn',onClick:function(){resetEqTab(tab);}},'重置当前'),
          h('button',{className:'equip-confirm-btn',onClick:applyPanel},'确定')
        )
      )
    );
  }

  function renderLegendaryBody(){
    var legTab = draft.legTab||'五阶传说';
    var legendary = draft.legendary||emptyLegendary();
    var curItems = legendary[legTab]||[];
    return React.createElement('div',null,
      React.createElement('div',{className:'pub3-tiertabs'},
        LEGENDARY_TIERS.map(function(t){
          var has = !!(legendary[t]&&legendary[t].length);
          return React.createElement('div',{key:t,
            className:'pub3-tiertab'+(t===legTab?' active':'')+(has?' configured':''),
            onClick:function(){setDraft(function(p){return Object.assign({},p,{legTab:t});});}},
            t,has&&React.createElement('span',{className:'pub3-tierdot'}));
        })
      ),
      React.createElement('div',{style:{marginTop:10}},
        React.createElement('div',{className:'sect-title'},legTab+' — 装备类型（多选）'),
        React.createElement('div',{className:'tag-grid'},
          LEGENDARY_TYPES.map(function(t){
            var sel = curItems.includes(t);
            return React.createElement('div',{key:t,className:'tag-item'+(sel?' selected':''),
              onClick:function(){
                setDraft(function(prev){
                  var lg = cloneObj(prev.legendary||emptyLegendary());
                  lg[legTab] = sel ? lg[legTab].filter(function(x){return x!==t;}) : lg[legTab].concat([t]);
                  return Object.assign({},prev,{legendary:lg});
                });
              }},t);
          })
        )
      )
    );
  }

  function renderMountBody(){
    var fly = draft.mountFly||'';
    var zodiac = draft.mountZodiac||[];
    return React.createElement('div',null,
      React.createElement('div',{className:'sect-title'},'传说坐骑数量'),
      React.createElement('div',{className:'tag-grid'},
        MOUNT_FLY.map(function(f){return React.createElement('div',{key:f,className:'tag-item'+(fly===f?' selected':''),
          onClick:function(){setDraft(function(p){return Object.assign({},p,{mountFly:p.mountFly===f?'':f});});}},f);})
      ),
      React.createElement('div',{className:'sect-title'},'星座组合（多选）',React.createElement('span',{onClick:function(e){e.stopPropagation();setDraft(function(p){return Object.assign({},p,{mountZodiacAny:!p.mountZodiacAny});});},style:{borderRadius:10,fontSize:11,padding:'2px 8px',marginLeft:6,fontWeight:600,cursor:'pointer',lineHeight:'16px',background:draft.mountZodiacAny?'#d8e2ff':'#f1f3f4',color:draft.mountZodiacAny?'#1A73E8':'#70757A',border:draft.mountZodiacAny?'1px solid #1A73E8':'1px solid transparent',transition:'all .2s'}},'一件即可')),
      React.createElement('div',{className:'tag-grid'},
        MOUNT_ZODIAC.map(function(z){return React.createElement('div',{key:z,className:'tag-item'+(zodiac.includes(z)?' selected':''),
          onClick:function(){setDraft(function(p){return Object.assign({},p,{mountZodiac:p.mountZodiac.includes(z)?p.mountZodiac.filter(function(x){return x!==z;}):p.mountZodiac.concat([z])});});}},z);})
      )
    );
  }

  function renderUnlockBody(){
    var unlockTab = draft.unlockTab||'T4';
    var unlockProf = draft.unlockProf||'战士';
    var unlock = draft.unlock||emptyUnlock();
    var curProfParts = (unlock[unlockTab]&&unlock[unlockTab].profs)?(unlock[unlockTab].profs[unlockProf]||[]):[];

    return React.createElement('div',null,
      React.createElement('div',{className:'pub3-tiertabs'},
        UNLOCK_T.map(function(t){
          var has = false;
          var td = unlock[t];
          if(td&&td.profs){UNLOCK_PROFS.forEach(function(p){if(td.profs[p]&&td.profs[p].length)has=true;});}
          return React.createElement('div',{key:t,
            className:'pub3-tiertab'+(t===unlockTab?' active':'')+(has?' configured':''),
            onClick:function(){setDraft(function(p){return Object.assign({},p,{unlockTab:t,unlockProf:'战士'});});}},
            t,has&&React.createElement('span',{className:'pub3-tierdot'}));
        })
      ),
      React.createElement('div',{style:{marginTop:10}},
        React.createElement('div',{className:'sect-title'},unlockTab+' — 职业'),
        React.createElement('div',{className:'pub3-tiertabs'},
          UNLOCK_PROFS.map(function(p){
            var has = unlock[unlockTab]&&unlock[unlockTab].profs&&unlock[unlockTab].profs[p]&&unlock[unlockTab].profs[p].length;
            return React.createElement('div',{key:p,
              className:'pub3-tiertab'+(p===unlockProf?' active':'')+(has?' configured':''),
              onClick:function(){setDraft(function(p2){return Object.assign({},p2,{unlockProf:p});});}},
              p,has&&React.createElement('span',{className:'pub3-tierdot'}));
          })
        ),
        React.createElement('div',{className:'sect-title',style:{marginTop:10}},unlockTab+' '+unlockProf+' — 装备部位（多选）'),
        React.createElement('div',{className:'tag-grid'},
          (UNLOCK_PARTS[unlockProf]||[]).map(function(pt){
            var sel = curProfParts.includes(pt);
            return React.createElement('div',{key:pt,className:'tag-item'+(sel?' selected':''),
              onClick:function(){
                setDraft(function(prev){
                  var ul = cloneObj(prev.unlock||emptyUnlock());
                  if(!ul[unlockTab])ul[unlockTab]={profs:{'战士':[],'输出':[],'法师':[]}};
                  if(!ul[unlockTab].profs)ul[unlockTab].profs={'战士':[],'输出':[],'法师':[]};
                  var plist = ul[unlockTab].profs[unlockProf]||[];
                  ul[unlockTab].profs[unlockProf] = sel?plist.filter(function(x){return x!==pt;}):plist.concat([pt]);
                  return Object.assign({},prev,{unlock:ul});
                });
              }},pt);
          })
        )
      )
    );
  }
}

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