(function() {
  var useState = React.useState;
  var useEffect = React.useEffect;

  var LOADOUT_KEY = 'cb_inv_loadout';

  var SLOT_DEFS = [
    { id: 'helmet', label: 'Style', hint: 'Architectural style', kinds: ['style'], icon: '🏛' },
    { id: 'vest', label: 'Asset Pack', hint: 'Primary building pack', kinds: ['asset_pack'], icon: '📦' },
    { id: 'backpack', label: 'Template', hint: 'Design template', kinds: ['template', 'presentation'], icon: '🗂' },
    { id: 'main', label: 'AI Tool', hint: 'Premium AI capability', kinds: ['ai_tool'], icon: '✦' },
    { id: 'side', label: 'Texture', hint: 'Materials & textures', kinds: ['texture'], icon: '🧱' },
    { id: 'melee', label: 'Gift', hint: 'Showcase gift', kinds: ['gift'], icon: '🎁' },
  ];

  var TABS = [
    { id: 'all', label: 'All', icon: '▣' },
    { id: 'assets', label: 'Assets', icon: '🏗' },
    { id: 'premiumTools', label: 'AI Tools', icon: '✦' },
    { id: 'templates', label: 'Templates', icon: '📐' },
    { id: 'gifts', label: 'Gifts', icon: '🎁' },
    { id: 'purchases', label: 'Bought', icon: '💳' },
    { id: 'send', label: 'Send', icon: '↗' },
  ];

  var RARITY_ORDER = { legendary: 5, epic: 4, rare: 3, uncommon: 2, common: 1 };

  var KIND_ICON = {
    asset_pack: '🏗',
    template: '📐',
    texture: '🧱',
    ai_tool: '✦',
    gift: '🎁',
    presentation: '🖥',
    style: '🏛',
  };

  var A = window.CBAssets;

  // Best art for an item: mapped gift/pack card → API preview → kind icon → null.
  function itemArt(item) {
    if (!item) return null;
    return (A && A.itemArt(item))
      || (item.previewImages && item.previewImages[0])
      || (A && A.kindIcon(item.kind))
      || null;
  }

  function inferRarity(item) {
    if (item && item.rarity) return item.rarity;
    var p = (item && item.priceCoins) || 0;
    if (p >= 450) return 'legendary';
    if (p >= 300) return 'epic';
    if (p >= 180) return 'rare';
    if (p >= 100) return 'uncommon';
    return 'common';
  }

  function loadLoadout() {
    try {
      return JSON.parse(localStorage.getItem(LOADOUT_KEY) || '{}') || {};
    } catch (e) {
      return {};
    }
  }

  function saveLoadout(lo) {
    try { localStorage.setItem(LOADOUT_KEY, JSON.stringify(lo)); } catch (e) {}
  }

  function InventoryPage() {
    var _data = useState(null); var data = _data[0], setData = _data[1];
    var _gifts = useState([]); var gifts = _gifts[0], setGifts = _gifts[1];
    var _tab = useState('all'); var tab = _tab[0], setTab = _tab[1];
    var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
    var _selected = useState(null); var selected = _selected[0], setSelected = _selected[1];
    var _loadout = useState(loadLoadout); var loadout = _loadout[0], setLoadout = _loadout[1];
    var _query = useState(''); var query = _query[0], setQuery = _query[1];
    var _sort = useState('rarity'); var sort = _sort[0], setSort = _sort[1];
    var _recipient = useState(''); var recipient = _recipient[0], setRecipient = _recipient[1];
    var _giftId = useState(''); var giftId = _giftId[0], setGiftId = _giftId[1];
    var _msg = useState(''); var msg = _msg[0], setMsg = _msg[1];
    var _busy = useState(false); var busy = _busy[0], setBusy = _busy[1];
    var _wallet = useState(null); var wallet = _wallet[0], setWallet = _wallet[1];

    var params = window.UserRouter.getParams() || {};
    var user = window.AuthState && window.AuthState.getUser();

    useEffect(function() {
      if (params.sendGiftTo) {
        setRecipient(params.sendGiftTo);
        setTab('send');
      }
      if (!window.AuthState || !window.AuthState.isLoggedIn()) {
        window.showUserToast('Sign in to view inventory', 'rose');
        setLoading(false);
        return;
      }
      Promise.all([
        window.CBBuildCoins.inventory(),
        window.CBBuildCoins.listGifts(),
        window.CBBuildCoins.getWallet().catch(function() { return null; }),
      ]).then(function(res) {
        setData(res[0]);
        setGifts((res[1] && res[1].gifts) || []);
        setWallet(res[2] && res[2].wallet);
        if (params.sendGiftTo && res[1] && res[1].gifts && res[1].gifts[0]) {
          setGiftId(res[1].gifts[0]._id);
        }
        var items = (res[0] && res[0].items) || [];
        if (items[0]) setSelected(items[0]);
        setLoading(false);
      }).catch(function(e) {
        window.showUserToast(e.message || 'Inventory unavailable', 'rose');
        setLoading(false);
      });
    }, []);

    var allItems = (data && data.items) || [];
    var grouped = (data && data.grouped) || {};

    var list;
    if (tab === 'all' || tab === 'send') list = allItems.slice();
    else list = (grouped[tab] || []).slice();

    var q = query.trim().toLowerCase();
    if (q) {
      list = list.filter(function(row) {
        var it = row.item || {};
        return (it.title || '').toLowerCase().indexOf(q) >= 0
          || (it.kind || '').toLowerCase().indexOf(q) >= 0
          || (it.category || '').toLowerCase().indexOf(q) >= 0
          || (it.rarity || '').toLowerCase().indexOf(q) >= 0;
      });
    }

    list.sort(function(a, b) {
      var ia = a.item || {};
      var ib = b.item || {};
      if (sort === 'rarity') {
        return (RARITY_ORDER[inferRarity(ib)] || 0) - (RARITY_ORDER[inferRarity(ia)] || 0);
      }
      if (sort === 'name') return (ia.title || '').localeCompare(ib.title || '');
      if (sort === 'newest') return new Date(b.createdAt || 0) - new Date(a.createdAt || 0);
      return 0;
    });
    var filtered = list;

    var rarityStats = { common: 0, uncommon: 0, rare: 0, epic: 0, legendary: 0 };
    var totalXp = 0;
    allItems.forEach(function(row) {
      var it = row.item || {};
      var r = inferRarity(it);
      rarityStats[r] = (rarityStats[r] || 0) + 1;
      totalXp += it.xpBonus || 0;
    });

    function equipToSlot(slotId, row) {
      var next = Object.assign({}, loadout);
      next[slotId] = row._id;
      setLoadout(next);
      saveLoadout(next);
      if (window.CBSfx) window.CBSfx.play('xp');
      // PUBG equip: item art rockets into the slot and detonates on impact
      requestAnimationFrame(function() {
        var slotEl = document.querySelector('.inv-slot-' + slotId);
        if (!slotEl || !window.CBGameFX) return;
        var RC = { common: '#9CA3AF', uncommon: '#34D399', rare: '#60A5FA', epic: '#C084FC', legendary: '#FBBF24' };
        var color = RC[inferRarity(row.item || {})] || '#5CE1E6';
        var srcEl = document.querySelector('.inv-slot.selected') || null;
        var art = window.CBAssets ? window.CBAssets.itemArt(row.item || {}) : null;
        if (window.CBGameFX.artFly && srcEl && art) {
          window.CBGameFX.artFly(srcEl, slotEl, art, color);
        } else {
          window.CBGameFX.bump(slotEl);
          window.CBGameFX.sparkle(slotEl, 8, color);
        }
      });
      var slot = SLOT_DEFS.find(function(s){ return s.id === slotId; });
      window.showUserToast('Equipped to ' + ((slot && slot.label) || 'slot'), 'lime');
    }

    function unequipSlot(slotId) {
      var next = Object.assign({}, loadout);
      delete next[slotId];
      setLoadout(next);
      saveLoadout(next);
    }

    function findRowById(id) {
      for (var i = 0; i < allItems.length; i++) {
        if (allItems[i]._id === id) return allItems[i];
      }
      return null;
    }

    function autoEquip(row) {
      var item = row.item || {};
      var slot = SLOT_DEFS.find(function(s) {
        return s.kinds.indexOf(item.kind) >= 0;
      }) || SLOT_DEFS[1];
      equipToSlot(slot.id, row);
    }

    function isEquipped(row) {
      var id = row._id;
      return Object.keys(loadout).some(function(k) { return loadout[k] === id; });
    }

    async function sendGift() {
      if (!recipient || !giftId || busy) return;
      setBusy(true);
      try {
        await window.CBBuildCoins.sendGift(recipient, giftId, msg);
        var g = gifts.find(function(x){ return x._id === giftId; });
        if (window.CBGameFX) {
          window.CBGameFX.celebrate({
            art: (window.CBAssets && g) ? window.CBAssets.itemArt(g) : null,
            title: 'Gift Deployed!',
            sub: g ? g.title : 'On its way',
            rarity: g && g.rarity,
            cta: 'Sent',
          });
        } else {
          window.showUserToast('Gift sent!', 'lime');
        }
        setMsg('');
        var inv = await window.CBBuildCoins.inventory();
        setData(inv);
      } catch (e) {
        window.showUserToast(e.message || 'Gift failed', 'rose');
      } finally {
        setBusy(false);
      }
    }

    var initials = (user && user.name || '?').split(' ').map(function(n){ return n[0]||''; }).join('').slice(0,2).toUpperCase();
    var selItem = selected && selected.item ? selected.item : null;
    var selRarity = selItem ? inferRarity(selItem) : 'common';

    var gridSlots = filtered.slice();
    while (gridSlots.length < 24) gridSlots.push(null);

    return (
      <div className="inv-screen">
        <div className="inv-topbar" data-tour="inventory-hero">
          <button className="back-btn"
            onMouseEnter={function(){ document.body.classList.add('hov'); }}
            onMouseLeave={function(){ document.body.classList.remove('hov'); }}
            onClick={function(){ window.navBack(); }}>← Back</button>
          <div className="inv-topbar-title">
            <h1>OPERATOR INVENTORY</h1>
            <p>Loadout · crates · rarity gear — BuildCoins assets</p>
          </div>
          <div className="inv-topbar-actions">
            <button className="btn btn-o" onClick={function(){ window.navigate('marketplace'); }}>Marketplace</button>
            <button className="btn btn-v" onClick={function(){ window.navigate('wallet'); }}>Wallet</button>
          </div>
        </div>

        {loading ? (
          <div className="pg-loading">OPENING CRATE…</div>
        ) : (
          <div className="inv-layout">
            <aside className="inv-loadout">
              <div className="inv-profile-card">
                <div className="inv-avatar">{initials}</div>
                <div>
                  <div className="inv-profile-name">{(user && user.name) || 'Builder'}</div>
                  <div className="inv-profile-meta">
                    {(window.CBRoles&&window.CBRoles.label(user&&user.role))||'Builder'} · {(user && user.reputation) || 0} REP
                  </div>
                </div>
              </div>

              <div className="inv-stat-strip">
                <div className="inv-mini-stat"><span>{allItems.length}</span>Items</div>
                <div className="inv-mini-stat"><span>{totalXp}</span>XP Gear</div>
                <div className="inv-mini-stat"><span>{(wallet && wallet.balance) || 0}</span>BC</div>
              </div>

              <div className="inv-rarity-bar" title="Rarity breakdown">
                {['common','uncommon','rare','epic','legendary'].map(function(r) {
                  return (
                    <div key={r} className={'inv-rarity-seg inv-r-' + r} style={{ flex: Math.max(rarityStats[r], 0.15) }}
                      title={r + ': ' + rarityStats[r]} />
                  );
                })}
              </div>

              <div className="inv-loadout-title">ACTIVE LOADOUT</div>
              <div className="inv-mannequin">
                <div className="inv-body-silhouette has-art" aria-hidden="true"
                  style={A ? { backgroundImage: 'url(' + A.mannequin() + ')' } : null} />
                {SLOT_DEFS.map(function(slot) {
                  var row = loadout[slot.id] ? findRowById(loadout[slot.id]) : null;
                  var it = row && row.item;
                  var rar = it ? inferRarity(it) : null;
                  return (
                    <button
                      key={slot.id}
                      type="button"
                      className={'inv-equip-slot inv-slot-' + slot.id + (row ? ' filled inv-r-' + rar : '')}
                      title={slot.hint}
                      onClick={function(){
                        if (row) { setSelected(row); }
                        else if (selected && selected.item && slot.kinds.indexOf(selected.item.kind) >= 0) {
                          equipToSlot(slot.id, selected);
                        } else {
                          window.showUserToast('Select a matching item, then tap this slot', 'violet');
                        }
                      }}
                      onContextMenu={function(e){
                        e.preventDefault();
                        if (row) unequipSlot(slot.id);
                      }}
                    >
                      {row ? (
                        <>
                          <span className="inv-equip-icon">
                            {A && A.kindIcon(it.kind)
                              ? <img src={A.kindIcon(it.kind)} alt="" />
                              : (KIND_ICON[it.kind] || slot.icon)}
                          </span>
                          <span className="inv-equip-name">{(it.title || '').split(' ').slice(0, 2).join(' ')}</span>
                        </>
                      ) : (
                        <>
                          <span className="inv-equip-icon dim">
                            {A && A.slotPlate(slot.id)
                              ? <img src={A.slotPlate(slot.id)} alt="" />
                              : slot.icon}
                          </span>
                          <span className="inv-equip-name dim">{slot.label}</span>
                        </>
                      )}
                    </button>
                  );
                })}
              </div>
              <p className="inv-loadout-hint">Tap slot to equip selected · right-click to unequip</p>
            </aside>

            <section className="inv-crate">
              <div className="inv-crate-toolbar">
                <div className="inv-tabs">
                  {TABS.map(function(t) {
                    var count = t.id === 'all' ? allItems.length
                      : t.id === 'send' ? null
                      : (grouped[t.id] || []).length;
                    return (
                      <button key={t.id} type="button"
                        className={'inv-tab' + (tab === t.id ? ' on' : '')}
                        onClick={function(){ setTab(t.id); }}>
                        <span>
                          {A && A.tabIcon(t.id)
                            ? <img className="inv-tab-img" src={A.tabIcon(t.id)} alt="" />
                            : t.icon}
                        </span> {t.label}
                        {count != null && <em>{count}</em>}
                      </button>
                    );
                  })}
                </div>
                <div className="inv-filters">
                  <input
                    className="inv-search"
                    value={query}
                    onChange={function(e){ setQuery(e.target.value); }}
                    placeholder="Search gear…"
                  />
                  <select className="inv-sort" value={sort} onChange={function(e){ setSort(e.target.value); }}>
                    <option value="rarity">Sort: Rarity</option>
                    <option value="newest">Sort: Newest</option>
                    <option value="name">Sort: Name</option>
                  </select>
                </div>
              </div>

              {tab === 'send' ? (
                <div className="inv-send-panel">
                  <div className="inv-inspect-title">SEND GIFT DROP</div>
                  <label className="bc-card-meta">Recipient user ID</label>
                  <input className="inv-search" style={{ width:'100%', marginBottom:12 }}
                    value={recipient} onChange={function(e){ setRecipient(e.target.value); }}
                    placeholder="User ID" />
                  <label className="bc-card-meta">Gift crate</label>
                  <select className="inv-sort" style={{ width:'100%', marginBottom:12 }}
                    value={giftId} onChange={function(e){ setGiftId(e.target.value); }}>
                    <option value="">Select a gift…</option>
                    {gifts.map(function(g) {
                      return <option key={g._id} value={g._id}>{g.title} — {g.priceCoins} BC · {g.rarity || 'common'}</option>;
                    })}
                  </select>
                  <label className="bc-card-meta">Message</label>
                  <input className="inv-search" style={{ width:'100%', marginBottom:16 }}
                    value={msg} onChange={function(e){ setMsg(e.target.value); }}
                    placeholder="Optional note" />
                  <button className="btn btn-v" disabled={busy || !recipient || !giftId} onClick={sendGift}>
                    Deploy Gift
                  </button>
                </div>
              ) : (
                <div className="inv-grid gfx-stagger" role="list" key={tab + ':' + sort}>
                  {filtered.length === 0 && (
                    <div className="inv-empty">
                      <div className="inv-empty-icon">
                        {A ? <img src={A.ui('empty-crate')} alt="" /> : '▣'}
                      </div>
                      <div>Crate empty in this category</div>
                      <button className="btn btn-v" style={{ marginTop:14 }}
                        onClick={function(){ window.navigate('marketplace'); }}>
                        Loot Marketplace
                      </button>
                    </div>
                  )}
                  {gridSlots.map(function(row, idx) {
                    if (!row) {
                      return <div key={'empty-' + idx} className="inv-slot empty" aria-hidden="true"
                        style={{ '--gfx-i': Math.min(idx, 18) }} />;
                    }
                    var item = row.item || {};
                    var rar = inferRarity(item);
                    var active = selected && selected._id === row._id;
                    var equipped = isEquipped(row);
                    var img = itemArt(item);
                    return (
                      <button
                        key={row._id}
                        type="button"
                        role="listitem"
                        style={{ '--gfx-i': Math.min(idx, 18) }}
                        className={'inv-slot inv-r-' + rar + (active ? ' selected' : '') + (equipped ? ' equipped' : '') + (rar === 'legendary' ? ' gfx-legendary' : '')}
                        onClick={function(){
                          setSelected(row);
                          if (window.CBHaptics) window.CBHaptics.play('tick');
                        }}
                        onDoubleClick={function(){ autoEquip(row); }}
                      >
                        <div className="inv-slot-glow" />
                        <div className="inv-slot-rarity">{rar}</div>
                        {equipped && (
                          <div className="inv-slot-eq">
                            {A ? <img src={A.eqBadge()} alt="equipped" /> : 'EQ'}
                          </div>
                        )}
                        <div className="inv-slot-art">
                          {img
                            ? <img src={img} alt="" />
                            : <span className="inv-slot-emoji">{KIND_ICON[item.kind] || '▣'}</span>}
                        </div>
                        <div className="inv-slot-name">{item.title || 'Item'}</div>
                        <div className="inv-slot-meta">
                          {(item.kind || 'item').replace(/_/g, ' ')}
                          {item.xpBonus ? ' · +' + item.xpBonus + 'XP' : ''}
                        </div>
                      </button>
                    );
                  })}
                </div>
              )}
            </section>

            <aside className={'inv-inspect inv-r-' + selRarity}>
              {selItem ? (
                <>
                  <div className="inv-inspect-stage">
                    <div className="inv-inspect-rarity">{selRarity}</div>
                    <div className="inv-inspect-art gfx-art-pop" key={selected._id}>
                      {itemArt(selItem)
                        ? <img src={itemArt(selItem)} alt="" />
                        : <div className="inv-inspect-emoji">{KIND_ICON[selItem.kind] || '▣'}</div>}
                      <div className="inv-inspect-shine"
                        style={A ? { backgroundImage: 'url(' + A.ui('inspect-shine') + ')' } : null} />
                    </div>
                    <div className="inv-inspect-pedestal" aria-hidden="true" />
                  </div>

                  <div className="inv-inspect-head">
                    <h2 className="inv-inspect-title">{selItem.title}</h2>
                    <span className="inv-inspect-level" title="Item version">
                      <b>⚡</b>{selItem.version || '1.0'}
                    </span>
                  </div>
                  <div className="inv-inspect-sub">
                    {[(selItem.kind || '').replace(/_/g, ' '), (selItem.category || '').replace(/_/g, ' '), selected.source]
                      .filter(Boolean).join(' · ')}
                  </div>

                  {/* Bars carry only numbers the item actually has. The reference's
                      HEALTH / DEFENSES / PREPARATION are combat stats CityBuildRR
                      gear has no equivalent of — inventing them would put made-up
                      figures in front of users. */}
                  <div className="inv-inspect-bars">
                    <div className="inv-bar">
                      <span className="inv-bar-label">Rarity</span>
                      <span className="inv-bar-val">{(RARITY_ORDER[selRarity] || 1)}/5</span>
                      <i style={{ '--pct': (((RARITY_ORDER[selRarity] || 1) / 5) * 100) + '%' }} />
                    </div>
                    <div className="inv-bar">
                      <span className="inv-bar-label">XP bonus</span>
                      <span className="inv-bar-val">+{selItem.xpBonus || 0}</span>
                      <i style={{ '--pct': Math.min(100, (selItem.xpBonus || 0)) + '%' }} />
                    </div>
                    <div className="inv-bar">
                      <span className="inv-bar-label">Value</span>
                      <span className="inv-bar-val">{selItem.priceCoins || 0} BC</span>
                      <i style={{ '--pct': Math.min(100, (selItem.priceCoins || 0) / 5) + '%' }} />
                    </div>
                    <div className="inv-bar">
                      <span className="inv-bar-label">Compatibility</span>
                      <span className="inv-bar-val">{selItem.compatibility || 'AI + AR'}</span>
                      <i className="inv-bar-full" style={{ '--pct': '100%' }} />
                    </div>
                  </div>

                  <div className="inv-inspect-section">Description</div>
                  <p className="inv-inspect-desc">
                    {selItem.description || 'Premium CityBuildRR gear for AI-assisted design and AR presentation.'}
                  </p>
                  {selected.giftedBy && (
                    <div className="inv-inspect-gift">
                      Gifted by <strong>{selected.giftedBy.name}</strong>
                      {selected.message ? ' — “' + selected.message + '”' : ''}
                    </div>
                  )}
                  <div className="inv-inspect-actions">
                    <button className="inv-cta inv-cta--primary" onClick={function(){ autoEquip(selected); }}>
                      {isEquipped(selected) ? 'Re-equip' : 'Equip to loadout'}
                    </button>
                    <button className="inv-cta inv-cta--ghost" onClick={function(){ window.navigate('marketplace'); }}>
                      Marketplace
                    </button>
                    {selItem.kind === 'gift' && (
                      <button className="btn btn-o" onClick={function(){
                        setTab('send');
                        setGiftId(selItem._id);
                      }} className="inv-cta inv-cta--ghost">Send gift</button>
                    )}
                  </div>
                </>
              ) : (
                <div className="inv-inspect-empty">
                  <div className="inv-inspect-emoji">
                    {A ? <img className="inv-empty-img" src={A.ui('empty-crate')} alt="" /> : '▣'}
                  </div>
                  <p>Select an item to see its stats and equip it.</p>
                </div>
              )}
            </aside>
          </div>
        )}
      </div>
    );
  }

  window.UserInventoryPage = InventoryPage;
})();
