// Pantalla de detalle de acción — chart interactivo + sidebar + tabs
function StockDetail({ symbol, onBack, onOpenTicker, holdings, watchlist,
                       isWatching, onToggleWatch, accent, intensity }) {
  const t = window.TICKERS[symbol];
  const [tab, setTab] = React.useState('resumen');

  if (!t) return null;

  const up = t.change >= 0;
  const holding = holdings.find((h) => h.symbol === symbol);
  const news = (window.NEWS[symbol] || window.NEWS.NVRA).slice(0, 6);

  const tabs = [
    { id: 'resumen',    label: 'Resumen' },
    { id: 'noticias',   label: 'Noticias' },
    { id: 'fund',       label: 'Fundamentales' },
    { id: 'tecnico',    label: 'Análisis técnico' },
    { id: 'perfil',     label: 'Perfil de la empresa' },
  ];

  const fmt = (n) => Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  return (
    <div className="detail-screen">
      {/* ── HEADER ── */}
      <div className="stock-header">
        <div className="hd-left">
          <div className="hd-breadcrumb">
            <a href="#" onClick={(e) => { e.preventDefault(); onBack(); }}>Inicio</a>
            &nbsp;/&nbsp; <a href="#">{t.sector}</a> &nbsp;/&nbsp; {t.name}
          </div>
          <div className="hd-name-row">
            <div className="hd-avatar">{t.symbol.slice(0, 2)}</div>
            <div>
              <div className="hd-name-line">
                <h1 className="hd-company">{t.name}</h1>
                <span className="hd-ticker">{t.symbol}</span>
              </div>
              <div className="hd-sub">{t.market} · {t.sector} · {t.cap}</div>
            </div>
          </div>
        </div>

        <div className="hd-right">
          <div className="hd-price">
            <span className="hd-price-curr">$</span>{fmt(t.price)}
          </div>
          <div className="hd-change-row">
            <span className={`hd-change-abs ${up ? 'up' : 'dn'}`}>
              {up ? '+' : ''}${fmt(Math.abs(t.change))}
            </span>
            <span className={`hd-change-pct ${up ? 'up' : 'dn'}`}>
              {up ? '▲' : '▼'} {up ? '+' : ''}{t.pct.toFixed(2)}%
            </span>
          </div>
          <div className="hd-time">Hoy · 16:00 EDT · Mercado cerrado</div>
        </div>
      </div>

      {/* ── TABS ── */}
      <div className="detail-tabs">
        {tabs.map((tb) => (
          <button key={tb.id}
                  className={`detail-tab${tab === tb.id ? ' on' : ''}`}
                  onClick={() => setTab(tb.id)}>
            {tb.label}
          </button>
        ))}
      </div>

      <div className="main-layout">
        {/* ─── PANEL IZQUIERDO ─── */}
        <div className="main-left">

          {/* Quick stats */}
          <div className="quick-stats">
            <div className="qs-item">
              <div className="qs-label">Apertura</div>
              <div className="qs-val">${fmt(t.open)}</div>
            </div>
            <div className="qs-item">
              <div className="qs-label">Máx. diario</div>
              <div className="qs-val">${fmt(t.high)}</div>
            </div>
            <div className="qs-item">
              <div className="qs-label">Mín. diario</div>
              <div className="qs-val">${fmt(t.low)}</div>
            </div>
            <div className="qs-item">
              <div className="qs-label">Volumen</div>
              <div className="qs-val">{t.volume}</div>
            </div>
            <div className="qs-item">
              <div className="qs-label">Mkt Cap</div>
              <div className="qs-val">{t.mktcap}</div>
            </div>
          </div>

          {/* Chart */}
          <window.Chart symbol={symbol} accent={accent} intensity={intensity}/>

          {/* Contenido por tab */}
          {tab === 'resumen' && <ResumenTab t={t} news={news} accent={accent}/>}
          {tab === 'noticias' && <NoticiasTab news={news}/>}
          {tab === 'fund' && <FundTab t={t}/>}
          {tab === 'tecnico' && <TecnicoTab t={t}/>}
          {tab === 'perfil' && <PerfilTab t={t}/>}
        </div>

        {/* ─── SIDEBAR DERECHO ─── */}
        <div className="sidebar">

          {/* Calculadora de análisis */}
          <Calculator t={t} fmt={fmt}/>

          <button className={`watch-btn${isWatching ? ' on' : ''}`}
                  onClick={() => onToggleWatch(symbol)}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill={isWatching ? 'currentColor' : 'none'}>
              <path d="M7 1.5L8.5 5h3.5L9.25 7.5 10.75 11 7 8.75 3.25 11 4.75 7.5 1.5 5H5Z"
                    stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/>
            </svg>
            {isWatching ? 'En seguimiento' : 'Añadir a seguimiento'}
          </button>

          {/* Mi posición */}
          {holding && (
            <>
              <div className="sidebar-label">Mi posición</div>
              <div className="metrics-panel position-panel">
                <div className="m-row">
                  <span className="m-label">Acciones</span>
                  <span className="m-val">{holding.shares}</span>
                </div>
                <div className="m-row">
                  <span className="m-label">Coste medio</span>
                  <span className="m-val">${fmt(holding.avgCost)}</span>
                </div>
                <div className="m-row">
                  <span className="m-label">Valor de mercado</span>
                  <span className="m-val">${fmt(t.price * holding.shares)}</span>
                </div>
                <div className="m-row">
                  <span className="m-label">P&amp;L</span>
                  <span className={`m-val ${t.price >= holding.avgCost ? 'up' : 'dn'}`}>
                    {t.price >= holding.avgCost ? '+' : ''}${fmt((t.price - holding.avgCost) * holding.shares)}
                    {' · '}
                    {(((t.price - holding.avgCost) / holding.avgCost) * 100).toFixed(2)}%
                  </span>
                </div>
              </div>
            </>
          )}

          <div className="sidebar-label">Métricas clave</div>
          <div className="metrics-panel">
            <div className="m-row"><span className="m-label">Capitalización</span><span className="m-val">{t.mktcap}</span></div>
            <div className="m-row"><span className="m-label">Volumen hoy</span><span className="m-val">{t.volume}</span></div>
            <div className="m-row"><span className="m-label">P/E Ratio</span><span className="m-val">{t.pe}</span></div>
            <div className="m-row"><span className="m-label">EPS (TTM)</span><span className="m-val">{t.eps}</span></div>
            <div className="m-row"><span className="m-label">Dividendo</span><span className={`m-val ${t.div === '—' ? 'muted' : 'up'}`}>{t.div}</span></div>
            <div className="m-row"><span className="m-label">Margen neto</span><span className="m-val">{t.margin}</span></div>
            <div className="m-row"><span className="m-label">Beta (5 años)</span><span className="m-val">{t.beta}</span></div>
          </div>

          <div className="sidebar-label">Rango 52 semanas</div>
          <div className="metrics-panel">
            <div className="m-52w">
              <div className="m-52w-labels">
                <span>Mín. ${fmt(t.range52.min)}</span>
                <span>${fmt(t.price)}</span>
                <span>Máx. ${fmt(t.range52.max)}</span>
              </div>
              <div className="m-52w-bar">
                <div className="m-52w-fill" style={{ width: `${t.range52.pos * 100}%` }}></div>
                <div className="m-52w-dot" style={{ left: `${t.range52.pos * 100}%` }}></div>
              </div>
            </div>
            <div className="m-row">
              <span className="m-label">Distancia al máx.</span>
              <span className="m-val dn">−{(((t.range52.max - t.price) / t.range52.max) * 100).toFixed(1)}%</span>
            </div>
            <div className="m-row">
              <span className="m-label">Distancia al mín.</span>
              <span className="m-val up">+{(((t.price - t.range52.min) / t.range52.min) * 100).toFixed(1)}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Sub-tabs ─────────────────────────────────────────────────────────────
function ResumenTab({ t, news, accent }) {
  return (
    <>
      <section className="info-grid">
        <div className="info-block">
          <div className="info-label">Sobre {t.name}</div>
          <p className="info-text">{t.desc}</p>
        </div>
        <div className="info-block">
          <div className="info-label">Consenso de analistas</div>
          <div className="consensus">
            <div className="consensus-ring">
              <svg viewBox="0 0 100 100" width="92" height="92">
                <circle cx="50" cy="50" r="42" fill="none" stroke="var(--border)" strokeWidth="8"/>
                <circle cx="50" cy="50" r="42" fill="none" stroke="var(--accent)" strokeWidth="8"
                        strokeDasharray={`${(4.2 / 5) * 2 * Math.PI * 42} ${2 * Math.PI * 42}`}
                        transform="rotate(-90 50 50)"
                        strokeLinecap="round"
                        style={{ filter: 'drop-shadow(0 0 6px var(--accent-glow))' }}/>
              </svg>
              <div className="consensus-score">
                <strong>4.2</strong>
                <span>/ 5</span>
              </div>
            </div>
            <div className="consensus-bars">
              {[
                { label: 'Comprar fuerte', n: 18, pct: 60, cls: 'up' },
                { label: 'Comprar',         n: 8,  pct: 27, cls: 'up' },
                { label: 'Mantener',        n: 3,  pct: 10, cls: 'mid' },
                { label: 'Vender',          n: 1,  pct: 3,  cls: 'dn' },
              ].map((r) => (
                <div key={r.label} className="cb-row">
                  <span className="cb-label">{r.label}</span>
                  <div className="cb-bar"><div className={`cb-fill ${r.cls}`} style={{ width: `${r.pct}%` }}></div></div>
                  <span className="cb-n">{r.n}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <section className="news-section">
        <div className="news-section-head">
          <span className="news-section-title">Noticias recientes</span>
          <a href="#" className="news-more">Ver todas →</a>
        </div>
        <div className="news-grid">
          {news.slice(0, 3).map((n, i) => <NewsCard key={i} n={n} accent={accent}/>)}
        </div>
      </section>
    </>
  );
}

function NoticiasTab({ news }) {
  return (
    <section className="news-section">
      <div className="news-section-head">
        <span className="news-section-title">Todas las noticias</span>
      </div>
      <div className="news-list">
        {news.map((n, i) => (
          <a href="#" key={i} className="news-list-item">
            <div className="news-list-tag" data-tone={n.tone}>{n.tag}</div>
            <div className="news-list-body">
              <div className="news-list-headline">{n.headline}</div>
              <div className="news-list-meta">{n.src} · {n.when}</div>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

function FundTab({ t }) {
  const rows = [
    ['Ingresos (TTM)',   '$382.4B',  '$391.0B', '+2.3%'],
    ['Beneficio neto',   '$101.0B',  '$99.8B',  '−1.2%'],
    ['Margen operativo', '30.1%',    '29.4%',   '−70 pb'],
    ['Flujo de caja libre', '$96.4B', '$92.1B', '−4.5%'],
    ['Deuda total',      '$108B',    '$104B',   '−3.7%'],
    ['ROE',              '147%',     '156%',    '+900 pb'],
  ];
  return (
    <section className="fund-section">
      <div className="news-section-head">
        <span className="news-section-title">Estado financiero · {t.name}</span>
      </div>
      <table className="fund-table">
        <thead>
          <tr><th>Métrica</th><th>2024</th><th>2023</th><th>Var.</th></tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r[0]}>
              <td>{r[0]}</td>
              <td className="num strong">{r[1]}</td>
              <td className="num">{r[2]}</td>
              <td className={`num ${r[3].startsWith('+') ? 'up' : 'dn'}`}>{r[3]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

function TecnicoTab({ t }) {
  const signals = [
    { label: 'RSI (14)',          val: '58.2',  tag: 'Neutral',     cls: 'mid' },
    { label: 'MACD',              val: '+1.42', tag: 'Compra',      cls: 'up' },
    { label: 'Media móvil 50d',   val: '$208.40', tag: 'Compra',    cls: 'up' },
    { label: 'Media móvil 200d',  val: '$192.10', tag: 'Compra fuerte', cls: 'up' },
    { label: 'Bandas de Bollinger', val: 'Centro', tag: 'Neutral',  cls: 'mid' },
    { label: 'Estocástico',       val: '72.1',   tag: 'Sobrecomprado', cls: 'dn' },
  ];
  return (
    <section className="tech-section">
      <div className="news-section-head">
        <span className="news-section-title">Indicadores técnicos</span>
      </div>
      <div className="tech-grid">
        {signals.map((s) => (
          <div key={s.label} className="tech-card">
            <div className="tech-label">{s.label}</div>
            <div className="tech-val">{s.val}</div>
            <div className={`tech-tag ${s.cls}`}>{s.tag}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function PerfilTab({ t }) {
  return (
    <section className="profile-section">
      <div className="profile-grid">
        <div>
          <div className="info-label">Descripción</div>
          <p className="info-text">{t.desc}</p>
        </div>
        <div>
          <div className="info-label">Datos clave</div>
          <ul className="profile-list">
            <li><span>CEO</span><strong>{'M. Vázquez'}</strong></li>
            <li><span>Sede</span><strong>{'San Francisco, CA'}</strong></li>
            <li><span>Empleados</span><strong>{'164,200'}</strong></li>
            <li><span>Fundación</span><strong>{'1998'}</strong></li>
            <li><span>Web</span><strong>{t.name.toLowerCase().replace(/\s+/g,'')}.com</strong></li>
          </ul>
        </div>
      </div>
    </section>
  );
}

function NewsCard({ n, accent }) {
  const toneColors = { pos: 'var(--accent)', neg: 'var(--neg)', neutral: 'var(--c-cyan)' };
  const c = toneColors[n.tone] || 'var(--accent)';
  return (
    <a href="#" className="news-card">
      <div className="news-img" style={{ background: `linear-gradient(135deg, color-mix(in oklab, ${c} 12%, var(--bg-card)) 0%, var(--bg-card) 80%)` }}>
        <div className="news-img-pattern">
          <svg width="100%" height="100%" viewBox="0 0 320 72" preserveAspectRatio="none">
            <polyline points={n.tone === 'neg'
                ? "10,20 60,30 110,40 160,52 210,46 260,58 310,60"
                : "10,55 60,42 110,38 160,28 210,22 260,18 310,8"}
              stroke={c} strokeWidth="2" fill="none" opacity="0.6"/>
            <polygon points={n.tone === 'neg'
                ? "10,20 60,30 110,40 160,52 210,46 260,58 310,60 310,72 10,72"
                : "10,55 60,42 110,38 160,28 210,22 260,18 310,8 310,72 10,72"}
              fill={c} opacity="0.08"/>
          </svg>
        </div>
      </div>
      <span className="news-tag" style={{ color: c }}>{n.tag}</span>
      <p className="news-hl">{n.headline}</p>
      <span className="news-meta">{n.src} · {n.when}</span>
    </a>
  );
}

// ─── Calculator ────────────────────────────────────────────────────────────
// Herramienta de análisis: dado un número de acciones (o monto a invertir),
// muestra el valor actual y permite proyectar valor a un precio objetivo.
function Calculator({ t, fmt }) {
  const [shares, setShares] = React.useState(100);
  const [target, setTarget] = React.useState(t.price);
  const [editing, setEditing] = React.useState('shares'); // 'shares' | 'amount'
  const [amount, setAmount] = React.useState(100 * t.price);

  // Estado local para inputs en texto — evita reformateo en cada tecla
  const [sharesText, setSharesText]   = React.useState('100');
  const [amountText, setAmountText]   = React.useState('');
  const [targetText, setTargetText]   = React.useState('');
  const [focusField, setFocusField]   = React.useState(null);

  // Cambio de ticker: resetear
  React.useEffect(() => {
    setShares(100);
    setAmount(100 * t.price);
    setTarget(t.price);
    setEditing('shares');
    setSharesText('100');
  }, [t.symbol]);

  // Sincronización bidireccional
  React.useEffect(() => {
    if (editing === 'shares') setAmount(shares * t.price);
  }, [shares, t.price, editing]);
  React.useEffect(() => {
    if (editing === 'amount') setShares(amount / t.price);
  }, [amount, t.price, editing]);

  // Cuando NO está siendo editado, mostrar el valor formateado
  const sharesDisplay = focusField === 'shares' ? sharesText
    : Number.isInteger(shares) ? String(shares) : shares.toFixed(2);
  const amountDisplay = focusField === 'amount' ? amountText : fmt(amount);
  const targetDisplay = focusField === 'target' ? targetText : fmt(target);

  const currentValue = shares * t.price;
  const projectedValue = shares * target;
  const diff = projectedValue - currentValue;
  const diffPct = t.price > 0 ? ((target - t.price) / t.price) * 100 : 0;
  const isUp = diff >= 0;

  const presets = [
    { label: '−10%',    pct: -0.10 },
    { label: 'Actual',  pct: 0 },
    { label: '+10%',    pct:  0.10 },
    { label: '+25%',    pct:  0.25 },
    { label: 'Máx. 52s', value: t.range52.max },
  ];

  const sliderMin = t.range52.min * 0.5;
  const sliderMax = t.range52.max * 1.5;

  const parseNum = (s) => {
    const cleaned = String(s).replace(/[^\d.]/g, '');
    const n = Number(cleaned);
    return Number.isFinite(n) ? Math.max(0, n) : 0;
  };

  return (
    <div className="calc-panel">
      <header className="calc-head">
        <div className="calc-head-icon" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <rect x="2.5" y="1.5" width="11" height="13" rx="1.5" stroke="currentColor" strokeWidth="1.3"/>
            <rect x="4.5" y="3.5" width="7" height="2.5" rx="0.5" fill="currentColor" opacity=".18"/>
            <circle cx="5.5" cy="8.5"  r="0.9" fill="currentColor"/>
            <circle cx="8"   cy="8.5"  r="0.9" fill="currentColor"/>
            <circle cx="10.5" cy="8.5" r="0.9" fill="currentColor"/>
            <circle cx="5.5" cy="11"   r="0.9" fill="currentColor"/>
            <circle cx="8"   cy="11"   r="0.9" fill="currentColor"/>
            <rect x="9.7" y="10.1" width="1.8" height="2.4" rx="0.4" fill="currentColor"/>
          </svg>
        </div>
        <h3>Calculadora</h3>
        <span className="calc-ref">${fmt(t.price)} <em>actual</em></span>
      </header>

      {/* Inputs: acciones <-> inversión */}
      <div className="calc-inputs">
        <label className="calc-field">
          <span>Acciones</span>
          <div className="calc-input">
            <input type="text" inputMode="numeric" value={sharesDisplay}
                   onFocus={() => { setFocusField('shares'); setEditing('shares'); setSharesText(sharesDisplay); }}
                   onBlur={() => setFocusField(null)}
                   onChange={(e) => {
                     setEditing('shares');
                     setSharesText(e.target.value);
                     setShares(parseNum(e.target.value));
                   }}/>
          </div>
        </label>
        <div className="calc-equals" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <path d="M3 6h10M3 10h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
        </div>
        <label className="calc-field">
          <span>Inversión</span>
          <div className="calc-input">
            <em>$</em>
            <input type="text" inputMode="decimal" value={amountDisplay}
                   onFocus={() => { setFocusField('amount'); setEditing('amount'); setAmountText(String(amount.toFixed(2))); }}
                   onBlur={() => setFocusField(null)}
                   onChange={(e) => {
                     setEditing('amount');
                     setAmountText(e.target.value);
                     setAmount(parseNum(e.target.value));
                   }}/>
          </div>
        </label>
      </div>

      {/* Valor actual destacado */}
      <div className="calc-result-current">
        <div className="calc-result-label">Valor actual de la posición</div>
        <div className="calc-result-value">
          <span className="calc-curr">$</span>{fmt(currentValue)}
        </div>
      </div>

      <div className="calc-divider"></div>

      {/* Proyección */}
      <div className="calc-project">
        <div className="calc-project-head">
          <span>Precio objetivo</span>
          <span className={`calc-project-pct ${isUp ? 'up' : 'dn'}`}>
            {diffPct >= 0 ? '+' : ''}{diffPct.toFixed(1)}%
          </span>
        </div>

        <div className="calc-target-input">
          <em>$</em>
          <input type="text" inputMode="decimal" value={targetDisplay}
                 onFocus={() => { setFocusField('target'); setTargetText(target.toFixed(2)); }}
                 onBlur={() => setFocusField(null)}
                 onChange={(e) => {
                   setTargetText(e.target.value);
                   setTarget(parseNum(e.target.value));
                 }}/>
        </div>

        <input type="range" className="calc-slider"
               min={sliderMin} max={sliderMax} step={0.1}
               value={target}
               onChange={(e) => setTarget(Number(e.target.value))}/>
        <div className="calc-slider-marks">
          <span>${fmt(sliderMin)}</span>
          <span className="calc-mark-now" style={{ left: `${((t.price - sliderMin) / (sliderMax - sliderMin)) * 100}%` }}>
            ${fmt(t.price)}
          </span>
          <span>${fmt(sliderMax)}</span>
        </div>

        <div className="calc-presets">
          {presets.map((p) => {
            const v = p.value != null ? p.value : t.price * (1 + p.pct);
            const active = Math.abs(target - v) < 0.01;
            return (
              <button key={p.label}
                      className={`calc-preset${active ? ' on' : ''}`}
                      onClick={() => setTarget(v)}>
                {p.label}
              </button>
            );
          })}
        </div>

        <div className="calc-projection-rows">
          <div className="calc-pr-row">
            <span>Valor proyectado</span>
            <span className="calc-pr-val">${fmt(projectedValue)}</span>
          </div>
          <div className="calc-pr-row">
            <span>Diferencia</span>
            <span className={`calc-pr-val ${isUp ? 'up' : 'dn'}`}>
              {isUp ? '+' : '−'}${fmt(Math.abs(diff))}
            </span>
          </div>
          <div className="calc-pr-row">
            <span>Rentabilidad</span>
            <span className={`calc-pr-val ${isUp ? 'up' : 'dn'}`}>
              {diffPct >= 0 ? '+' : ''}{diffPct.toFixed(2)}%
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

window.StockDetail = StockDetail;
