// THEME D · Analyst Terminal — Gestor / trader (DARK)
// Densidad alta, escaneo rápido, tabla + heatmap + waterfall + watchlist.
// Inspirado en terminales profesionales: hairlines, mono everywhere, color = signo.

const AT = {
  bg:       '#0A0E14',
  panel:    '#0F1420',
  panel2:   '#121826',
  ink:      '#E2E8F0',
  inkSoft:  '#94A3B8',
  mute:     '#64748B',
  divider:  '#1E293B',
  hairline: '#26344F',
  accent:   FINAZ_TOKENS.live,
  type: {
    sans: '"Geist", "IBM Plex Sans", sans-serif',
    mono: '"Geist Mono", "IBM Plex Mono", ui-monospace, monospace',
  },
};

function HeatCell({ s }) {
  const intensity = Math.min(Math.abs(s.chg) / 2.5, 1);
  const color = s.chg >= 0 ? FINAZ_TOKENS.positive : FINAZ_TOKENS.negative;
  const bg = `color-mix(in oklab, ${color} ${Math.round(10 + intensity * 60)}%, transparent)`;
  return (
    <div style={{ background: bg, padding: '10px 12px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', borderRight: `1px solid ${AT.hairline}`, minHeight: 76, fontFamily: AT.type.mono }}>
      <div style={{ fontSize: 11, color: AT.ink, fontWeight: 500 }}>{s.name}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <Delta value={s.chg} size={15} theme="dark" />
        <span style={{ fontSize: 10, color: AT.mute }}>{(s.contrib>=0?'+':'')+s.contrib.toFixed(2)}pp</span>
      </div>
    </div>
  );
}

function MiniSpark({ width = 70, height = 22, positive = true }) {
  // synthetic noisy mini sparkline
  const pts = Array.from({ length: 24 }, (_, i) => {
    const x = (i / 23) * width;
    const phase = (Math.sin(i * 0.7) + Math.cos(i * 0.31)) * 0.4 + (i / 23) * (positive ? 0.6 : -0.6);
    const y = height/2 - phase * height * 0.45;
    return [x, y];
  });
  const d = pts.map(([x,y], i) => (i === 0 ? 'M' : 'L') + x.toFixed(1) + ' ' + y.toFixed(1)).join(' ');
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <path d={d} stroke={positive ? FINAZ_TOKENS.positive : FINAZ_TOKENS.negative} strokeWidth="1" fill="none" strokeLinejoin="round" />
    </svg>
  );
}

