
const { useState, useEffect } = React;

/* ── Shared section wrapper ── */
function SectionCard({ children, id }) {
  return (
    <section id={id} style={{ marginBottom: 24 }}>
      <div className="card" style={{ padding: 24 }}>
        {children}
      </div>
    </section>
  );
}

/* ── Portafolios page ── */
const GURUS = [
  { name:'Warren Buffett', firm:'Berkshire Hathaway', aum:'$371B', updated:'Q4 2025', holdings:[{t:'AAPL',pct:44.1,chg:0},{t:'BAC',pct:11.2,chg:-0.3},{t:'AXP',pct:8.4,chg:0},{t:'KO',pct:6.8,chg:0},{t:'CVX',pct:5.9,chg:-1.1}] },
  { name:'Bill Ackman', firm:'Pershing Square', aum:'$10.5B', updated:'Q4 2025', holdings:[{t:'HLT',pct:18.2,chg:2.1},{t:'BN',pct:16.4,chg:0},{t:'CMG',pct:15.8,chg:0},{t:'QSR',pct:14.6,chg:0},{t:'GOOGL',pct:12.3,chg:5.2}] },
  { name:'Michael Burry', firm:'Scion Asset Mgmt', aum:'$361M', updated:'Q4 2025', holdings:[{t:'BABA',pct:22.8,chg:8.4},{t:'JD',pct:19.6,chg:3.2},{t:'HII',pct:12.1,chg:-5.8},{t:'BKNG',pct:11.4,chg:0},{t:'REAL',pct:9.7,chg:-2.1}] },
  { name:'David Tepper', firm:'Appaloosa Mgmt', aum:'$6.2B', updated:'Q4 2025', holdings:[{t:'META',pct:25.4,chg:4.1},{t:'AMZN',pct:18.6,chg:2.8},{t:'GOOGL',pct:14.2,chg:1.5},{t:'MSFT',pct:11.8,chg:0},{t:'NVDA',pct:9.3,chg:6.7}] },
];

