
const { useState, useEffect } = React;

const T_MKT = {
  es: { title:'Tamaño de Mercado', cryptoTitle:'Mercado Cripto Global', stockTitle:'Principales Empresas por Cap. de Mercado', totalCap:'Cap. de Mercado Total', btcDom:'Dominancia BTC', ethDom:'Dominancia ETH', vol24:'Volumen 24h', coins:'Monedas Activas', change24:'Cambio 24h', loading:'Cargando...', error:'Error al cargar datos', source:'Fuente: CoinGecko', viewFull:'Ver en CompaniesMarketCap' },
  en: { title:'Market Size', cryptoTitle:'Global Crypto Market', stockTitle:'Top Companies by Market Cap', totalCap:'Total Market Cap', btcDom:'BTC Dominance', ethDom:'ETH Dominance', vol24:'24h Volume', coins:'Active Coins', change24:'24h Change', loading:'Loading...', error:'Error loading data', source:'Source: CoinGecko', viewFull:'View on CompaniesMarketCap' }
};

const TOP_COMPANIES = [
  { name:'Apple', ticker:'AAPL', cap:3.28, color:'#5ba3f5' },
  { name:'Microsoft', ticker:'MSFT', cap:3.09, color:'#00a4ef' },
  { name:'NVIDIA', ticker:'NVDA', cap:2.65, color:'#76b900' },
  { name:'Amazon', ticker:'AMZN', cap:2.18, color:'#ff9900' },
  { name:'Alphabet', ticker:'GOOGL', cap:2.05, color:'#4285f4' },
  { name:'Meta', ticker:'META', cap:1.38, color:'#0866ff' },
  { name:'Berkshire', ticker:'BRK.B', cap:1.08, color:'#c9a84c' },
  { name:'Tesla', ticker:'TSLA', cap:0.79, color:'#e82127' },
  { name:'Saudi Aramco', ticker:'2222.SR', cap:1.72, color:'#006c35' },
  { name:'TSMC', ticker:'TSM', cap:0.89, color:'#9b7fe8' },
];

function fmt(n) {
  if (n >= 1e12) return `$${(n/1e12).toFixed(2)}T`;
  if (n >= 1e9) return `$${(n/1e9).toFixed(1)}B`;
  if (n >= 1e6) return `$${(n/1e6).toFixed(1)}M`;
  return `$${n.toFixed(0)}`;
}

