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

  var PLACEHOLDER = 'https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=600&q=80';
  var A = window.CBAssets;

  // Mapped pack/gift card art wins over generic API previews and the Unsplash fallback.
  function itemArt(item) {
    return (A && A.itemArt(item))
      || (item.previewImages && item.previewImages[0])
      || PLACEHOLDER;
  }

  var SPOT_OPTIONS = [
    { hours: 24, label: '24 Hours' },
    { hours: 72, label: '3 Days' },
    { hours: 168, label: '7 Days' },
    { hours: 720, label: '30 Days' },
  ];

  function MarketplacePage() {
    var _items = useState([]); var items = _items[0], setItems = _items[1];
    var _cats = useState([]); var cats = _cats[0], setCats = _cats[1];
    var _cat = useState(''); var cat = _cat[0], setCat = _cat[1];
    var _ai = useState([]); var ai = _ai[0], setAi = _ai[1];
    var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
    var _busy = useState(null); var busy = _busy[0], setBusy = _busy[1];
    var _view = useState('shop'); var view = _view[0], setView = _view[1];
    var _spotHours = useState(24); var spotHours = _spotHours[0], setSpotHours = _spotHours[1];

    function load() {
      setLoading(true);
      var params = {};
      if (cat) params.category = cat;
      Promise.all([
        window.CBBuildCoins.listMarketplace(params),
        window.CBBuildCoins.aiFeatures(),
      ]).then(function(res) {
        setItems((res[0] && res[0].items) || []);
        setCats((res[0] && res[0].categories) || []);
        setAi((res[1] && res[1].features) || []);
        setLoading(false);
      }).catch(function(e) {
        window.showUserToast(e.message || 'Marketplace unavailable', 'rose');
        setLoading(false);
      });
    }

    useEffect(function() { load(); }, [cat]);

    function requireAuth() {
      if (!window.AuthState || !window.AuthState.isLoggedIn()) {
        window.showUserToast('Sign in to purchase', 'rose');
        return false;
      }
      return true;
    }

    async function buy(item) {
      if (!requireAuth() || busy) return;
      setBusy(item._id);
      try {
        await window.CBBuildCoins.buyItem(item._id);
        if (window.CBHaptics) window.CBHaptics.play('xp');
        if (window.CBGameFX) {
          window.CBGameFX.celebrate({
            art: itemArt(item),
            title: 'Unlocked!',
            sub: item.title,
            rarity: item.rarity,
            cta: 'Nice',
          });
        } else {
          window.showUserToast('Unlocked ' + item.title, 'lime');
        }
      } catch (e) {
        window.showUserToast(e.message || 'Purchase failed', 'rose');
      } finally {
        setBusy(null);
      }
    }

    async function wish(item, btnEl) {
      if (!requireAuth()) return;
      try {
        var r = await window.CBBuildCoins.wishlist(item._id);
        if (window.CBGameFX && btnEl) {
          window.CBGameFX.pop(btnEl);
          if (r.wishlisted) window.CBGameFX.sparkle(btnEl, 6, '#FB7185');
        }
        window.showUserToast(r.wishlisted ? 'Added to wishlist' : 'Removed from wishlist', 'violet');
      } catch (e) {
        window.showUserToast(e.message || 'Wishlist failed', 'rose');
      }
    }

    async function unlockAi(feat) {
      if (!requireAuth() || busy) return;
      setBusy(feat.key);
      try {
        await window.CBBuildCoins.unlockAi(feat.key);
        if (window.CBGameFX && A) {
          window.CBGameFX.celebrate({
            art: A.aiIcon(feat.key),
            title: 'AI Unlocked!',
            sub: feat.label,
            rarity: 'epic',
            cta: 'Let’s build',
          });
        } else {
          window.showUserToast('Unlocked ' + feat.label, 'lime');
        }
      } catch (e) {
        window.showUserToast(e.message || 'Unlock failed', 'rose');
      } finally {
        setBusy(null);
      }
    }

    async function buySpotlight() {
      if (!requireAuth() || busy) return;
      var user = window.AuthState.getUser();
      setBusy('spotlight');
      try {
        await window.CBBuildCoins.buySpotlight({
          targetType: 'profile',
          targetId: user._id,
          durationHours: spotHours,
          hours: spotHours,
        });
        if (window.CBGameFX && A) {
          window.CBGameFX.celebrate({
            art: A.spotlightTile(spotHours),
            title: 'Spotlight On!',
            sub: 'Visibility boost — never rankings',
            cta: 'Shine',
          });
        } else {
          window.showUserToast('Spotlight active — visibility only, not rankings', 'lime');
        }
      } catch (e) {
        window.showUserToast(e.message || 'Spotlight failed', 'rose');
      } finally {
        setBusy(null);
      }
    }

    return (
      <div className="bc-screen">
        <div className="bc-hero" data-tour="bc-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>
          <h1>Marketplace</h1>
          <p>Premium architectural assets, AI tools, and spotlights. BuildCoins never buy votes or guarantee winners.</p>
        </div>

        <div className="bc-tabs bc-tabs--primary" data-tour="bc-tabs">
          {/* Real tabs only — Wallet/Inventory navigate away and must not
              sit inside a tablist, which may only contain role="tab". */}
          <div className="bc-tabset" role="tablist" aria-label="Marketplace sections">
            {['shop', 'ai', 'spotlight'].map(function(v) {
              var labels = { shop: 'Assets', ai: 'AI Premium', spotlight: 'Spotlight' };
              var marks = { shop: '◈', ai: '✦', spotlight: '◎' };
              return (
                <button
                  key={v}
                  type="button"
                  role="tab"
                  aria-selected={view === v}
                  className={'bc-tab' + (view === v ? ' on' : '')}
                  onClick={function(){ setView(v); }}
                >
                  <span className="play-tab-mark" aria-hidden="true">{marks[v]}</span>
                  {labels[v]}
                </button>
              );
            })}
          </div>

          <span className="bc-tabs-sep" aria-hidden="true" />

          <nav className="bc-tabset bc-tabset--nav" aria-label="BuildCoins">
            <button type="button" className="bc-tab bc-tab--link" onClick={function(){ window.navigate('wallet'); }}>
              <span className="play-tab-mark" aria-hidden="true">⬡</span> Wallet
            </button>
            <button type="button" className="bc-tab bc-tab--link" onClick={function(){ window.navigate('inventory'); }}>
              <span className="play-tab-mark" aria-hidden="true">▣</span> Inventory
            </button>
          </nav>
        </div>

        {view === 'shop' && (
          <>
            {/* Filters, not tabs — a toggle group, so aria-pressed rather
                than a tablist whose children were never role="tab". */}
            <div className="bc-tabs bc-tabs--chips" role="group" aria-label="Filter assets by category">
              <button type="button" className={'bc-tab' + (!cat ? ' on' : '')}
                aria-pressed={!cat} onClick={function(){ setCat(''); }}>All</button>
              {cats.slice(0, 12).map(function(c) {
                return (
                  <button key={c} type="button" className={'bc-tab' + (cat === c ? ' on' : '')}
                    aria-pressed={cat === c} onClick={function(){ setCat(c); }}>
                    {A && A.catIcon(c) && <img className="bc-cat-icon" src={A.catIcon(c)} alt="" />}
                    {String(c).replace(/_/g, ' ')}
                  </button>
                );
              })}
            </div>
            {loading ? <div className="pg-loading">LOADING…</div> : (
              <div className="bc-grid gfx-stagger" key={cat || 'all'}>
                {items.map(function(item, idx) {
                  var img = itemArt(item);
                  var legendary = item.rarity === 'legendary' || (item.priceCoins || 0) >= 450;
                  return (
                    <div key={item._id}
                      className={'bc-card bc-card--asset' + (legendary ? ' gfx-legendary' : '')}
                      data-tour={idx === 0 ? 'bc-card' : undefined}
                      style={{ '--gfx-i': Math.min(idx, 16) }}>
                      <div className="bc-card-media">
                        <img src={img} alt="" loading="lazy" />
                        {item.kind && (
                          <span className="bc-chip bc-chip--kind">{String(item.kind).replace(/_/g, ' ')}</span>
                        )}
                        {legendary && <span className="bc-chip bc-chip--rare">Legendary</span>}
                      </div>
                      <div className="bc-card-body">
                        <div className="bc-card-meta">{item.category}</div>
                        <h3 className="bc-card-title">{item.title}</h3>
                        <div className="bc-price">
                          <span className="bc-price-n">{(item.priceCoins || 0).toLocaleString()}</span>
                          <span className="bc-price-unit">BC</span>
                        </div>
                        <div className="bc-card-actions">
                          <button className="btn btn-v bc-buy" disabled={busy === item._id}
                            onClick={function(){ buy(item); }}>
                            {busy === item._id ? 'Buying…' : 'Buy'}
                          </button>
                          <button className="btn btn-o bc-wish"
                            aria-label={'Save ' + item.title + ' to wishlist'}
                            onClick={function(e){ wish(item, e.currentTarget); }}>♡</button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}

        {view === 'ai' && (
          <div className="bc-grid gfx-stagger">
            {ai.map(function(feat, idx) {
              return (
                <div key={feat.key} className="bc-card" style={{ '--gfx-i': Math.min(idx, 16) }}>
                  <div className="bc-card-body">
                    {A && A.aiIcon(feat.key) && (
                      <img className="bc-ai-icon" src={A.aiIcon(feat.key)} alt="" />
                    )}
                    <div className="bc-card-meta">AI Premium</div>
                    <h3 className="bc-card-title">{feat.label}</h3>
                    <p style={{ fontSize:13, color:'var(--text-dim)', margin:0 }}>{feat.description || ''}</p>
                    <div className="bc-price">{feat.priceCoins} BC</div>
                    <button className="btn btn-v" disabled={busy === feat.key}
                      onClick={function(){ unlockAi(feat); }}>Unlock</button>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {view === 'spotlight' && (
          <div className="bc-tx">
            <p style={{ color:'var(--text-dim)', marginBottom:16 }}>
              Feature your profile for limited time. Spotlights increase visibility only — they do not affect challenge winners or reputation.
            </p>
            <div className="bc-grid bc-spot-grid">
              {SPOT_OPTIONS.map(function(opt) {
                var tile = A && A.spotlightTile(opt.hours);
                return (
                  <button key={opt.hours} type="button"
                    className={'bc-card bc-spot-card' + (spotHours === opt.hours ? ' on' : '')}
                    onClick={function(){ setSpotHours(opt.hours); }}>
                    {tile && <img src={tile} alt="" />}
                    <div className="bc-card-body">
                      <h3 className="bc-card-title">{opt.label}</h3>
                    </div>
                  </button>
                );
              })}
            </div>
            <button className="btn btn-v" disabled={busy === 'spotlight'} onClick={buySpotlight}>
              Activate Spotlight
            </button>
          </div>
        )}
      </div>
    );
  }

  window.UserMarketplacePage = MarketplacePage;
})();