function PortfoliosPage({ lang }) {
  const [activeGuru, setActiveGuru] = useState(0);
  const g = GURUS[activeGuru];
  const t = {
    es: { title:'Portafolios de Grandes Inversores', source:'Fuente: Dataroma / 13F filings', holdings:'Principales Posiciones', aum:'AUM', updated:'Actualizado', change:'Cambio trim.', viewDataroma:'Ver en Dataroma' },
    en: { title:'Top Investor Portfolios', source:'Source: Dataroma / 13F filings', holdings:'Top Holdings', aum:'AUM', updated:'Updated', change:'Qtr Change', viewDataroma:'View on Dataroma' }
  }[lang] || {};

  return (
    <div style={{ padding: 24, maxWidth: 1400, margin: '0 auto' }}>
      <div className="card">
        <div className="sec-label">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/></svg>
          {t.title}
          <a href="https://www.dataroma.com/m/home.php" target="_blank" rel="noopener noreferrer"
            style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--blue)', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 4, fontWeight: 400, letterSpacing: 0, textTransform: 'none' }}>
            {t.viewDataroma}
            <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>

        {/* Guru selector */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap' }}>
          {GURUS.map((g, i) => (
            <button key={i} onClick={() => setActiveGuru(i)}
              className={`btn ${activeGuru === i ? 'btn-gold' : 'btn-outline'}`}
              style={{ flexDirection: 'column', alignItems: 'flex-start', padding: '10px 16px', gap: 2, minWidth: 160 }}>
              <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 13 }}>{g.name}</span>
              <span style={{ fontSize: 11, fontWeight: 400, opacity: 0.75 }}>{g.firm}</span>
            </button>
          ))}
        </div>

        {/* Holdings */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="two-col">
          <div>
            <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
              {[[t.aum, g.aum],[t.updated, g.updated]].map(([l,v]) => (
                <div key={l}>
                  <div style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 2 }}>{l}</div>
                  <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 16, color: 'var(--text)' }}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 12, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>{t.holdings}</div>
            {g.holdings.map(h => (
              <div key={h.t} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 14, color: 'var(--gold)', width: 52, flexShrink: 0 }}>{h.t}</span>
                <div style={{ flex: 1, height: 8, background: 'var(--bg2)', borderRadius: 99, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${h.pct}%`, background: 'var(--gold)', borderRadius: 99, opacity: 0.7 }}></div>
                </div>
                <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 13, color: 'var(--text)', width: 40, textAlign: 'right' }}>{h.pct}%</span>
                <span style={{ fontSize: 11, width: 48, textAlign: 'right', color: h.chg > 0 ? 'var(--green)' : h.chg < 0 ? 'var(--red)' : 'var(--muted)', fontWeight: 600 }}>
                  {h.chg > 0 ? '+' : ''}{h.chg !== 0 ? h.chg + '%' : '—'}
                </span>
              </div>
            ))}
          </div>
          <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 10, padding: 20, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 8, minHeight: 220 }}>
            <div style={{ width: 120, height: 120, position: 'relative' }}>
              <svg viewBox="0 0 36 36" style={{ width: '100%', height: '100%', transform: 'rotate(-90deg)' }}>
                {g.holdings.reduce((acc, h, i) => {
                  const colors = ['#c9a84c','#5ba3f5','#3dd68c','#f06b6b','#9b7fe8'];
                  const prev = acc.offset;
                  const circ = 2 * Math.PI * 15.9155;
                  acc.els.push(
                    <circle key={h.t} cx="18" cy="18" r="15.9155" fill="none"
                      stroke={colors[i]} strokeWidth="3.5"
                      strokeDasharray={`${(h.pct/100)*circ} ${circ}`}
                      strokeDashoffset={-prev * circ / 100} />
                  );
                  acc.offset += h.pct;
                  return acc;
                }, { els: [], offset: 0 }).els}
              </svg>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center' }}>
              {g.holdings.map((h, i) => {
                const colors = ['#c9a84c','#5ba3f5','#3dd68c','#f06b6b','#9b7fe8'];
                return (
                  <div key={h.t} 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)' }}>{h.t}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        <div style={{ marginTop: 12, fontSize: 10, color: 'var(--muted)' }}>{t.source}</div>
      </div>
    </div>
  );
}

/* ── Brokers page ── */
const BROKERS = [
  { name:'Interactive Brokers', logo:'IBKR', commission:'$0–$0.005/acción', min:'$0', platforms:'IBKR, TWS, Mobile', assets:'Acciones, ETFs, Opciones, Futuros, Forex, Cripto, Bonos', reg:'SEC, FINRA, FCA', margin:'Desde 5.83%', rating:4.8, pros:['Mejor para traders activos','Acceso global a 150 mercados','Bajas comisiones en opciones'], note:'Mejor plataforma profesional' },
  { name:'Charles Schwab', logo:'SCHW', commission:'$0', min:'$0', platforms:'Schwab, thinkorswim, Mobile', assets:'Acciones, ETFs, Opciones, Futuros, Bonos', reg:'SEC, FINRA', margin:'Desde 11.075%', rating:4.7, pros:['Sin comisiones en acciones/ETFs','Excelente investigación y educación','thinkorswim para opciones'], note:'Mejor relación calidad/precio' },
  { name:'TD Ameritrade', logo:'TDA', commission:'$0', min:'$0', platforms:'thinkorswim, Mobile', assets:'Acciones, ETFs, Opciones, Futuros, Forex', reg:'SEC, FINRA', margin:'Desde 12.5%', rating:4.6, pros:['thinkorswim es líder en opciones','Educación de alta calidad','Ahora integrado con Schwab'], note:'Fusionado con Schwab' },
  { name:'Robinhood', logo:'HOOD', commission:'$0', min:'$0', platforms:'Mobile, Web', assets:'Acciones, ETFs, Opciones, Cripto', reg:'SEC, FINRA', margin:'Desde 5.75%', rating:3.9, pros:['Interfaz muy simple','Sin mínimo de cuenta','Cripto integrado'], note:'Ideal para principiantes' },
  { name:'eToro', logo:'eToro', commission:'0%', min:'$50', platforms:'Web, Mobile', assets:'Acciones, ETFs, Cripto, CFDs, Forex', reg:'FCA, CySEC, ASIC', margin:'Varía', rating:4.1, pros:['Copy trading único','Social investing','Acceso global'], note:'CopyTrading líder' },
];

function BrokersPage({ lang }) {
  const labels = lang === 'es'
    ? { title:'Comparativa de Brokers', comm:'Comisión', min:'Mínimo', platforms:'Plataformas', assets:'Activos', reg:'Regulación', margin:'Margen', rating:'Rating', pros:'Ventajas', note:'Nota', disclaimer:'Información de referencia. Verifica condiciones actuales antes de abrir cuenta.' }
    : { title:'Broker Comparison', comm:'Commission', min:'Minimum', platforms:'Platforms', assets:'Assets', reg:'Regulation', margin:'Margin', rating:'Rating', pros:'Advantages', note:'Note', disclaimer:'Reference info. Verify current conditions before opening an account.' };

  return (
    <div style={{ padding: 24, maxWidth: 1400, margin: '0 auto' }}>
      <div className="card">
        <div className="sec-label">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg>
          {labels.title}
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl" style={{ minWidth: 900 }}>
            <thead>
              <tr>
                <th>Broker</th>
                <th>{labels.comm}</th>
                <th>{labels.min}</th>
                <th>{labels.platforms}</th>
                <th>{labels.assets}</th>
                <th>{labels.reg}</th>
                <th>{labels.margin}</th>
                <th>{labels.rating}</th>
                <th>{labels.note}</th>
              </tr>
            </thead>
            <tbody>
              {BROKERS.map(b => (
                <tr key={b.logo}>
                  <td>
                    <div>
                      <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 13, color: 'var(--gold)' }}>{b.logo}</div>
                      <div style={{ fontSize: 11, color: 'var(--text2)' }}>{b.name}</div>
                    </div>
                  </td>
                  <td style={{ color: 'var(--green)', fontWeight: 600 }}>{b.commission}</td>
                  <td>{b.min}</td>
                  <td style={{ fontSize: 12 }}>{b.platforms}</td>
                  <td style={{ fontSize: 11, color: 'var(--text2)', maxWidth: 180 }}>{b.assets}</td>
                  <td style={{ fontSize: 11 }}>{b.reg}</td>
                  <td style={{ fontSize: 12 }}>{b.margin}</td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                      <span style={{ color: 'var(--gold)', fontSize: 13 }}>★</span>
                      <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700 }}>{b.rating}</span>
                    </div>
                  </td>
                  <td><span className="badge badge-gold" style={{ fontSize: 10, whiteSpace: 'nowrap' }}>{b.note}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 12, fontSize: 10, color: 'var(--muted)' }}>{labels.disclaimer}</div>
      </div>
    </div>
  );
}

/* ── Videos page ── */
function VideosPage({ lang }) {
  const t = lang === 'es'
    ? { title:'Videos & Lives', live:'EN VIVO', latest:'Último Video', tiktok:'TikTok', youtube:'YouTube', subscribe:'Suscribirse', follow:'Seguir', subs:'Suscriptores', followers:'Seguidores', viewChannel:'Ver canal completo', latestLive:'Último Live', watchOn:'Ver en' }
    : { title:'Videos & Lives', live:'LIVE', latest:'Latest Video', tiktok:'TikTok', youtube:'YouTube', subscribe:'Subscribe', follow:'Follow', subs:'Subscribers', followers:'Followers', viewChannel:'View full channel', latestLive:'Latest Live', watchOn:'Watch on' };

  return (
    <div style={{ padding: 24, maxWidth: 1400, margin: '0 auto' }}>
      <div className="card" style={{ marginBottom: 16 }}>
        <div className="sec-label">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>
          {t.title}
        </div>

        {/* Hero: Latest Live */}
        <div style={{ position: 'relative', borderRadius: 12, overflow: 'hidden', marginBottom: 24, background: '#000', border: '1px solid var(--border)' }}>
          <div style={{ position: 'absolute', top: 14, left: 14, zIndex: 2, display: 'flex', alignItems: 'center', gap: 6, background: 'rgba(255,0,0,0.95)', padding: '4px 10px', borderRadius: 4, fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 11, letterSpacing: '0.1em', color: 'white' }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'white', animation: 'livepulse 1.5s ease-in-out infinite' }}></span>
            {t.live}
          </div>
          <div style={{ position: 'relative', paddingBottom: '40%', height: 0 }}>
            <iframe
              src="https://www.youtube.com/embed/live_stream?channel=UCWNw3SAjOzVl-DTeQpYANRA&autoplay=0"
              style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 'none' }}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              title="Inside Wall Street Live"
            />
          </div>
        </div>

        {/* Two-column: TikTok latest + YouTube latest */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="two-col">

          {/* TikTok column */}
          <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 38, height: 38, borderRadius: 8, background: '#000', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="white"><path d="M19.59 6.69a4.83 4.83 0 01-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 01-2.88 2.5 2.89 2.89 0 01-2.89-2.89 2.89 2.89 0 012.89-2.89c.28 0 .54.04.79.1V9.01a6.33 6.33 0 00-.79-.05 6.34 6.34 0 00-6.34 6.34 6.34 6.34 0 006.34 6.34 6.34 6.34 0 006.33-6.34V8.69a8.18 8.18 0 004.79 1.53V6.77a4.85 4.85 0 01-1.02-.08z"/></svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 14, color: 'var(--text)' }}>@insidewallstreet</div>
                <div style={{ fontSize: 11, color: 'var(--muted)' }}>89K {t.followers}</div>
              </div>
              <a href="https://www.tiktok.com/@insidewallstreet" target="_blank" rel="noopener noreferrer"
                className="btn" style={{ background: '#fe2c55', color: 'white', textDecoration: 'none', fontWeight: 700, fontSize: 12 }}>
                {t.follow}
              </a>
            </div>

            {/* Latest TikTok preview - vertical 9:16 */}
            <div style={{ padding: 16 }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10 }}>{t.latest}</div>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <a href="https://www.tiktok.com/@insidewallstreet" target="_blank" rel="noopener noreferrer"
                  style={{ display: 'block', position: 'relative', width: 260, aspectRatio: '9/16', borderRadius: 10, overflow: 'hidden', background: 'linear-gradient(135deg, #fe2c55 0%, #25f4ee 100%)', cursor: 'pointer', textDecoration: 'none' }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)' }}></div>
                  <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 64, height: 64, borderRadius: '50%', background: 'rgba(255,255,255,0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="#fe2c55"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                  </div>
                  <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 14, background: 'linear-gradient(to top, rgba(0,0,0,0.85) 0%, transparent 100%)', color: 'white' }}>
                    <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 14, marginBottom: 4 }}>Análisis NVDA: ¿comprar ahora?</div>
                    <div style={{ fontSize: 11, opacity: 0.85 }}>2.4K likes • Hace 2 días</div>
                  </div>
                </a>
              </div>
              <div style={{ marginTop: 14, textAlign: 'center', fontSize: 11 }}>
                <a href="https://www.tiktok.com/@insidewallstreet" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--blue)', textDecoration: 'none' }}>
                  {t.viewChannel} →
                </a>
              </div>
            </div>
          </div>

          {/* YouTube column */}
          <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 38, height: 38, borderRadius: 8, background: '#ff0000', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="white"><path d="M22.54 6.42a2.78 2.78 0 00-1.95-1.96C18.88 4 12 4 12 4s-6.88 0-8.59.46A2.78 2.78 0 001.46 6.42 29 29 0 001 12a29 29 0 00.46 5.58A2.78 2.78 0 003.41 19.6C5.12 20 12 20 12 20s6.88 0 8.59-.4a2.78 2.78 0 001.95-1.97A29 29 0 0023 12a29 29 0 00-.46-5.58z"/><polygon points="9.75 15.02 15.5 12 9.75 8.98 9.75 15.02" fill="#ff0000"/></svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 14, color: 'var(--text)' }}>@InsideWallStreet</div>
                <div style={{ fontSize: 11, color: 'var(--muted)' }}>42K {t.subs}</div>
              </div>
              <a href="https://www.youtube.com/@InsideWallStreet?sub_confirmation=1" target="_blank" rel="noopener noreferrer"
                className="btn" style={{ background: '#ff0000', color: 'white', textDecoration: 'none', fontWeight: 700, fontSize: 12 }}>
                {t.subscribe}
              </a>
            </div>

            {/* Latest YouTube video */}
            <div style={{ padding: 16 }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10 }}>{t.latest}</div>
              <div style={{ borderRadius: 10, overflow: 'hidden', position: 'relative', paddingBottom: '56.25%', height: 0, background: '#000' }}>
                <iframe
                  src="https://www.youtube.com/embed?listType=user_uploads&list=InsideWallStreet&autoplay=0"
                  style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 'none' }}
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowFullScreen
                  title="Inside Wall Street Latest"
                />
              </div>
              <div style={{ marginTop: 14, textAlign: 'center', fontSize: 11 }}>
                <a href="https://www.youtube.com/@InsideWallStreet" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--blue)', textDecoration: 'none' }}>
                  {t.viewChannel} →
                </a>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}

/* ── HomePage ── */
function HomePage({ lang }) {
  const pageTitles = { es: ['Perfil de Inversión','Síguenos','Opciones','Tamaño de Mercado','Compradores','Criptomonedas'], en: ['Investment Profile','Follow Us','Options','Market Size','Insiders','Crypto'] };
  const [pt] = useState(pageTitles);

  return (
    <div style={{ padding: '20px 24px', maxWidth: 1600, margin: '0 auto' }}>
      <SectionCard id="perfil">
        <InvestorProfile lang={lang} />
      </SectionCard>
      <SectionCard id="redes">
        <SocialSection lang={lang} />
      </SectionCard>
      <SectionCard id="opciones">
        <OptionsAnalyzer lang={lang} />
      </SectionCard>
      <SectionCard id="mercado">
        <MarketSize lang={lang} />
      </SectionCard>
      <SectionCard id="compradores">
        <InsiderTrading lang={lang} />
      </SectionCard>
      <SectionCard id="cripto">
        <CryptoSection lang={lang} />
      </SectionCard>
    </div>
  );
}

/* ── Root App ── */
const PAGE_TITLES = {
  inicio:        { es:'Inicio', en:'Home' },
  criptomonedas: { es:'Criptomonedas', en:'Cryptocurrencies' },
  portafolios:   { es:'Portafolios', en:'Portfolios' },
  brokers:       { es:'Brokers', en:'Brokers' },
  videos:        { es:'Videos', en:'Videos' },
  compradores:   { es:'Compradores', en:'Insiders' },
};

function App() {
  const [page, setPage] = useState('inicio');
  const [collapsed, setCollapsed] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [lang, setLang] = useState('es');
  const [authOpen, setAuthOpen] = useState(false);
  const mainRef = React.useRef(null);

  const handleNav = (id) => {
    setPage(id);
    if (mainRef.current) mainRef.current.scrollTop = 0;
    if (window.innerWidth < 768) setSidebarOpen(false);
  };

  const pageTitle = (PAGE_TITLES[page] || PAGE_TITLES.inicio)[lang];

  return (
    <div style={{ display: 'flex', height: '100vh', overflow: 'hidden', background: 'var(--bg)' }}>
      <div className={`sidebar-overlay ${sidebarOpen && window.innerWidth < 768 ? 'active' : ''}`}
        onClick={() => setSidebarOpen(false)} />

      {sidebarOpen && (
        <Sidebar
          collapsed={collapsed}
          onCollapse={() => setCollapsed(c => !c)}
          activePage={page}
          onNav={handleNav}
          lang={lang}
        />
      )}

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
        <TopBar
          onMenuClick={() => setSidebarOpen(o => !o)}
          lang={lang}
          onLangToggle={() => setLang(l => l === 'es' ? 'en' : 'es')}
          pageTitle={pageTitle}
          onOpenAuth={() => setAuthOpen(true)}
        />
        <LiveTickerBar lang={lang} />
        <main ref={mainRef} style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
          {page === 'inicio'        && <HomePage lang={lang} />}
          {page === 'criptomonedas' && <CryptoPage lang={lang} />}
          {page === 'portafolios'   && <PortfoliosPage lang={lang} />}
          {page === 'brokers'       && <BrokersPage lang={lang} />}
          {page === 'videos'        && <VideosPage lang={lang} />}
          {page === 'compradores'   && <InsidersPage lang={lang} />}
        </main>
      </div>

      <AuthModal open={authOpen} onClose={() => setAuthOpen(false)} lang={lang} />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ThemeProvider><AuthProvider><App /></AuthProvider></ThemeProvider>);