// ─── Spec card ──────────────────────────────────────────────────────────
function AnalystSpec() {
  return (
    <div style={{
      width: '100%', height: '100%',
      background: AT.bg, color: AT.ink, padding: 36,
      fontFamily: AT.type.sans, overflow: 'hidden',
      '--mono': AT.type.mono,
      backgroundImage: 'radial-gradient(circle at 100% 0%, rgba(37,99,235,0.06), transparent 50%)',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.16em', color: AT.mute, fontFamily: AT.type.mono }}>TEMA D · GESTOR / TRADER</div>
          <div style={{ fontSize: 34, fontFamily: AT.type.mono, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 8, lineHeight: 1.05, color: AT.ink }}>
            Analyst<span style={{ color: AT.accent }}>.</span>Terminal
          </div>
          <div style={{ fontSize: 13, color: AT.inkSoft, marginTop: 8, maxWidth: 420, lineHeight: 1.5 }}>
            Compacto, operativo, denso. Escaneo rápido, comparación, drilldown bajo demanda. <em>Sin storytelling</em>: el dato manda.
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 10, color: AT.mute, fontFamily: AT.type.mono, letterSpacing: '0.08em' }}>DENSIDAD</div>
          <div style={{ display: 'flex', gap: 3, marginTop: 6, justifyContent: 'flex-end' }}>
            {[1,2,3,4,5].map(i => <span key={i} style={{ width: 14, height: 4, borderRadius: 1, background: i <= 5 ? AT.accent : AT.divider }} />)}
          </div>
          <div style={{ fontSize: 11, color: AT.inkSoft, marginTop: 4, fontFamily: AT.type.mono }}>Alta</div>
        </div>
      </div>

      {/* type */}
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: AT.mute, marginBottom: 12, marginTop: 24, fontFamily: AT.type.mono }}>TIPOGRAFÍA</div>
      <div style={{ display: 'grid', gap: 8 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderBottom: `1px solid ${AT.divider}`, paddingBottom: 6 }}>
          <span style={{ fontFamily: AT.type.mono, fontSize: 26, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em', color: AT.ink }}>11.275,40 <span style={{ color: FINAZ_TOKENS.positive }}>+1,24%</span></span>
          <span style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute }}>Geist Mono · 26 · ticker</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderBottom: `1px solid ${AT.divider}`, paddingBottom: 6 }}>
          <span style={{ fontFamily: AT.type.sans, fontSize: 13, color: AT.ink }}>Banca +2,4% · Inmobiliario −1,0% · Volumen +18%</span>
          <span style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute }}>Geist · 13 · row label</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, letterSpacing: '0.08em' }}>SIM-SECTOR-004 · 16:38 · MOCK</span>
          <span style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute }}>Geist Mono · 10 · meta</span>
        </div>
      </div>

      {/* tokens */}
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: AT.mute, marginBottom: 12, marginTop: 24, fontFamily: AT.type.mono }}>TOKENS</div>
      <div>
        <Swatch name="finaz.signal.positive" hex={FINAZ_TOKENS.positive} note="Filas/celdas en verde · tabular" theme="dark" />
        <Swatch name="finaz.signal.negative" hex={FINAZ_TOKENS.negative} note="Filas/celdas en rojo · tabular" theme="dark" />
        <Swatch name="finaz.status.live"     hex={FINAZ_TOKENS.live}     note="Feed conectado · pulso discreto" theme="dark" />
        <Swatch name="terminal.bg"           hex={AT.bg}                  note="Fondo principal · profundidad alta" theme="dark" />
      </div>

      {/* states */}
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: AT.mute, marginBottom: 12, marginTop: 24, fontFamily: AT.type.mono }}>ESTADOS DE DATO</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {['LIVE','DELAYED','FROZEN','MOCK','EST','CORRECTED'].map(s => <StateChip key={s} state={s} theme="dark" />)}
      </div>

      {/* do/dont */}
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: AT.mute, marginBottom: 12, marginTop: 24, fontFamily: AT.type.mono }}>REGLAS DEL TEMA</div>
      <DoDont items={[
        { kind: 'do',   text: 'Tablas ordenables, sparklines, filtros persistentes.' },
        { kind: 'dont', text: 'Storytelling lento o animaciones que retrasen el escaneo.' },
        { kind: 'do',   text: 'Source cards plegadas en tooltip; no romper el ritmo.' },
        { kind: 'dont', text: 'Color sin signo ni etiqueta. Color ≠ única información.' },
      ]} theme="dark" />

      <div style={{ position: 'absolute', bottom: 24, left: 36, right: 36, display: 'flex', justifyContent: 'space-between', fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, letterSpacing: '0.08em', borderTop: `1px solid ${AT.divider}`, paddingTop: 12 }}>
        <span>INFORMAR · COMPARAR · ALERTAR</span>
        <span>WATCHLIST · HEATMAP · WATERFALL</span>
      </div>
    </div>
  );
}