function MarketSize({ lang }) {
  const t = T_MKT[lang] || T_MKT.es;
  const [cg, setCg] = useState(null);
  const [cgLoading, setCgLoading] = useState(true);
  const [cgErr, setCgErr] = useState(false);

  useEffect(() => {
    setCgLoading(true);
    const apiKey = localStorage.getItem('iws_coingecko_key') || '';
    const url = apiKey
      ? `https://pro-api.coingecko.com/api/v3/global?x_cg_pro_api_key=${apiKey}`
      : 'https://api.coingecko.com/api/v3/global';
    fetch(url)
      .then(r => r.json())
      .then(j => { setCg(j.data); setCgLoading(false); })
      .catch(() => { setCgErr(true); setCgLoading(false); });
  }, []);

  const maxCap = Math.max(...TOP_COMPANIES.map(c => c.cap));

  return (
    <div>
      <div className="sec-label">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 010 20M12 2a15.3 15.3 0 000 20"/></svg>
        {t.title}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="two-col">

        {/* LEFT: Crypto Global */}
        <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 'var(--rl)', padding: 20 }}>
          <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 13, color: 'var(--text)', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ display: 'inline-flex', width: 8, height: 8, borderRadius: '50%', background: 'var(--gold)' }}></span>
            {t.cryptoTitle}
          </div>
          {cgLoading ? (
            <div style={{ color: 'var(--muted)', fontSize: 13, padding: '20px 0' }}>{t.loading}</div>
          ) : cgErr ? (
            <div style={{ color: 'var(--red)', fontSize: 13 }}>{t.error}</div>
          ) : cg && (
            <>
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 4 }}>{t.totalCap}</div>
                <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 28, color: 'var(--text)' }}>
                  {fmt(cg.total_market_cap?.usd || 0)}
                </div>
                <div style={{ fontSize: 12, marginTop: 2, color: (cg.market_cap_change_percentage_24h_usd||0) >= 0 ? 'var(--green)' : 'var(--red)' }}>
                  {(cg.market_cap_change_percentage_24h_usd||0) >= 0 ? '▲' : '▼'} {Math.abs(cg.market_cap_change_percentage_24h_usd||0).toFixed(2)}% {t.change24}
                </div>
              </div>

              {/* Stat grid */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
                {[
                  { l: t.vol24, v: fmt(cg.total_volume?.usd||0) },
                  { l: t.coins, v: (cg.active_cryptocurrencies||0).toLocaleString() },
                  { l: t.btcDom, v: `${(cg.market_cap_percentage?.btc||0).toFixed(1)}%` },
                  { l: t.ethDom, v: `${(cg.market_cap_percentage?.eth||0).toFixed(1)}%` },
                ].map(({ l, v }) => (
                  <div key={l} style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 8, padding: '10px 12px' }}>
                    <div style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{l}</div>
                    <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 16, color: 'var(--text)' }}>{v}</div>
                  </div>
                ))}
              </div>

              {/* Dominance bar */}
              <div>
                <div style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>Dominancia de Mercado</div>
                <div style={{ height: 8, borderRadius: 99, overflow: 'hidden', display: 'flex' }}>
                  {Object.entries(cg.market_cap_percentage||{}).slice(0,5).map(([coin, pct], i) => {
                    const COLORS = ['#f7931a','#627eea','#26a17b','#e84142','#9b7fe8'];
                    return <div key={coin} style={{ width: `${pct}%`, background: COLORS[i], transition: 'width 0.5s' }} title={`${coin.toUpperCase()}: ${pct.toFixed(1)}%`}></div>;
                  })}
                  <div style={{ flex: 1, background: 'var(--border)' }}></div>
                </div>
                <div style={{ display: 'flex', gap: 10, marginTop: 6, flexWrap: 'wrap' }}>
                  {Object.entries(cg.market_cap_percentage||{}).slice(0,5).map(([coin, pct], i) => {
                    const COLORS = ['#f7931a','#627eea','#26a17b','#e84142','#9b7fe8'];
                    return (
                      <div key={coin} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11 }}>
                        <span style={{ width: 8, height: 8, borderRadius: 2, background: COLORS[i], display: 'inline-block' }}></span>
                        <span style={{ color: 'var(--text2)', textTransform: 'uppercase' }}>{coin}</span>
                        <span style={{ color: 'var(--muted)' }}>{pct.toFixed(1)}%</span>
                      </div>
                    );
                  })}
                </div>
              </div>
              <div style={{ marginTop: 10, fontSize: 10, color: 'var(--muted)' }}>{t.source}</div>
            </>
          )}
        </div>

        {/* RIGHT: Top stocks by market cap */}
        <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 'var(--rl)', padding: 20 }}>
          <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 13, color: 'var(--text)', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ display: 'inline-flex', width: 8, height: 8, borderRadius: '50%', background: 'var(--blue)' }}></span>
              {t.stockTitle}
            </div>
            <a href="https://companiesmarketcap.com/" target="_blank" rel="noopener noreferrer"
              style={{ fontSize: 11, color: 'var(--blue)', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 4 }}>
              {t.viewFull}
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
            </a>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {TOP_COMPANIES.sort((a,b) => b.cap - a.cap).map((co, i) => (
              <div key={co.ticker} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 11, color: 'var(--muted)', width: 16, textAlign: 'right', flexShrink: 0 }}>{i+1}</span>
                <span style={{ fontSize: 12, fontWeight: 700, color: co.color, width: 56, fontFamily: 'Barlow, sans-serif', flexShrink: 0 }}>{co.ticker}</span>
                <div style={{ flex: 1, position: 'relative', height: 18 }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'var(--bg2)', borderRadius: 4 }}></div>
                  <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: `${(co.cap/maxCap)*100}%`, background: `${co.color}40`, borderRadius: 4, transition: 'width 0.5s' }}></div>
                  <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: `${(co.cap/maxCap)*100}%`, background: co.color, borderRadius: 4, transition: 'width 0.5s', maxWidth: '100%', opacity: 0.5 }}></div>
                  <span style={{ position: 'absolute', left: 8, top: 0, bottom: 0, display: 'flex', alignItems: 'center', fontSize: 10, color: 'var(--text)', fontWeight: 600 }}>{co.name}</span>
                </div>
                <span style={{ fontSize: 12, fontFamily: 'Barlow, sans-serif', fontWeight: 700, color: 'var(--text)', width: 52, textAlign: 'right', flexShrink: 0 }}>${co.cap}T</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 10, fontSize: 10, color: 'var(--muted)' }}>Datos aproximados. Fuente: companiesmarketcap.com</div>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { MarketSize });
