
const { useState, useEffect, useRef } = React;

const T_CRYPTO = {
  es: { title:'Criptomonedas', rank:'#', name:'Nombre', price:'Precio', change:'24h', cap:'Cap. Mercado', vol:'Volumen 24h', loading:'Cargando datos...', error:'Error al cargar. Intenta nuevamente.', retry:'Reintentar', source:'Fuente: CoinGecko', widget:'Gráfico en Vivo', selectCoin:'Selecciona una moneda para ver el gráfico' },
  en: { title:'Cryptocurrencies', rank:'#', name:'Name', price:'Price', change:'24h', cap:'Market Cap', vol:'Volume 24h', loading:'Loading data...', error:'Error loading. Please retry.', retry:'Retry', source:'Source: CoinGecko', widget:'Live Chart', selectCoin:'Select a coin to view the chart' }
};

function fmtPrice(n) {
  if (n >= 1000) return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
  if (n >= 1) return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 });
  if (n >= 0.01) return '$' + n.toFixed(4);
  return '$' + n.toFixed(6);
}
function fmtLarge(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(0)}M`;
  return `$${n.toFixed(0)}`;
}

const COIN_SYMBOLS = { bitcoin:'BTCUSDT', ethereum:'ETHUSDT', solana:'SOLUSDT', 'binancecoin':'BNBUSDT', 'ripple':'XRPUSDT', cardano:'ADAUSDT', avalanche:'AVAXUSDT', polkadot:'DOTUSDT', chainlink:'LINKUSDT', 'dogecoin':'DOGEUSDT' };

function CryptoSection({ lang, fullPage = false }) {
  const t = T_CRYPTO[lang] || T_CRYPTO.es;
  const [coins, setCoins] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [selectedCoin, setSelectedCoin] = useState(null);
  const [chartInterval, setChartInterval] = useState('D');
  const tvRef = useRef(null);

  const fetchCoins = () => {
    setLoading(true); setError(false);
    const apiKey = localStorage.getItem('iws_coingecko_key') || '';
    const base = apiKey
      ? `https://pro-api.coingecko.com/api/v3/coins/markets`
      : `https://api.coingecko.com/api/v3/coins/markets`;
    const url = `${base}?vs_currency=usd&order=market_cap_desc&per_page=${fullPage ? 50 : 20}&page=1&sparkline=false&price_change_percentage=24h${apiKey ? `&x_cg_pro_api_key=${apiKey}` : ''}`;
    fetch(url)
      .then(r => r.json())
      .then(data => { setCoins(data); setLoading(false); if (data[0] && !selectedCoin) setSelectedCoin(data[0]); })
      .catch(() => { setError(true); setLoading(false); });
  };

  useEffect(() => { fetchCoins(); }, []);

  const tvSymbol = selectedCoin ? (COIN_SYMBOLS[selectedCoin.id] || `${selectedCoin.symbol.toUpperCase()}USDT`) : 'BTCUSDT';
  const tvSrc = `https://s3.tradingview.com/widgetembed/?symbol=BINANCE:${tvSymbol}&interval=${chartInterval}&theme=dark&style=1&locale=${lang === 'es' ? 'es' : 'en'}&hide_top_toolbar=0&withdateranges=1&hide_side_toolbar=0&allow_symbol_change=0&save_image=false`;

  const intervals = [['1','1m'],['15','15m'],['60','1h'],['D','1D'],['W','1W']];

  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"/><path d="M9.5 9h3.5a2 2 0 010 4H9.5m0-4v4m0 0h3.5a2 2 0 010 4H9.5m0-4v4m0-8V7m0 10v2"/></svg>
        {t.title}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, minHeight: 480 }} className="two-col">

        {/* LEFT: Coins table */}
        <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 'var(--rl)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          {loading ? (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 13, flexDirection: 'column', gap: 10 }}>
              <div style={{ width: 24, height: 24, border: '2px solid var(--border)', borderTopColor: 'var(--gold)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }}></div>
              {t.loading}
              <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
            </div>
          ) : error ? (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 10 }}>
              <div style={{ color: 'var(--red)', fontSize: 13 }}>{t.error}</div>
              <button className="btn btn-outline btn-sm" onClick={fetchCoins}>{t.retry}</button>
            </div>
          ) : (
            <div style={{ overflowY: 'auto', flex: 1 }}>
              <table className="tbl" style={{ minWidth: 360 }}>
                <thead style={{ position: 'sticky', top: 0, background: 'var(--card2)', zIndex: 1 }}>
                  <tr>
                    <th style={{ width: 28 }}>{t.rank}</th>
                    <th>{t.name}</th>
                    <th style={{ textAlign: 'right' }}>{t.price}</th>
                    <th style={{ textAlign: 'right' }}>{t.change}</th>
                    <th style={{ textAlign: 'right' }} className="hide-mobile">{t.cap}</th>
                  </tr>
                </thead>
                <tbody>
                  {coins.map(c => {
                    const chg = c.price_change_percentage_24h || 0;
                    const isSelected = selectedCoin?.id === c.id;
                    return (
                      <tr key={c.id} onClick={() => setSelectedCoin(c)}
                        style={{ cursor: 'pointer', background: isSelected ? 'rgba(201,168,76,0.06)' : undefined }}>
                        <td style={{ color: 'var(--muted)', fontSize: 11 }}>{c.market_cap_rank}</td>
                        <td>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <img src={c.image} alt={c.name} style={{ width: 20, height: 20, borderRadius: '50%' }} onError={e => e.target.style.display='none'} />
                            <span style={{ fontWeight: 600, fontSize: 13, color: isSelected ? 'var(--gold)' : 'var(--text)' }}>{c.name}</span>
                            <span style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase' }}>{c.symbol}</span>
                          </div>
                        </td>
                        <td style={{ textAlign: 'right', fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 13, color: 'var(--text)' }}>
                          {fmtPrice(c.current_price)}
                        </td>
                        <td style={{ textAlign: 'right' }}>
                          <span style={{ fontSize: 12, fontWeight: 600, color: chg >= 0 ? 'var(--green)' : 'var(--red)', fontFamily: 'Barlow, sans-serif' }}>
                            {chg >= 0 ? '+' : ''}{chg.toFixed(2)}%
                          </span>
                        </td>
                        <td style={{ textAlign: 'right', fontSize: 12, color: 'var(--text2)' }} className="hide-mobile">
                          {fmtLarge(c.market_cap)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              <div style={{ padding: '6px 12px', fontSize: 10, color: 'var(--muted)', borderTop: '1px solid var(--border)' }}>{t.source}</div>
            </div>
          )}
        </div>

        {/* RIGHT: TradingView chart */}
        <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 'var(--rl)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          {selectedCoin ? (
            <>
              <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg2)', flexWrap: 'wrap' }}>
                <img src={selectedCoin.image} alt={selectedCoin.name} style={{ width: 22, height: 22, borderRadius: '50%' }} onError={e => e.target.style.display='none'} />
                <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 15, color: 'var(--text)' }}>{selectedCoin.name}</span>
                <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 14, color: 'var(--gold)' }}>{fmtPrice(selectedCoin.current_price)}</span>
                <span style={{ fontSize: 12, color: (selectedCoin.price_change_percentage_24h||0) >= 0 ? 'var(--green)' : 'var(--red)', fontWeight: 600 }}>
                  {(selectedCoin.price_change_percentage_24h||0) >= 0 ? '+' : ''}{(selectedCoin.price_change_percentage_24h||0).toFixed(2)}%
                </span>
                <div style={{ marginLeft: 'auto', display: 'flex', gap: 3 }}>
                  {intervals.map(([k,l]) => (
                    <button key={k} onClick={() => setChartInterval(k)}
                      className={`btn btn-sm ${chartInterval === k ? 'btn-active' : 'btn-ghost'}`}
                      style={{ padding: '3px 7px', fontSize: 11, fontFamily: 'Barlow, sans-serif' }}>
                      {l}
                    </button>
                  ))}
                </div>
              </div>
              <iframe key={`${tvSymbol}-${chartInterval}`} src={tvSrc}
                style={{ flex: 1, border: 'none', width: '100%', minHeight: 380 }}
                title={`Chart ${selectedCoin.name}`}
                allow="fullscreen" />
            </>
          ) : (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 10, color: 'var(--muted)', padding: 24 }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2"><circle cx="12" cy="12" r="10"/><path d="M9.5 9h3.5a2 2 0 010 4H9.5m0-4v4m0 0h3.5a2 2 0 010 4H9.5m0-4v4m0-8V7m0 10v2"/></svg>
              <span style={{ fontSize: 13 }}>{t.selectCoin}</span>
            </div>
          )}
        </div>

      </div>
    </div>
  );
}

function CryptoPage({ lang }) {
  return (
    <div style={{ padding: 24, maxWidth: 1600, margin: '0 auto' }}>
      <CryptoSection lang={lang} fullPage={true} />
    </div>
  );
}

Object.assign(window, { CryptoSection, CryptoPage });