// ─── Screen archetype: analyst workbench ───────────────────────────────
function AnalystScreen() {
  const { d, area, px, py } = scenarioPath(640, 220, 8);

  const watchlist = [
    { t: 'IBEX SIM',    last: '11.275,40', d: 1.24,  vol: '+18%', pos: true,  src: 'SIM-MKT-001'},
    { t: 'BANCA SIM',   last: '128,40',   d: 2.40,  vol: '+24%', pos: true,  src: 'SIM-SECTOR-004'},
    { t: 'ENERG SIM',   last: '74,15',    d: -0.70, vol: '+5%',  pos: false, src: 'SIM-SECTOR-004'},
    { t: 'INMOB SIM',   last: '12,08',    d: -1.00, vol: '+9%',  pos: false, src: 'SIM-SECTOR-004'},
    { t: 'TECH SIM',    last: '208,50',   d: 0.30,  vol: '+3%',  pos: true,  src: 'SIM-SECTOR-004'},
    { t: 'UTIL SIM',    last: '52,90',    d: 0.10,  vol: '+1%',  pos: true,  src: 'SIM-SECTOR-004'},
  ];

  return (
    <div style={{
      width: '100%', height: '100%',
      background: AT.bg, color: AT.ink, fontFamily: AT.type.sans,
      overflow: 'hidden', display: 'flex', flexDirection: 'column',
      '--mono': AT.type.mono,
    }}>
      {/* command bar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '10px 18px', borderBottom: `1px solid ${AT.divider}`, background: AT.panel, fontFamily: AT.type.mono, fontSize: 11 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 18, height: 18, background: AT.accent, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700 }}>F</div>
          <span style={{ color: AT.inkSoft, letterSpacing: '0.1em' }}>FINAZ · ANALYST TERMINAL</span>
        </div>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 4, padding: '5px 10px', background: AT.bg, border: `1px solid ${AT.divider}`, borderRadius: 3, maxWidth: 320 }}>
          <span style={{ color: AT.mute }}>{'>'}</span>
          <span style={{ color: AT.ink }}>IBEX SIM <span style={{ color: AT.mute }}>· intraday · 1m</span></span>
        </div>
        <div style={{ display: 'flex', gap: 14, color: AT.inkSoft }}>
          <span>F1 watchlist</span><span>F2 heatmap</span><span>F3 levels</span><span>F4 fundamentals</span>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <StateChip state="MOCK" theme="dark" />
          <span style={{ color: AT.mute }}>16:40:12 CET</span>
        </div>
      </div>

      {/* grid */}
      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '290px 1fr 280px', minHeight: 0 }}>
        {/* left: watchlist */}
        <div style={{ borderRight: `1px solid ${AT.divider}`, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: '8px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: `1px solid ${AT.divider}`, background: AT.panel }}>
            <span style={{ fontFamily: AT.type.mono, fontSize: 10, letterSpacing: '0.14em', color: AT.inkSoft }}>WATCHLIST · 6</span>
            <span style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute }}>%CHG ▼</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 70px 56px 70px', fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, padding: '6px 14px', borderBottom: `1px solid ${AT.divider}`, letterSpacing: '0.06em' }}>
            <span>TICKER</span><span style={{ textAlign: 'right' }}>LAST</span><span style={{ textAlign: 'right' }}>%CHG</span><span style={{ textAlign: 'right' }}>SPARK</span>
          </div>
          <div style={{ flex: 1, overflow: 'hidden' }}>
            {watchlist.map((r, i) => (
              <div key={r.t} style={{
                display: 'grid', gridTemplateColumns: '1fr 70px 56px 70px',
                fontFamily: AT.type.mono, fontSize: 11, padding: '8px 14px',
                background: i === 0 ? 'rgba(37,99,235,0.08)' : 'transparent',
                borderBottom: `1px solid ${AT.divider}`,
                alignItems: 'center',
              }}>
                <span style={{ color: AT.ink, fontWeight: i === 0 ? 600 : 400 }}>{r.t}</span>
                <span style={{ color: AT.ink, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{r.last}</span>
                <span style={{ textAlign: 'right' }}><Delta value={r.d} size={11} theme="dark" /></span>
                <span style={{ display: 'flex', justifyContent: 'flex-end' }}><MiniSpark positive={r.pos} /></span>
              </div>
            ))}
          </div>
          <div style={{ padding: '10px 14px', borderTop: `1px solid ${AT.divider}`, background: AT.panel, fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, display: 'flex', justifyContent: 'space-between' }}>
            <span>Σ contribución</span>
            <span style={{ color: FINAZ_TOKENS.positive }}>+0,59 pp</span>
          </div>
        </div>

        {/* center: chart + waterfall */}
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          {/* kpi strip */}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 22, padding: '14px 22px', borderBottom: `1px solid ${AT.divider}` }}>
            <div>
              <div style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, letterSpacing: '0.1em' }}>IBEX SIM · 1D</div>
              <div style={{ fontFamily: AT.type.mono, fontSize: 26, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em', color: AT.ink, marginTop: 2 }}>11.275,40</div>
            </div>
            <div><Delta value={1.24} size={20} theme="dark" /><div style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, marginTop: 2 }}>SESIÓN</div></div>
            <div><span style={{ fontFamily: AT.type.mono, fontSize: 18, color: AT.ink, fontVariantNumeric: 'tabular-nums' }}>11.318,60</span><div style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, marginTop: 2 }}>HIGH</div></div>
            <div><span style={{ fontFamily: AT.type.mono, fontSize: 18, color: AT.ink, fontVariantNumeric: 'tabular-nums' }}>11.018,40</span><div style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, marginTop: 2 }}>LOW</div></div>
            <div><Delta value={-2.80} size={18} theme="dark" /><div style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute, marginTop: 2 }}>DRAWDOWN</div></div>
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
              {['1m','5m','30m','1H','1D','1W'].map(p => (
                <span key={p} style={{
                  fontFamily: AT.type.mono, fontSize: 10,
                  padding: '3px 7px', borderRadius: 2,
                  background: p === '1m' ? AT.accent : 'transparent',
                  color: p === '1m' ? '#fff' : AT.inkSoft,
                  border: p === '1m' ? 'none' : `1px solid ${AT.divider}`,
                }}>{p}</span>
              ))}
            </div>
          </div>

          {/* chart */}
          <div style={{ flex: 1, position: 'relative', padding: '12px 22px', minHeight: 0 }}>
            <svg viewBox="0 0 640 220" width="100%" height="100%" preserveAspectRatio="none">
              {/* grid */}
              {[0.2,0.4,0.6,0.8].map(p => (
                <g key={p}>
                  <line x1="0" x2="640" y1={220*p} y2={220*p} stroke={AT.divider} />
                  <text x="6" y={220*p-2} fontFamily={AT.type.mono} fontSize="9" fill={AT.mute}>{(11340 - p*340).toFixed(0)}</text>
                </g>
              ))}
              {/* watch levels */}
              <line x1="0" x2="640" y1={py(11340)} y2={py(11340)} stroke={FINAZ_TOKENS.warning} strokeDasharray="3 3" strokeWidth="1" />
              <text x="634" y={py(11340)-3} textAnchor="end" fontFamily={AT.type.mono} fontSize="9" fill={FINAZ_TOKENS.warning}>R 11.340</text>
              <line x1="0" x2="640" y1={py(11180)} y2={py(11180)} stroke={FINAZ_TOKENS.warning} strokeDasharray="3 3" strokeWidth="1" opacity="0.5" />
              <text x="634" y={py(11180)-3} textAnchor="end" fontFamily={AT.type.mono} fontSize="9" fill={FINAZ_TOKENS.warning} opacity="0.7">S 11.180</text>
              {/* area */}
              <path d={area} fill={AT.accent} fillOpacity="0.10" />
              <path d={d} stroke={AT.accent} strokeWidth="1.4" fill="none" />
              {/* events */}
              {SCENARIO.events.map(ev => {
                const cx = px(ev.t); const cy = py(SCENARIO.series.find(s => s.i === ev.t).v);
                return (
                  <g key={ev.time}>
                    <line x1={cx} x2={cx} y1="0" y2="220" stroke={AT.hairline} strokeWidth="0.6" />
                    <circle cx={cx} cy={cy} r="3" fill={AT.bg} stroke={AT.accent} strokeWidth="1.4" />
                  </g>
                );
              })}
            </svg>
          </div>

          {/* waterfall (sector contribution) */}
          <div style={{ borderTop: `1px solid ${AT.divider}`, padding: '10px 22px 14px', background: AT.panel }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <span style={{ fontFamily: AT.type.mono, fontSize: 10, letterSpacing: '0.12em', color: AT.inkSoft }}>WATERFALL · CONTRIBUCIÓN SECTORIAL (pp)</span>
              <span style={{ fontFamily: AT.type.mono, fontSize: 10, color: AT.mute }}>SIM-SECTOR-004 · MOCK</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 70 }}>
              {SCENARIO.sectors.map(s => {
                const h = Math.abs(s.contrib) * 90;
                const positive = s.contrib >= 0;
                return (
                  <div key={s.name} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                    <div style={{ fontFamily: AT.type.mono, fontSize: 9, color: positive ? FINAZ_TOKENS.positive : FINAZ_TOKENS.negative }}>{(s.contrib>=0?'+':'')+s.contrib.toFixed(2)}</div>
                    <div style={{ height: h, width: '100%', background: positive ? FINAZ_TOKENS.positive : FINAZ_TOKENS.negative, opacity: 0.85 }} />
                    <div style={{ fontFamily: AT.type.mono, fontSize: 9, color: AT.mute, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.name.slice(0,5)}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* right: heatmap + alerts */}
        <div style={{ borderLeft: `1px solid ${AT.divider}`, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: '8px 14px', borderBottom: `1px solid ${AT.divider}`, background: AT.panel, fontFamily: AT.type.mono, fontSize: 10, letterSpacing: '0.14em', color: AT.inkSoft }}>HEATMAP SECTORIAL</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', borderBottom: `1px solid ${AT.divider}` }}>
            {SCENARIO.sectors.slice(0,6).map(s => (
              <div key={s.name} style={{ borderBottom: `1px solid ${AT.hairline}` }}><HeatCell s={s} /></div>
            ))}
          </div>

          <div style={{ padding: '8px 14px', borderBottom: `1px solid ${AT.divider}`, background: AT.panel, fontFamily: AT.type.mono, fontSize: 10, letterSpacing: '0.14em', color: AT.inkSoft, marginTop: 0 }}>ALERTAS · WATCH LEVELS</div>
          <div style={{ flex: 1, fontFamily: AT.type.mono, fontSize: 10.5, padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 8, overflow: 'hidden' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', color: AT.ink, padding: '6px 8px', background: 'rgba(109,40,217,0.10)', borderLeft: `2px solid ${FINAZ_TOKENS.warning}` }}>
              <span>R 11.340 · IBEX SIM</span><span style={{ color: FINAZ_TOKENS.warning }}>−0,57%</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', color: AT.ink, padding: '6px 8px', background: 'rgba(37,99,235,0.08)', borderLeft: `2px solid ${FINAZ_TOKENS.live}` }}>
              <span>VOL 20D · BANCA</span><span style={{ color: FINAZ_TOKENS.live }}>+24%</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', color: AT.inkSoft, padding: '6px 8px', borderLeft: `2px solid ${AT.divider}` }}>
              <span>S 11.180 · IBEX SIM</span><span>+0,85%</span>
            </div>
            <div style={{ fontSize: 9, color: AT.mute, marginTop: 4, fontStyle: 'italic' }}>Niveles de vigilancia. No recomendación.</div>
          </div>
        </div>
      </div>

      {/* footer ticker */}
      <div style={{ borderTop: `1px solid ${AT.divider}`, background: '#000', padding: '6px 18px', display: 'flex', gap: 24, fontFamily: AT.type.mono, fontSize: 11, color: AT.inkSoft, overflow: 'hidden', whiteSpace: 'nowrap' }}>
        <span>IBEX SIM <span style={{ color: FINAZ_TOKENS.positive }}>+1,24%</span></span>
        <span>DAX SIM <span style={{ color: FINAZ_TOKENS.positive }}>+0,82%</span></span>
        <span>CAC SIM <span style={{ color: FINAZ_TOKENS.positive }}>+0,45%</span></span>
        <span>FTSE SIM <span style={{ color: FINAZ_TOKENS.negative }}>−0,12%</span></span>
        <span>EUR/USD <span style={{ color: FINAZ_TOKENS.positive }}>+0,18%</span></span>
        <span>BUND10Y <span style={{ color: FINAZ_TOKENS.negative }}>−2.4 bps</span></span>
        <span>BRENT SIM <span style={{ color: FINAZ_TOKENS.negative }}>−0,80%</span></span>
        <span style={{ marginLeft: 'auto', color: AT.mute }}>MOCK · SIM-MKT-001 · 16:40 CET</span>
      </div>
    </div>
  );
}

Object.assign(window, { AnalystSpec, AnalystScreen, AT_TOKENS: AT, HeatCell, MiniSpark });
