/* global React, GAMES, Icon, CoinIcon, useShop, useCoins, SHASTE_API */

function ShopPage() {
  const [gameSlug, setGameSlug] = React.useState(() => (GAMES[0] && GAMES[0].slug) || '');
  const [category, setCategory] = React.useState('all');
  const [purchaseState, setPurchaseState] = React.useState({ loadingId: null, error: '', success: '' });

  const { data: shopData, loading: shopLoading, error: shopError } = useShop(gameSlug);
  const { data: coinsData, loading: coinsLoading } = useCoins();

  const itemsRaw = Array.isArray(shopData && shopData.items)
    ? shopData.items
    : (Array.isArray(shopData) ? shopData : []);

  const categories = React.useMemo(() => {
    const values = new Set();
    itemsRaw.forEach((item) => {
      if (item && typeof item.category === 'string' && item.category.trim()) {
        values.add(item.category.trim());
      }
    });
    return ['all', ...Array.from(values)];
  }, [itemsRaw]);

  React.useEffect(() => {
    if (!categories.includes(category)) {
      setCategory('all');
    }
  }, [categories, category]);

  const items = itemsRaw.filter((item) => category === 'all' || item.category === category);

  const balance = Number.isFinite(coinsData && coinsData.balance) ? coinsData.balance : 0;

  const onPurchase = async (itemId) => {
    if (!SHASTE_API || typeof SHASTE_API.purchaseShopItem !== 'function') {
      setPurchaseState({ loadingId: null, error: 'Shop API is unavailable right now.', success: '' });
      return;
    }

    setPurchaseState({ loadingId: itemId, error: '', success: '' });
    try {
      await SHASTE_API.purchaseShopItem(itemId);
      setPurchaseState({ loadingId: null, error: '', success: 'Purchase completed successfully.' });
    } catch (err) {
      setPurchaseState({ loadingId: null, error: err && err.message ? err.message : 'Could not complete purchase.', success: '' });
    }
  };

  return (
    <div className="container fade-in" style={{ maxWidth: 980 }}>
      <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Store</div>
          <h1 className="h-display" style={{ fontSize: 'clamp(32px, 4vw, 46px)', marginTop: 6 }}>Game Shop</h1>
        </div>
        <div className="chip chip--coin" title="Current balance">
          <CoinIcon size={16} />
          <span className="chip__num">{coinsLoading ? '…' : balance.toLocaleString()}</span>
        </div>
      </div>

      <div className="card" style={{ marginTop: 18, display: 'grid', gap: 12, gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))' }}>
        <label style={{ display: 'grid', gap: 6 }}>
          <span className="eyebrow" style={{ fontSize: 10 }}>Game</span>
          <select className="input" value={gameSlug} onChange={(e) => setGameSlug(e.target.value)}>
            {GAMES.map((game) => (
              <option key={game.slug} value={game.slug}>{game.title}</option>
            ))}
          </select>
        </label>

        <label style={{ display: 'grid', gap: 6 }}>
          <span className="eyebrow" style={{ fontSize: 10 }}>Category</span>
          <select className="input" value={category} onChange={(e) => setCategory(e.target.value)}>
            {categories.map((cat) => (
              <option key={cat} value={cat}>{cat === 'all' ? 'All categories' : cat}</option>
            ))}
          </select>
        </label>
      </div>

      {purchaseState.error && <div className="card" style={{ marginTop: 14, borderColor: 'rgba(255,92,169,.5)', color: '#ffc4de' }}>{purchaseState.error}</div>}
      {purchaseState.success && <div className="card" style={{ marginTop: 14, borderColor: 'rgba(96,220,140,.5)', color: '#ccffd9' }}>{purchaseState.success}</div>}

      {shopError && <div className="card" style={{ marginTop: 14, color: '#ffd7d7' }}>{shopError.message || 'Failed to load shop items.'}</div>}
      {shopLoading && <div className="card" style={{ marginTop: 14 }}>Loading shop items…</div>}

      {!shopLoading && !shopError && (
        <div style={{ marginTop: 16, display: 'grid', gap: 12 }}>
          {items.length === 0 && <div className="card">No items found for this filter.</div>}
          {items.map((item) => {
            const price = Number.isFinite(item && item.price) ? item.price : 0;
            const disabled = purchaseState.loadingId === item.id || balance < price;
            return (
              <div key={item.id} className="card" style={{ display: 'grid', gap: 10 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                  <div>
                    <h3 style={{ margin: 0 }}>{item.name || 'Unknown item'}</h3>
                    {item.description && <p style={{ margin: '6px 0 0', color: 'var(--muted)' }}>{item.description}</p>}
                  </div>
                  <div className="chip chip--coin"><CoinIcon size={14} /> <span className="chip__num">{price.toLocaleString()}</span></div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
                  <div style={{ color: 'var(--subtle)', fontSize: 12 }}>{item.category || 'Uncategorized'}</div>
                  <button className="btn btn--primary btn--sm" disabled={disabled} onClick={() => onPurchase(item.id)}>
                    {purchaseState.loadingId === item.id ? 'Purchasing…' : 'Buy'}
                    <Icon name="arrow" size={12} />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ShopPage });
