/* ════════════════════════════════════════════════════════════
   Notification Center — top-right bell + dropdown panel
   ════════════════════════════════════════════════════════════ */

const { useState: nC_s, useEffect: nC_e, useRef: nC_r } = React;

function buildNotifications() {
  const lang = window.__LANG || 'zh';
  const recs = (window.MOCK_RECS || []).slice(0, 6);
  const now = Date.now();
  return [
    { id: 'sig1', kind: 'signed', ts: now - 18 * 60000, sym: recs[0]?.symbol || 'NVDA',
      ttl: lang === 'zh' ? '承诺书已签署' : 'Contract acknowledged',
      msg: lang === 'zh' ? '已记入 §III 履约条款 · 下次查看将出现回顾区块' : 'Recorded under §III · followup will appear next visit' },
    { id: 'fresh', kind: 'fresh', ts: now - 7 * 60000, sym: null,
      ttl: lang === 'zh' ? '数据已更新' : 'Data refreshed',
      msg: lang === 'zh' ? '美股 / A股 三源融合分已重算 · 7 分钟前' : 'US & CN fusion scores recomputed · 7m ago' },
    { id: 'sl', kind: 'alert', ts: now - 42 * 60000, sym: recs[1]?.symbol || 'TSLA',
      ttl: lang === 'zh' ? '触发止损接近' : 'Stop-loss proximity',
      msg: lang === 'zh' ? `${recs[1]?.symbol || 'TSLA'} 距止损位仅 1.2% · 考虑止盈或离场` : `${recs[1]?.symbol || 'TSLA'} within 1.2% of stop · consider exit` },
    { id: 'circuit', kind: 'system', ts: now - 3 * 3600000, sym: null,
      ttl: lang === 'zh' ? 'MA Cross 策略降权' : 'MA Cross strategy degraded',
      msg: lang === 'zh' ? '30 天胜率跌至 41% · 自动降至 0.7 权重' : '30d win rate 41% · auto-weighted to 0.7' },
    { id: 'recap', kind: 'recap', ts: now - 26 * 3600000, sym: null,
      ttl: lang === 'zh' ? '昨日推荐成绩' : 'Yesterday\'s scorecard',
      msg: lang === 'zh' ? '4 / 6 击中目标 · 最佳 +5.8%(NVDA)· 最差 -1.4%(TSLA)' : '4/6 hit target · best +5.8% (NVDA) · worst -1.4% (TSLA)' },
    { id: 'opp', kind: 'opp', ts: now - 51 * 3600000, sym: recs[2]?.symbol || '600519.SH',
      ttl: lang === 'zh' ? '反方分析师警示' : 'Opposite analyst flag',
      msg: lang === 'zh' ? `${recs[2]?.symbol || '600519.SH'} 镜像评分 38/100 · 估值与外部专家分歧大` : `${recs[2]?.symbol || '600519.SH'} mirror score 38 · valuation diverges` },
  ];
}

function relTime(ms) {
  const lang = window.__LANG || 'zh';
  const m = Math.floor((Date.now() - ms) / 60000);
  if (m < 1) return lang === 'zh' ? '刚刚' : 'just now';
  if (m < 60) return lang === 'zh' ? `${m} 分钟前` : `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return lang === 'zh' ? `${h} 小时前` : `${h}h ago`;
  const d = Math.floor(h / 24);
  return lang === 'zh' ? `${d} 天前` : `${d}d ago`;
}

const KIND_MARK = {
  signed:  { glyph: '§', cls: 'k-signed' },
  fresh:   { glyph: '◉', cls: 'k-fresh' },
  alert:   { glyph: '!', cls: 'k-alert' },
  system:  { glyph: '※', cls: 'k-system' },
  recap:   { glyph: '✓', cls: 'k-recap' },
  opp:     { glyph: '⇄', cls: 'k-opp' },
};

function NotificationBell({ onOpen, count }) {
  return (
    <button className="notif-bell" onClick={onOpen} aria-label="Notifications">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/>
        <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>
      </svg>
      {count > 0 && <span className="notif-dot" aria-label={`${count} unread`}>{count > 9 ? '9+' : count}</span>}
    </button>
  );
}

function NotificationCenter({ open, onClose, onOpenStock }) {
  const items = nC_s(() => buildNotifications())[0];
  const lang = window.__LANG || 'zh';
  if (!open) return null;
  return (
    <>
      <div className="notif-veil" onClick={onClose} />
      <aside className="notif-panel" role="dialog" aria-label="Notifications">
        <header className="notif-hdr">
          <div className="notif-ttl">
            <span className="notif-kicker">{lang === 'zh' ? '通知中心' : 'NOTIFICATIONS'}</span>
            <span className="notif-meta">{items.length} {lang === 'zh' ? '条 · 全部已读' : '· all read'}</span>
          </div>
          <button className="notif-close" onClick={onClose} aria-label="Close">✕</button>
        </header>
        <div className="notif-list">
          {items.map(n => {
            const k = KIND_MARK[n.kind] || KIND_MARK.system;
            return (
              <button key={n.id} className="notif-row"
                      onClick={() => { if (n.sym && onOpenStock) onOpenStock(n.sym); onClose(); }}>
                <div className={'notif-mark ' + k.cls}>{k.glyph}</div>
                <div className="notif-body">
                  <div className="notif-row-top">
                    <span className="notif-row-ttl">{n.ttl}</span>
                    {n.sym && <span className="notif-row-sym">{n.sym}</span>}
                  </div>
                  <div className="notif-row-msg">{n.msg}</div>
                  <div className="notif-row-time">{relTime(n.ts)}</div>
                </div>
              </button>
            );
          })}
        </div>
        <footer className="notif-foot">
          <span>{lang === 'zh' ? '通道:' : 'channels:'}</span>
          <span className="ch on"><span className="d"/> PWA</span>
          <span className="ch on"><span className="d"/> macOS</span>
          <span className="ch on"><span className="d"/> statusLine</span>
        </footer>
      </aside>
    </>
  );
}

window.NotificationBell = NotificationBell;
window.NotificationCenter = NotificationCenter;
window.buildNotifications = buildNotifications;
