// Gems Store — cosmetic-only shop. Gems buy avatars & avatar frames, nothing
// else. AI (Atlas Coach) is a separate paid feature and is NEVER sold for gems.

function GemsStoreSection() {
  const { state, actions } = useStore();
  const mobile = useIsMobile();
  const [flash, setFlash] = React.useState(null);          // { id, kind:'buy'|'equip'|'poor' }

  const owned    = state.store.owned || [];
  const balance  = state.gems.balance;
  const equipped = state.cosmetics || { avatar: 'default', frame: 'none' };
  const name     = state.user.name || '';

  const isOwned = (item) => item.cost === 0 || owned.includes(item.id);

  const buy = (item) => {
    if (isOwned(item)) return;
    if (balance < item.cost) { setFlash({ id: item.id, kind: 'poor' }); setTimeout(() => setFlash(null), 1800); return; }
    actions.buyStoreItem(item.id, item.cost);
    setFlash({ id: item.id, kind: 'buy' }); setTimeout(() => setFlash(null), 2200);
  };
  const equip = (kind, id) => { actions.equipCosmetic(kind, id); setFlash({ id, kind: 'equip' }); setTimeout(() => setFlash(null), 1600); };

  const lv = (typeof xpToLevel === 'function') ? xpToLevel(state.xp || 0) : null;

  return (
    <section style={{
      padding: mobile ? '18px 16px calc(72px + env(safe-area-inset-bottom))' : '40px 32px 120px',
      background: '#FAFAF7', borderTop: '1px solid rgba(15,26,46,0.06)', overflowX: 'hidden',
    }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>

        {flash && flash.kind === 'buy' && (
          <div style={{
            position: 'fixed', top: 80, right: mobile ? 16 : 32, zIndex: 200,
            background: '#0F1A2E', color: '#FAFAF7', padding: '10px 20px', borderRadius: 999,
            fontFamily: '"Inter",system-ui', fontSize: 14, fontWeight: 700,
            animation: 'fadeIn 0.3s ease', boxShadow: '0 8px 32px rgba(15,26,46,0.25)',
          }}>✓ Añadido a tu colección</div>
        )}

        {/* Compact balance + level strip — the only thing above the items, so the
            redeemable avatars & frames are the first thing you see (no scrolling). */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap',
          padding: mobile ? '12px 16px' : '14px 20px', borderRadius: 16, marginBottom: 10,
          background: '#0F1A2E', color: '#FAFAF7',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
            <span style={{ fontSize: 20, lineHeight: 1 }} aria-hidden="true">💎</span>
            <span style={{ fontFamily: '"Inter",system-ui', fontSize: mobile ? 24 : 28, fontWeight: 800, letterSpacing: -0.8, lineHeight: 1 }}>
              {balance.toLocaleString('es-ES')}
            </span>
            <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 600, color: 'rgba(250,250,247,0.55)' }}>gemas</span>
          </div>
          {lv && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
              <span style={{ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 999, background: 'rgba(59,130,246,0.18)', border: '1px solid rgba(59,130,246,0.4)' }}>
                <span style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 9, fontWeight: 700, color: '#93C5FD', letterSpacing: 0.5 }}>NIVEL</span>
                <span style={{ fontFamily: '"Inter",system-ui', fontSize: 15, fontWeight: 900, lineHeight: 1 }}>{lv.level}</span>
              </span>
              <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, letterSpacing: -0.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lv.title}</span>
            </div>
          )}
        </div>

        {/* "Cómo funcionan las gemas" — kept visible but small */}
        {(typeof GemsHelpButton === 'function') && (
          <div style={{ marginBottom: mobile ? 16 : 22 }}>
            <GemsHelpButton style={{ fontSize: 12 }} />
          </div>
        )}

        {/* ── Redeemable items first ──────────────────────────────────────────── */}
        <CosmeticGroup
          title="Avatares" kind="avatar" items={AVATARS} mobile={mobile} name={name}
          equipped={equipped} balance={balance} isOwned={isOwned} flash={flash}
          onBuy={buy} onEquip={equip}
        />
        <CosmeticGroup
          title="Marcos" kind="frame" items={FRAMES} mobile={mobile} name={name}
          equipped={equipped} balance={balance} isOwned={isOwned} flash={flash}
          onBuy={buy} onEquip={equip}
        />

        {/* ── Below the items: badges, then the system explanation ─────────────── */}
        <GsAchievements mobile={mobile} />

        <div style={{
          display: 'flex', alignItems: 'flex-start', gap: 10,
          padding: '12px 14px', borderRadius: 14, marginTop: mobile ? 24 : 36,
          background: 'rgba(42,111,219,0.06)', border: '1px solid rgba(42,111,219,0.16)',
        }}>
          <span style={{ fontSize: 16, lineHeight: 1.2 }} aria-hidden="true">💡</span>
          <p style={{ margin: 0, fontFamily: '"Inter",system-ui', fontSize: mobile ? 12 : 12.5, color: '#3A4257', lineHeight: 1.5 }}>
            Las gemas se ganan entrenando y solo se canjean por <strong>cosméticos</strong> (avatares y marcos).
            La IA de <strong>Atlas Coach</strong> será una función de pago aparte — nunca se desbloquea con gemas.
          </p>
        </div>
      </div>
    </section>
  );
}

