
const { useState, useRef, useEffect } = React;

const QZ = {
  es: {
    questions: [
      { q: '¿Cuánto tiempo planeas mantener tus inversiones?',
        opts: [{ l:'Menos de 1 año', s:1 },{ l:'1 a 3 años', s:2 },{ l:'3 a 7 años', s:3 },{ l:'7 a 15 años', s:4 },{ l:'Más de 15 años', s:5 }] },
      { q: 'Si tu portafolio cae 20% en un mes, ¿qué harías?',
        opts: [{ l:'Vendería todo de inmediato', s:1 },{ l:'Vendería una parte', s:2 },{ l:'No haría nada', s:3 },{ l:'Compraría un poco más', s:4 },{ l:'Invertiría mucho más', s:5 }] },
      { q: '¿Cuál es tu objetivo principal de inversión?',
        opts: [{ l:'Preservar mi capital', s:1 },{ l:'Generar ingresos estables', s:2 },{ l:'Crecimiento moderado', s:3 },{ l:'Crecimiento acelerado', s:4 },{ l:'Máximo retorno posible', s:5 }] },
      { q: '¿Qué porcentaje de tus ahorros dedicarías a invertir?',
        opts: [{ l:'Menos del 10%', s:1 },{ l:'10% a 25%', s:2 },{ l:'25% a 50%', s:3 },{ l:'50% a 75%', s:4 },{ l:'Más del 75%', s:5 }] },
      { q: '¿Tienes experiencia previa invirtiendo en bolsa?',
        opts: [{ l:'Ninguna experiencia', s:1 },{ l:'Menos de 1 año', s:2 },{ l:'1 a 3 años', s:3 },{ l:'3 a 10 años', s:4 },{ l:'Más de 10 años', s:5 }] },
      { q: '¿Qué tipo de activos te interesan más?',
        opts: [{ l:'Solo bonos y depósitos', s:1 },{ l:'Bonos + algunas acciones', s:2 },{ l:'Mezcla equilibrada', s:3 },{ l:'Mayormente acciones y ETFs', s:4 },{ l:'Acciones + cripto + opciones', s:5 }] },
      { q: '¿Necesitas acceso rápido al dinero invertido en los próximos 2 años?',
        opts: [{ l:'Sí, muy probable', s:1 },{ l:'Posiblemente', s:2 },{ l:'No estoy seguro', s:3 },{ l:'Probablemente no', s:4 },{ l:'No, definitivamente no', s:5 }] },
      { q: '¿Con qué frecuencia revisarías tu portafolio?',
        opts: [{ l:'Varias veces al día', s:2 },{ l:'Una vez por semana', s:3 },{ l:'Una vez al mes', s:4 },{ l:'Cada trimestre', s:4 },{ l:'Una vez al año', s:5 }] },
      { q: '¿Cómo describes tu tolerancia a la volatilidad del mercado?',
        opts: [{ l:'Muy baja — el riesgo me estresa', s:1 },{ l:'Baja — prefiero estabilidad', s:2 },{ l:'Media — tolero altibajos moderados', s:3 },{ l:'Alta — acepto caídas por mejores retornos', s:4 },{ l:'Muy alta — busco activos volátiles', s:5 }] },
    ],
    profiles: [
      { id:'conservador', name:'Conservador', range:[9,20], color:'#5ba3f5',
        desc:'Priorizas la seguridad sobre el rendimiento. Buscas estabilidad y protección del capital.',
        tickers:[{s:'BND',n:'Vanguard Total Bond',t:'ETF'},{s:'AGG',n:'iShares US Aggregate Bond',t:'ETF'},{s:'SHY',n:'iShares 1-3Y Treasury',t:'ETF'},{s:'TIP',n:'iShares TIPS Bond',t:'ETF'},{s:'GLD',n:'SPDR Gold Shares',t:'ETF'},{s:'TLT',n:'iShares 20+ Year Treasury',t:'ETF'},{s:'VTIP',n:'Vanguard Short-Term TIPS',t:'ETF'},{s:'BIL',n:'SPDR 1-3 Month T-Bill',t:'ETF'},{s:'JNJ',n:'Johnson & Johnson',t:'Acción'},{s:'PG',n:'Procter & Gamble',t:'Acción'},{s:'KO',n:'Coca-Cola',t:'Acción'}] },
      { id:'mod-conservador', name:'Moderado-Conservador', range:[21,28], color:'#9b7fe8',
        desc:'Buscas estabilidad con algo de crecimiento. Mezcla de renta fija y acciones de dividendos.',
        tickers:[{s:'VCIT',n:'Vanguard Interm Corp Bond',t:'ETF'},{s:'VIG',n:'Vanguard Dividend Appreciation',t:'ETF'},{s:'SDY',n:'SPDR S&P Dividend ETF',t:'ETF'},{s:'GLD',n:'SPDR Gold Shares',t:'ETF'},{s:'SCHD',n:'Schwab US Dividend Equity',t:'ETF'},{s:'JEPI',n:'JPMorgan Equity Premium',t:'ETF'},{s:'DGRO',n:'iShares Core Dividend Growth',t:'ETF'},{s:'BRK.B',n:'Berkshire Hathaway',t:'Acción'},{s:'JPM',n:'JPMorgan Chase',t:'Acción'},{s:'PEP',n:'PepsiCo',t:'Acción'},{s:'V',n:'Visa Inc',t:'Acción'},{s:'MA',n:'Mastercard',t:'Acción'}] },
      { id:'moderado', name:'Moderado', range:[29,36], color:'#c9a84c',
        desc:'Equilibrio entre crecimiento y estabilidad. El portafolio clásico de largo plazo.',
        tickers:[{s:'VOO',n:'Vanguard S&P 500',t:'ETF'},{s:'VTI',n:'Vanguard Total Stock Market',t:'ETF'},{s:'QQQ',n:'Invesco QQQ (Nasdaq-100)',t:'ETF'},{s:'SCHD',n:'Schwab US Dividend Equity',t:'ETF'},{s:'VYM',n:'Vanguard High Dividend Yield',t:'ETF'},{s:'SPY',n:'SPDR S&P 500 ETF',t:'ETF'},{s:'VXUS',n:'Vanguard Total Intl Stock',t:'ETF'},{s:'IWM',n:'iShares Russell 2000',t:'ETF'},{s:'AAPL',n:'Apple Inc',t:'Acción'},{s:'MSFT',n:'Microsoft',t:'Acción'},{s:'GOOGL',n:'Alphabet',t:'Acción'},{s:'AMZN',n:'Amazon',t:'Acción'},{s:'COST',n:'Costco',t:'Acción'},{s:'UNH',n:'UnitedHealth',t:'Acción'}] },
      { id:'crecimiento', name:'Crecimiento', range:[37,41], color:'#3dd68c',
        desc:'Orientado al crecimiento a largo plazo. Alta exposición a tecnología y sectores de futuro.',
        tickers:[{s:'VGT',n:'Vanguard IT ETF',t:'ETF'},{s:'XLK',n:'Technology Select Sector',t:'ETF'},{s:'SMH',n:'VanEck Semiconductor',t:'ETF'},{s:'SOXX',n:'iShares Semiconductor',t:'ETF'},{s:'QQQM',n:'Invesco Nasdaq-100',t:'ETF'},{s:'IBIT',n:'iShares Bitcoin Trust',t:'ETF'},{s:'NVDA',n:'NVIDIA Corp',t:'Acción'},{s:'TSLA',n:'Tesla',t:'Acción'},{s:'META',n:'Meta Platforms',t:'Acción'},{s:'AVGO',n:'Broadcom',t:'Acción'},{s:'AMD',n:'AMD',t:'Acción'},{s:'CRM',n:'Salesforce',t:'Acción'},{s:'NFLX',n:'Netflix',t:'Acción'},{s:'PLTR',n:'Palantir',t:'Acción'}] },
      { id:'agresivo', name:'Agresivo', range:[42,45], color:'#f06b6b',
        desc:'Máximo crecimiento con alta tolerancia al riesgo. Activos volátiles de alto potencial.',
        tickers:[{s:'TQQQ',n:'ProShares UltraPro QQQ 3x',t:'ETF'},{s:'SOXL',n:'Direxion Semis 3x Bull',t:'ETF'},{s:'ARKK',n:'ARK Innovation ETF',t:'ETF'},{s:'TSLL',n:'Direxion TSLA 2x Bull',t:'ETF'},{s:'NVDL',n:'GraniteShares NVDA 2x',t:'ETF'},{s:'MSTR',n:'MicroStrategy',t:'Acción'},{s:'COIN',n:'Coinbase',t:'Acción'},{s:'HOOD',n:'Robinhood',t:'Acción'},{s:'SOFI',n:'SoFi Technologies',t:'Acción'},{s:'BTC-USD',n:'Bitcoin',t:'Cripto'},{s:'ETH-USD',n:'Ethereum',t:'Cripto'},{s:'SOL-USD',n:'Solana',t:'Cripto'},{s:'GME',n:'GameStop',t:'Acción'},{s:'RIVN',n:'Rivian',t:'Acción'}] },
    ],
    ui: { title:'Descubre tu Perfil de Inversión', sub:'9 preguntas para conocer tu estrategia ideal', next:'Siguiente', prev:'Anterior', finish:'Ver mi Perfil', restart:'Reiniciar', q:'Pregunta', of:'de', yourProfile:'Tu Perfil', recommended:'Activos Recomendados', clickTicker:'Clic en un ticker para ver su gráfico', selectAnswer:'Selecciona una opción para continuar' },
    chartTypes: { 1:'Velas', 2:'Línea', 3:'Área', 0:'Barras' },
  },
  en: {
    questions: [
      { q: 'How long do you plan to hold your investments?',
        opts: [{ l:'Less than 1 year', s:1 },{ l:'1 to 3 years', s:2 },{ l:'3 to 7 years', s:3 },{ l:'7 to 15 years', s:4 },{ l:'More than 15 years', s:5 }] },
      { q: 'If your portfolio drops 20% in a month, what would you do?',
        opts: [{ l:'Sell everything immediately', s:1 },{ l:'Sell a portion', s:2 },{ l:'Do nothing', s:3 },{ l:'Buy a little more', s:4 },{ l:'Invest significantly more', s:5 }] },
      { q: 'What is your primary investment goal?',
        opts: [{ l:'Preserve my capital', s:1 },{ l:'Generate stable income', s:2 },{ l:'Moderate growth', s:3 },{ l:'Accelerated growth', s:4 },{ l:'Maximum possible return', s:5 }] },
      { q: 'What percentage of your savings would you invest?',
        opts: [{ l:'Less than 10%', s:1 },{ l:'10% to 25%', s:2 },{ l:'25% to 50%', s:3 },{ l:'50% to 75%', s:4 },{ l:'More than 75%', s:5 }] },
      { q: 'Do you have prior experience investing in the stock market?',
        opts: [{ l:'No experience at all', s:1 },{ l:'Less than 1 year', s:2 },{ l:'1 to 3 years', s:3 },{ l:'3 to 10 years', s:4 },{ l:'More than 10 years', s:5 }] },
      { q: 'What type of assets interest you most?',
        opts: [{ l:'Bonds and deposits only', s:1 },{ l:'Bonds + some stocks', s:2 },{ l:'Balanced mix', s:3 },{ l:'Mostly stocks and ETFs', s:4 },{ l:'Stocks + crypto + options', s:5 }] },
      { q: 'Will you need quick access to invested funds in the next 2 years?',
        opts: [{ l:'Yes, very likely', s:1 },{ l:'Possibly', s:2 },{ l:'Not sure', s:3 },{ l:'Probably not', s:4 },{ l:'No, definitely not', s:5 }] },
      { q: 'How often would you review your portfolio?',
        opts: [{ l:'Multiple times a day', s:2 },{ l:'Once a week', s:3 },{ l:'Once a month', s:4 },{ l:'Every quarter', s:4 },{ l:'Once a year', s:5 }] },
      { q: 'How would you describe your market volatility tolerance?',
        opts: [{ l:'Very low — risk stresses me', s:1 },{ l:'Low — I prefer stability', s:2 },{ l:'Medium — I accept moderate swings', s:3 },{ l:'High — I accept drops for better returns', s:4 },{ l:'Very high — I seek volatile assets', s:5 }] },
    ],
    profiles: [
      { id:'conservative', name:'Conservative', range:[9,20], color:'#5ba3f5', desc:'You prioritize safety over returns. Stable assets and capital protection.', tickers:[{s:'BND',n:'Vanguard Total Bond',t:'ETF'},{s:'AGG',n:'iShares US Aggregate Bond',t:'ETF'},{s:'SHY',n:'iShares 1-3Y Treasury',t:'ETF'},{s:'TIP',n:'iShares TIPS Bond',t:'ETF'},{s:'GLD',n:'SPDR Gold',t:'ETF'},{s:'TLT',n:'iShares 20+Y Treasury',t:'ETF'},{s:'BIL',n:'SPDR 1-3M T-Bill',t:'ETF'},{s:'JNJ',n:'Johnson & Johnson',t:'Stock'},{s:'PG',n:'Procter & Gamble',t:'Stock'},{s:'KO',n:'Coca-Cola',t:'Stock'}] },
      { id:'mod-conservative', name:'Moderately Conservative', range:[21,28], color:'#9b7fe8', desc:'Stability with some growth. Mix of fixed income and dividend stocks.', tickers:[{s:'VCIT',n:'Vanguard Interm Corp Bond',t:'ETF'},{s:'VIG',n:'Vanguard Dividend Appreciation',t:'ETF'},{s:'SDY',n:'SPDR S&P Dividend ETF',t:'ETF'},{s:'GLD',n:'SPDR Gold',t:'ETF'},{s:'SCHD',n:'Schwab US Dividend Equity',t:'ETF'},{s:'JEPI',n:'JPMorgan Equity Premium',t:'ETF'},{s:'BRK.B',n:'Berkshire Hathaway',t:'Stock'},{s:'JPM',n:'JPMorgan Chase',t:'Stock'},{s:'V',n:'Visa Inc',t:'Stock'},{s:'MA',n:'Mastercard',t:'Stock'}] },
      { id:'moderate', name:'Moderate', range:[29,36], color:'#c9a84c', desc:'Balance between growth and stability. The classic long-term portfolio.', tickers:[{s:'VOO',n:'Vanguard S&P 500',t:'ETF'},{s:'VTI',n:'Vanguard Total Stock',t:'ETF'},{s:'QQQ',n:'Invesco QQQ (Nasdaq-100)',t:'ETF'},{s:'SCHD',n:'Schwab US Dividend',t:'ETF'},{s:'VYM',n:'Vanguard High Dividend',t:'ETF'},{s:'SPY',n:'SPDR S&P 500',t:'ETF'},{s:'VXUS',n:'Vanguard Total Intl Stock',t:'ETF'},{s:'AAPL',n:'Apple',t:'Stock'},{s:'MSFT',n:'Microsoft',t:'Stock'},{s:'GOOGL',n:'Alphabet',t:'Stock'},{s:'AMZN',n:'Amazon',t:'Stock'},{s:'COST',n:'Costco',t:'Stock'}] },
      { id:'growth', name:'Growth', range:[37,41], color:'#3dd68c', desc:'Growth-oriented. High exposure to tech and future sectors.', tickers:[{s:'VGT',n:'Vanguard IT ETF',t:'ETF'},{s:'XLK',n:'Technology Select Sector',t:'ETF'},{s:'SMH',n:'VanEck Semiconductor',t:'ETF'},{s:'SOXX',n:'iShares Semiconductor',t:'ETF'},{s:'IBIT',n:'iShares Bitcoin Trust',t:'ETF'},{s:'NVDA',n:'NVIDIA Corp',t:'Stock'},{s:'TSLA',n:'Tesla',t:'Stock'},{s:'META',n:'Meta Platforms',t:'Stock'},{s:'AVGO',n:'Broadcom',t:'Stock'},{s:'AMD',n:'AMD',t:'Stock'},{s:'CRM',n:'Salesforce',t:'Stock'},{s:'PLTR',n:'Palantir',t:'Stock'}] },
      { id:'aggressive', name:'Aggressive', range:[42,45], color:'#f06b6b', desc:'Maximum growth with high risk tolerance. High-potential volatile assets.', tickers:[{s:'TQQQ',n:'ProShares UltraPro QQQ 3x',t:'ETF'},{s:'SOXL',n:'Direxion Semis 3x Bull',t:'ETF'},{s:'ARKK',n:'ARK Innovation ETF',t:'ETF'},{s:'TSLL',n:'Direxion TSLA 2x Bull',t:'ETF'},{s:'MSTR',n:'MicroStrategy',t:'Stock'},{s:'COIN',n:'Coinbase',t:'Stock'},{s:'HOOD',n:'Robinhood',t:'Stock'},{s:'SOFI',n:'SoFi',t:'Stock'},{s:'BTC-USD',n:'Bitcoin',t:'Crypto'},{s:'ETH-USD',n:'Ethereum',t:'Crypto'},{s:'SOL-USD',n:'Solana',t:'Crypto'},{s:'GME',n:'GameStop',t:'Stock'}] },
    ],
    ui: { title:'Discover Your Investor Profile', sub:'9 questions to find your ideal strategy', next:'Next', prev:'Previous', finish:'See My Profile', restart:'Restart', q:'Question', of:'of', yourProfile:'Your Profile', recommended:'Recommended Assets', clickTicker:'Click a ticker to see its chart', selectAnswer:'Select an option to continue' },
    chartTypes: { 1:'Candles', 2:'Line', 3:'Area', 0:'Bars' },
  }
};

