/* ════════════════════════════════════════════════════════════
   AnalystBullpen — today's analysts on duty.
   Sits at top of dashboard. Three avatars, each with a beat,
   a confidence chip, and a tiny morning-note headline.
   The "editorial team" made human.
   ════════════════════════════════════════════════════════════ */

const { useState: ab_s, useEffect: ab_e } = React;

function AnalystBullpen({ market = 'us' }) {
  const lang = window.__LANG || 'zh';

  // Deterministic daily roster — same day → same team
  const day = Math.floor(Date.now() / 86400000);
  const roster = ab_pickRoster(day, lang);

  const [collapsed, setCollapsed] = ab_s(() => {
    try { return localStorage.getItem('bullpen.collapsed') === '1'; } catch (e) { return false; }
  });

  const toggle = () => {
    const v = !collapsed;
    setCollapsed(v);
    try { localStorage.setItem('bullpen.collapsed', v ? '1' : '0'); } catch (e) {}
    window.haptic?.light();
  };

  const dateLabel = new Date().toLocaleDateString(lang==='zh'?'zh-CN':'en-US', { weekday: 'short', month: 'short', day: 'numeric' });

  return (
    <section className={'abp' + (collapsed ? ' is-collapsed' : '')} aria-label={lang==='zh'?'今日值班分析师':"Today's analysts on duty"}>
      <header className="abp-mast">
        <span className="abp-eb">
          <span className="abp-dot"/>
          {lang==='zh'?'今日值班':'ON DUTY'} · {dateLabel}
        </span>
        <button className="abp-toggle" onClick={toggle} aria-expanded={!collapsed}>
          {collapsed ? (lang==='zh'?'展开':'Show') : (lang==='zh'?'收起':'Hide')}
        </button>
      </header>

      {!collapsed && (
        <ul className="abp-list">
          {roster.map((p, i) => (
            <li key={i} className="abp-card" style={{ '--seat-tint': p.tint }}>
              <div className="abp-avatar" style={{ background: p.tint }}>
                <span className="abp-initials">{p.initials}</span>
                <span className="abp-badge">{p.role}</span>
              </div>
              <div className="abp-meta">
                <div className="abp-name">
                  {p.name}
                  <span className="abp-conf" title="confidence">
                    <span className="abp-conf-bar"><span style={{ width: (p.conf*100)+'%' }}/></span>
                    {Math.round(p.conf*100)}
                  </span>
                </div>
                <div className="abp-beat">{p.beat}</div>
                <div className="abp-note">"{p.note}"</div>
              </div>
              <span className="abp-sign">— {p.sig}</span>
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}

/* ─── deterministic roster picker ─────────────────────────────── */

function ab_pickRoster(day, lang) {
  const techPool = lang === 'zh' ? [
    { initials: 'CS', name: '陈思远',  sig: 'C. Chen',    beat: '量价 / 60D 趋势', notes: ['MA20/50 在 NVDA 上发生金叉,量能放大 1.4×。','SPY RSI 进入超买,但宽度指标仍健康。','三大指数当前均线多头排列,守住短期支撑。'] },
    { initials: 'LW', name: '李文哲',  sig: 'W. Li',      beat: '波动率 / 期权流', notes: ['VIX 期限结构持续 contango,系统性风险偏低。','看涨 gamma 集中在 TSLA 250 / 260。','SKEW 指数显示下行保险溢价回落。'] },
    { initials: 'ZH', name: '张昊',    sig: 'H. Zhang',   beat: '量化因子',         notes: ['今日 momentum factor 表现优于 value 0.6%。','high-beta basket 创 5 日新高。','分散投资因子下半周率先反弹。'] },
  ] : [
    { initials: 'KM', name: 'Karen M.', sig: 'K. Murray', beat: 'Price & volume', notes: ['MA20/50 golden-crossed on NVDA, volume 1.4×.','SPY RSI hot but breadth healthy.','Indexes still in uptrend; near-term support holds.'] },
    { initials: 'JR', name: 'James R.', sig: 'J. Reilly', beat: 'Volatility / flow', notes: ['VIX term structure in contango; risk muted.','Bullish gamma stacked on TSLA 250 / 260.','SKEW softer — downside hedges cheaper.'] },
    { initials: 'SP', name: 'Sara P.',  sig: 'S. Park',   beat: 'Quant factors',  notes: ['Momentum +60bps over value today.','High-beta basket prints 5-day high.','Low-vol bouncing into the back half of week.'] },
  ];

  const aiPool = lang === 'zh' ? [
    { initials: 'F1', name: 'FELIX-A1', sig: 'Model · ver 7.4', beat: '推理模型 / 100K 样本', notes: ['上行类似 2024-03 样本群,后 5 日中位收益 +1.8%。','本周回归提示 small-cap 跑赢概率 58%。','行业轮动模型偏向 energy → tech 切换。'] },
    { initials: 'F2', name: 'FELIX-A2', sig: 'Model · ver 7.4', beat: '语义新闻流',           notes: ['财报季情绪较上季提升 +12%,Beat:Miss = 2.7:1。','央行措辞偏鸽,概率指标 0.71。','地缘风险词频回落至 60D 低位。'] },
    { initials: 'F3', name: 'FELIX-A3', sig: 'Model · ver 7.4', beat: '链上 / 资金流',         notes: ['本周稳定币净流入 +$1.4B,偏向 BTC。','机构 ETF flow 由净卖出转为净买入。','Smart-money 集中 buy AAPL 看涨期权。'] },
  ] : [
    { initials: 'F1', name: 'FELIX-A1', sig: 'Model · ver 7.4', beat: 'Inference / 100K refs', notes: ['Up-tape similar to 2024-03 cohort: +1.8% in 5d.','Small-caps win-rate this week: 58%.','Sector model rotates energy → tech.'] },
    { initials: 'F2', name: 'FELIX-A2', sig: 'Model · ver 7.4', beat: 'News semantics',        notes: ['Earnings tone +12% vs last quarter, beat:miss 2.7:1.','Fed cadence dovish, p = 0.71.','Geopolitical-risk keywords at 60D low.'] },
    { initials: 'F3', name: 'FELIX-A3', sig: 'Model · ver 7.4', beat: 'On-chain & flow',       notes: ['Stablecoin net inflows +$1.4B, BTC-leaning.','ETF flow flips net buyer this week.','Smart-money concentrated in AAPL calls.'] },
  ];

  const proPool = lang === 'zh' ? [
    { initials: 'YT', name: '杨涛',     sig: '杨涛 · 摩根方东 · 16Y', beat: '半导体 / 算力',     notes: ['NVDA 财报指引上修空间剩 8-10%。','AMD MI300 出货爬坡持续。','TSMC 4nm 利用率维持 95%+。'] },
    { initials: 'WX', name: 'Wendy 周', sig: '周文姗 · UBS · 11Y',    beat: '消费 / 出行',       notes: ['美线航司 ASM 同比 +6.4%,继续 hold。','奢侈品在中国本周回暖 +3.2%。','零售大盘库存周转改善。'] },
    { initials: 'KH', name: 'Kevin 黄', sig: 'K. Huang · Sequoia',    beat: '宏观 / 资产配置',   notes: ['全球 60/40 5Y vol 仍在均值下沿。','日股周线 RS 创新高,保持 OW。','美债期限利差 close 收敛至 −0.18%。'] },
  ] : [
    { initials: 'TY', name: 'Yang Tao',  sig: 'T. Yang · MS · 16Y',    beat: 'Semis & AI compute',  notes: ['NVDA guide raise still has 8-10% upside.','AMD MI300 ramp tracking ahead.','TSMC 4nm utilization >95%.'] },
    { initials: 'WZ', name: 'Wendy Z.',  sig: 'W. Zhou · UBS · 11Y',    beat: 'Consumer & travel',   notes: ['US airline ASM YoY +6.4% — stay long.','China luxury reads +3.2% WoW.','Retail inventory turns improving broadly.'] },
    { initials: 'KH', name: 'Kevin H.',  sig: 'K. Huang · Sequoia',    beat: 'Macro & allocation',  notes: ['Global 60/40 5Y vol still in lower half.','Japan RS at fresh high — stay OW.','UST term spread closes at -0.18%.'] },
  ];

  // Confidences seeded by day so they feel real and drift naturally
  const seed = (n) => ((day * 9301 + n * 49297) % 233280) / 233280;
  const pick = (pool, i) => {
    const p = pool[Math.floor(seed(i) * pool.length)];
    return {
      ...p,
      role: ['TECH','AI','EXPERT'][i],
      tint: ['#3a6fbf','#c08038','#3a8a55'][i],
      conf: 0.62 + seed(i + 7) * 0.30,           // 62–92%
      note: p.notes[Math.floor(seed(i + 14) * p.notes.length)],
    };
  };

  return [pick(techPool, 0), pick(aiPool, 1), pick(proPool, 2)];
}

window.AnalystBullpen = AnalystBullpen;