// Compact badges/insignias block — lives below the redeemable items in the store.
function GsAchievements({ mobile }) {
  const { state } = useStore();
  if (typeof ACHIEVEMENTS === 'undefined') return null;
  const achievements = state.achievements || [];
  const unlocked = ACHIEVEMENTS.filter(a => achievements.includes(a.id)).length;
  const cats = (typeof ACHIEVEMENT_CATS !== 'undefined') ? ACHIEVEMENT_CATS : [...new Set(ACHIEVEMENTS.map(a => a.cat))];
  return (
    <div style={{ background: '#FFFFFF', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: mobile ? '18px 16px' : '20px 24px', marginTop: mobile ? 28 : 44 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 11, fontWeight: 700, color: '#5C6477', letterSpacing: 1.2, textTransform: 'uppercase' }}>Insignias</div>
        <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#6B7280' }}>{unlocked} / {ACHIEVEMENTS.length} desbloqueadas</span>
      </div>
      {cats.map(cat => {
        const list = ACHIEVEMENTS.filter(a => a.cat === cat);
        if (!list.length) return null;
        return (
          <div key={cat} style={{ marginBottom: 18 }}>
            <div style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 10, fontWeight: 700, color: '#6B7280', letterSpacing: 1, marginBottom: 10, textTransform: 'uppercase' }}>{cat}</div>
            <div style={{ display: 'grid', gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: 10 }}>
              {list.map(ach => {
                const got = achievements.includes(ach.id);
                return (
                  <div key={ach.id} style={{
                    padding: '14px 12px', borderRadius: 16,
                    background: got ? '#FFFFFF' : 'rgba(15,26,46,0.03)',
                    border: got ? '1px solid rgba(15,26,46,0.12)' : '1px dashed rgba(15,26,46,0.12)',
                    textAlign: 'center', opacity: got ? 1 : 0.5,
                  }}>
                    <div style={{ fontSize: 26, marginBottom: 6, filter: got ? 'none' : 'grayscale(1)' }}>{got ? ach.icon : '🔒'}</div>
                    <div style={{ fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 700, color: '#0F1A2E', marginBottom: 3 }}>{ach.title}</div>
                    <div style={{ fontFamily: '"Inter",system-ui', fontSize: 10, color: '#6B7280', lineHeight: 1.4 }}>{ach.desc}</div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function CosmeticGroup({ title, kind, items, mobile, name, equipped, balance, isOwned, flash, onBuy, onEquip }) {
  return (
    <div style={{ marginBottom: mobile ? 28 : 44 }}>
      <div style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 11, fontWeight: 700, color: '#5C6477', letterSpacing: 1.2, marginBottom: 14, textTransform: 'uppercase' }}>
        {title}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: mobile ? 12 : 16 }}>
        {items.map(item => (
          <CosmeticCard
            key={item.id} item={item} kind={kind} mobile={mobile} name={name}
            equipped={equipped} owned={isOwned(item)} equippedNow={equipped[kind] === item.id}
            canAfford={balance >= item.cost} flash={flash} onBuy={() => onBuy(item)} onEquip={() => onEquip(kind, item.id)}
          />
        ))}
      </div>
    </div>
  );
}

function CosmeticCard({ item, kind, mobile, name, equipped, owned, equippedNow, canAfford, flash, onBuy, onEquip }) {
  const rar = RARITY[item.rarity] || RARITY.comun;
  const previewAvatar = kind === 'avatar' ? item.id : (equipped.avatar || 'default');
  const previewFrame  = kind === 'frame'  ? item.id : (equipped.frame  || 'none');
  const poor = flash && flash.id === item.id && flash.kind === 'poor';

  let btnLabel, btnBg, btnColor, btnAction, btnDisabled = false;
  if (equippedNow)      { btnLabel = '✓ Equipado';  btnBg = '#E7F8EC'; btnColor = '#1F8B3A'; btnDisabled = true; }
  else if (owned)       { btnLabel = 'Equipar';      btnBg = '#0F1A2E'; btnColor = '#FAFAF7'; btnAction = onEquip; }
  else if (poor)        { btnLabel = 'Sin gemas';    btnBg = 'rgba(194,69,69,0.1)'; btnColor = '#C24545'; btnDisabled = true; }
  else if (canAfford)   { btnLabel = 'Comprar';      btnBg = '#0F1A2E'; btnColor = '#FAFAF7'; btnAction = onBuy; }
  else                  { btnLabel = 'No disponible'; btnBg = 'rgba(15,26,46,0.06)'; btnColor = '#6B7280'; btnDisabled = true; }

  return (
    <div style={{
      padding: mobile ? '16px 14px' : '20px 18px', borderRadius: mobile ? 18 : 22,
      background: '#FFFFFF', minWidth: 0,
      border: equippedNow ? `1.5px solid ${rar.color}` : '1px solid rgba(15,26,46,0.08)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
    }}>
      <AvatarBadge avatarId={previewAvatar} frameId={previewFrame} name={name} size={mobile ? 60 : 72}
        style={{ marginBottom: 12 }} />

      {/* Rarity chip */}
      <span style={{
        display: 'inline-block', padding: '3px 10px', borderRadius: 999,
        background: `${rar.color}1A`, color: rar.color,
        fontFamily: '"Inter",system-ui', fontSize: 10, fontWeight: 800, letterSpacing: 0.3,
        textTransform: 'uppercase', marginBottom: 8,
      }}>{rar.label}</span>

      <div style={{ fontFamily: '"Inter",system-ui', fontSize: mobile ? 14 : 15, fontWeight: 700, color: '#0F1A2E', marginBottom: 8 }}>
        {item.name}
      </div>

      {/* Cost */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 12, minHeight: 20 }}>
        {item.cost === 0 ? (
          <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 700, color: '#5C6477' }}>Gratis</span>
        ) : (
          <>
            <span style={{ fontSize: 14 }}>💎</span>
            <span style={{ fontFamily: '"Inter",system-ui', fontSize: mobile ? 16 : 18, fontWeight: 800, color: owned ? '#1F8B3A' : canAfford ? '#0F1A2E' : '#C24545', letterSpacing: -0.5 }}>
              {item.cost.toLocaleString('es-ES')}
            </span>
          </>
        )}
      </div>

      <button
        onClick={btnAction} disabled={btnDisabled}
        style={{
          width: '100%', padding: '9px 12px', borderRadius: 11, border: 'none',
          cursor: btnDisabled ? 'default' : 'pointer', background: btnBg, color: btnColor,
          fontFamily: '"Inter",system-ui', fontSize: 12.5, fontWeight: 700, transition: 'all 0.15s',
        }}
      >{btnLabel}</button>
    </div>
  );
}

Object.assign(window, { GemsStoreSection });