function InvestorProfile({ lang }) {
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [selected, setSelected] = useState(null);
  const [ticker, setTicker] = useState(null);
  const [chartStyle, setChartStyle] = useState(1);
  const chartRef = useRef(null);

  const d = QZ[lang] || QZ.es;
  const qs = d.questions;
  const complete = step >= qs.length;
  const totalScore = Object.values(answers).reduce((a,b) => a+b, 0);
  const profile = complete ? (d.profiles.find(p => totalScore >= p.range[0] && totalScore <= p.range[1]) || d.profiles[d.profiles.length-1]) : null;

  const handleSelect = (score) => {
    setSelected(score);
    // Auto-advance after a brief delay so user sees their selection
    setTimeout(() => {
      setAnswers(prev => ({...prev, [step]: score}));
      setSelected(null);
      setStep(s => s+1);
    }, 220);
  };
  const handlePrev = () => {
    if (step === 0) return;
    const prev = answers[step-1] || null;
    setSelected(prev);
    setStep(s => s-1);
  };
  const handleRestart = () => { setStep(0); setAnswers({}); setSelected(null); setTicker(null); };

  const progress = complete ? 100 : Math.round((step / qs.length) * 100);

  const chartSrc = ticker
    ? `https://s3.tradingview.com/widgetembed/?symbol=${encodeURIComponent(ticker)}&interval=D&theme=dark&style=${chartStyle}&locale=${lang === 'es' ? 'es' : 'en'}&hide_top_toolbar=0&withdateranges=1&hide_side_toolbar=0&allow_symbol_change=0&save_image=false&details=0`
    : null;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, height: 520 }} className="two-col">
      {/* LEFT: Quiz */}
      <div style={{ display: 'flex', flexDirection: 'column', background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 'var(--rl)', padding: 24, overflow: 'hidden' }}>
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 17, color: 'var(--text)', marginBottom: 4 }}>{d.ui.title}</div>
          <div style={{ fontSize: 12, color: 'var(--muted)' }}>{d.ui.sub}</div>
        </div>

        {/* Progress bar */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--muted)', marginBottom: 6 }}>
            <span>{complete ? (lang==='es'?'Completado':'Completed') : `${d.ui.q} ${step+1} ${d.ui.of} ${qs.length}`}</span>
            <span>{progress}%</span>
          </div>
          <div style={{ height: 4, background: 'var(--border)', borderRadius: 99, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${progress}%`, background: 'var(--gold)', borderRadius: 99, transition: 'width 0.35s ease' }}></div>
          </div>
        </div>

        {!complete ? (
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 15, color: 'var(--text)', marginBottom: 14, lineHeight: 1.4 }}>
                {qs[step].q}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {qs[step].opts.map((opt, i) => {
                  const isSel = selected === opt.s && answers[step] === undefined ? true : answers[step] === opt.s ? true : selected === opt.s;
                  const checked = selected === opt.s;
                  return (
                    <button key={i} onClick={() => handleSelect(opt.s)}
                      style={{
                        textAlign: 'left', padding: '10px 14px',
                        background: checked ? 'rgba(201,168,76,0.12)' : 'var(--bg2)',
                        border: `1px solid ${checked ? 'var(--gold)' : 'var(--border)'}`,
                        borderRadius: 8, color: checked ? 'var(--gold)' : 'var(--text2)',
                        cursor: 'pointer', fontSize: 13, fontFamily: 'DM Sans, sans-serif',
                        transition: 'all 0.15s', display: 'flex', alignItems: 'center', gap: 10,
                      }}
                      onMouseEnter={e => { if (!checked) { e.currentTarget.style.borderColor = 'var(--muted)'; e.currentTarget.style.color = 'var(--text)'; }}}
                      onMouseLeave={e => { if (!checked) { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text2)'; }}}
                    >
                      <span style={{ width: 18, height: 18, borderRadius: '50%', border: `2px solid ${checked ? 'var(--gold)' : 'var(--border)'}`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        {checked && <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--gold)' }}></span>}
                      </span>
                      {opt.l}
                    </button>
                  );
                })}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              {step > 0 && (
                <button className="btn btn-outline" onClick={handlePrev}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="15 18 9 12 15 6"/></svg>
                  {d.ui.prev}
                </button>
              )}
              <div style={{ flex: 1, fontSize: 11, color: 'var(--muted)', textAlign: 'right', alignSelf: 'center' }}>
                {lang === 'es' ? 'Selecciona una opción para continuar' : 'Select an option to continue'}
              </div>
            </div>
          </div>
        ) : (
          /* Results summary in left panel */
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ padding: 16, background: `${profile.color}15`, border: `1px solid ${profile.color}40`, borderRadius: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: profile.color, marginBottom: 4 }}>{d.ui.yourProfile}</div>
              <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 22, color: profile.color }}>{profile.name}</div>
              <div style={{ fontSize: 12, color: 'var(--text2)', marginTop: 6, lineHeight: 1.5 }}>{profile.desc}</div>
            </div>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>{d.ui.recommended}</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {profile.tickers.map(tk => (
                  <button key={tk.s} onClick={() => setTicker(tk.s)}
                    style={{
                      padding: '6px 12px', borderRadius: 6,
                      background: ticker === tk.s ? `${profile.color}20` : 'var(--bg2)',
                      border: `1px solid ${ticker === tk.s ? profile.color : 'var(--border)'}`,
                      color: ticker === tk.s ? profile.color : 'var(--text2)',
                      cursor: 'pointer', fontSize: 12, fontWeight: 700, fontFamily: 'Barlow, sans-serif',
                      transition: 'all 0.15s',
                    }}>
                    {tk.s}
                    <span style={{ fontSize: 10, fontWeight: 400, marginLeft: 4, color: 'var(--muted)' }}>{tk.t}</span>
                  </button>
                ))}
              </div>
            </div>
            <button className="btn btn-outline btn-sm" onClick={handleRestart} style={{ alignSelf: 'flex-start', marginTop: 'auto' }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></svg>
              {d.ui.restart}
            </button>
          </div>
        )}
      </div>

      {/* RIGHT: Chart */}
      <div style={{ display: 'flex', flexDirection: 'column', background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 'var(--rl)', overflow: 'hidden' }}>
        {ticker ? (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 16px', borderBottom: '1px solid var(--border)', background: 'var(--card2)' }}>
              <span style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 15, color: 'var(--text)' }}>{ticker}</span>
              <span style={{ fontSize: 11, color: 'var(--muted)', flex: 1 }}>{profile?.tickers.find(t=>t.s===ticker)?.n || ''}</span>
              <div style={{ display: 'flex', gap: 4 }}>
                {Object.entries(d.chartTypes).map(([k,v]) => (
                  <button key={k} className={`btn btn-sm ${parseInt(k)===chartStyle ? 'btn-active' : 'btn-ghost'}`}
                    onClick={() => setChartStyle(parseInt(k))}
                    style={{ fontFamily: 'Barlow, sans-serif', fontSize: 11, padding: '4px 8px', borderRadius: 5 }}>
                    {v}
                  </button>
                ))}
              </div>
            </div>
            <iframe key={`${ticker}-${chartStyle}`} src={chartSrc}
              style={{ flex: 1, border: 'none', width: '100%' }}
              title={`Chart ${ticker}`}
              allow="fullscreen" />
          </>
        ) : (
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 12 }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--bg2)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--muted)" strokeWidth="1.5"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 14, color: 'var(--text2)', marginBottom: 4 }}>
                {complete ? d.ui.clickTicker : (lang === 'es' ? 'Completa el cuestionario' : 'Complete the questionnaire')}
              </div>
              <div style={{ fontSize: 12, color: 'var(--muted)' }}>
                {complete ? (lang==='es'?'Selecciona un activo recomendado para ver el gráfico':'Select a recommended asset to view the chart') : (lang==='es'?'El gráfico del activo aparecerá aquí':'The asset chart will appear here')}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { InvestorProfile });
