// =========================================================
// FBIF 资讯订阅 · Reader pane (渲染层 / 阅读层)
// Renders the full article body (RSS content:encoded), plus
// AI summary, quality-score breakdown, translate toggle,
// and source attribution / 阅读原文.
// =========================================================

// score-breakdown popover content (AI multi-dim judgment, 仿 PRD §6)
const ScoreBreakdown = ({ entry }) => {
  const b = entry.breakdown;
  const meta = window.FBIF_DATA.TIER_META[entry.source_tier];
  return (
    <div style={{ width: 280, padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <ScoreRing score={entry.quality_score} size={48} stroke={4} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 500, color: '#1F2329' }}>质量分构成</div>
          <div style={{ fontSize: 12, color: '#8F959E' }}>模型多维打分 · 代码加权</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <ScoreBar label="一手信息" value={b.info} />
        <ScoreBar label="行业重要" value={b.importance} />
        <ScoreBar label="品类相关" value={b.relevance} />
        <ScoreBar label="时效性"   value={b.timeliness} />
        <ScoreBar label="独家性"   value={b.exclusivity} />
      </div>
      <Divider style={{ margin: '12px 0' }} />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: '#646A73' }}>
        <span>信源等级</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <TierTag tier={entry.source_tier} /> {meta.label.split('·')[1].trim()}
        </span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: '#646A73', marginTop: 6 }}>
        <span>模型置信度</span>
        <span style={{ fontFamily: 'var(--font-mono)', color: '#1F2329' }}>{Math.round(entry.confidence * 100)}%</span>
      </div>
      <p style={{ fontSize: 11, color: '#BBBFC4', margin: '10px 0 0', lineHeight: '16px' }}>
        模型只输出维度分，最终分与是否精选由确定性代码决定。MVP 阶段为 mock 数据。
      </p>
    </div>
  );
};

const Popover = ({ open, onClose, children, anchorStyle }) => {
  if (!open) return null;
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
      <div style={{
        position: 'absolute', zIndex: 41, top: 'calc(100% + 6px)', right: 0,
        background: '#fff', borderRadius: 8, boxShadow: '0 4px 12px rgba(31,35,41,.08), 0 0 1px rgba(31,35,41,.12)',
        border: '1px solid #EDEFF2', ...anchorStyle,
      }}>{children}</div>
    </>
  );
};

const ActionBtn = ({ icon, label, active, activeColor = '#1456F0', onClick, title }) => {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} title={title || label}
      style={{
        height: 30, padding: label ? '0 10px' : 0, width: label ? undefined : 30,
        border: '1px solid transparent', borderRadius: 6, background: hover ? '#F2F3F5' : 'transparent',
        color: active ? activeColor : '#646A73', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13,
        display: 'inline-flex', alignItems: 'center', gap: 6, transition: 'background-color .15s, color .15s',
      }}>
      <Icon name={icon} size={16} style={active && icon === 'bookmark' ? { fill: 'currentColor' } : undefined} />
      {label}
    </button>
  );
};

const AISummary = ({ entry }) => {
  const [open, setOpen] = React.useState(true);
  // derive 3 fake key points from summary + breakdown framing
  const points = [
    entry.summary,
    entry.source_tier === 'T1' ? '来自品牌/机构官方一手发布，可直接引用。' : '权威行业媒体原创，建议结合一手源交叉验证。',
    '建议跟进方向：' + (entry.tags[0] ? (window.FBIF_DATA.TAGS.find(t => t.id === entry.tags[0])?.name || '行业趋势') : '行业趋势') + ' 的后续动态。',
  ];
  return (
    <div style={{ border: '1px solid #DEE0E3', borderRadius: 8, overflow: 'hidden', marginBottom: 24 }}>
      <div onClick={() => setOpen(o => !o)} style={{
        display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', cursor: 'pointer',
        background: '#F7F8FA', borderBottom: open ? '1px solid #EDEFF2' : 'none',
      }}>
        <span style={{ width: 22, height: 22, borderRadius: 6, background: '#EBF1FE', color: '#1456F0', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="sparkles" size={14} />
        </span>
        <span style={{ fontSize: 13, fontWeight: 500, color: '#1F2329', flex: 1 }}>AI 摘要 · 关键要点</span>
        <Tag tone="info" style={{ height: 18, fontSize: 11, lineHeight: '18px' }}>Beta</Tag>
        <Icon name={open ? 'chevron-up' : 'chevron-down'} size={15} color="#8F959E" />
      </div>
      {open && (
        <ul style={{ margin: 0, padding: '12px 16px 12px 16px', listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {points.map((p, i) => (
            <li key={i} style={{ display: 'flex', gap: 8, fontSize: 13, lineHeight: '21px', color: '#1F2329' }}>
              <span style={{ color: '#1456F0', flexShrink: 0, marginTop: 7, width: 5, height: 5, borderRadius: 9999, background: '#1456F0' }} />
              <span style={{ textWrap: 'pretty' }}>{p}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

const ReaderEmpty = () => {
  useLucide();
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 48, textAlign: 'center', color: '#8F959E', background: '#fff' }}>
      <Icon name="book-open" size={64} color="#D4D7DC" />
      <div style={{ fontSize: 15, color: '#1F2329', marginTop: 16 }}>选择一条资讯开始阅读</div>
      <div style={{ fontSize: 13, color: '#8F959E', marginTop: 6, maxWidth: 300, lineHeight: '20px' }}>
        从左侧时间线点击任意卡片，正文将在此渲染。精选流默认只展示高质量分内容。
      </div>
    </div>
  );
};

const Reader = ({ entry, onOpenOriginal, onClose, embedded = false }) => {
  useLucide();
  const [showScore, setShowScore] = React.useState(false);
  const [translated, setTranslated] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = 0; setTranslated(false); }, [entry && entry.id]);

  if (!entry) return <div style={{ flex: 1, minWidth: 0, display: 'flex' }}><ReaderEmpty /></div>;

  const meta = window.FBIF_DATA.TIER_META[entry.source_tier];
  const hasScore = entry.quality_score != null && entry.breakdown;
  const isCompiled = /^\[编译\]/.test(entry.title);

  return (
    <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>
      {/* toolbar */}
      <div style={{ height: 56, flexShrink: 0, borderBottom: '1px solid #DEE0E3', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: embedded ? '0 12px' : '0 16px', gap: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          {onClose && <Button variant="ghost" size="dense" icon="x" title="关闭（Esc）" onClick={onClose} />}
          <SourceMark short={entry.source_short} color={entry.source_color} size={22} radius={6} />
          <span style={{ fontSize: 13, color: '#1F2329', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{entry.source_name.replace(/\s*Newsroom/, '')}</span>
          {!embedded && <SourceTypeChip type={entry.source_type} />}
          {!embedded && <TierTag tier={entry.source_tier} compact />}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 2, flexShrink: 0 }}>
          {!embedded && <ActionBtn icon="languages" label={translated ? '原文' : '翻译'} active={translated} onClick={() => setTranslated(t => !t)} title="中英翻译（演示）" />}
          {!embedded && <Divider vertical style={{ height: 18, margin: '0 4px' }} />}
          <Button variant={embedded ? 'secondary' : 'primary'} size="dense" icon="external-link" onClick={() => onOpenOriginal(entry)} title="阅读原文">{embedded ? '原文' : '阅读原文'}</Button>
        </div>
      </div>

      {/* scroll body */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
        <div style={{ maxWidth: 720, margin: '0 auto', padding: embedded ? '24px 28px 64px' : '32px 40px 80px' }}>
          {/* meta chips */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
            {entry.is_featured && <Tag tone="info" dot>精选</Tag>}
            {entry.tags.map(tid => {
              const t = window.FBIF_DATA.TAGS.find(x => x.id === tid);
              return t ? (
                <span key={tid} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 22, padding: '0 8px', borderRadius: 4, background: '#F2F3F5', fontSize: 12, color: '#646A73' }}>
                  <span style={{ width: 6, height: 6, borderRadius: 9999, background: t.color }} />{t.name}
                </span>
              ) : null;
            })}
            {translated && <Tag tone="success" dot>已翻译为简体中文</Tag>}
          </div>

          {/* title */}
          <h1 style={{ fontSize: embedded ? 24 : 28, lineHeight: embedded ? '34px' : '38px', fontWeight: 600, color: '#1F2329', margin: '0 0 16px', textWrap: 'pretty' }}>
            {entry.title.replace(/^\[编译\]\s*/, '')}
          </h1>

          {/* byline + score */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, paddingBottom: 20, marginBottom: 24, borderBottom: '1px solid #EDEFF2' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
              <SourceMark short={entry.source_short} color={entry.source_color} size={36} radius={8} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14, color: '#1F2329', fontWeight: 500 }}>{entry.source_name}</div>
                <div style={{ fontSize: 12, color: '#8F959E', display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
                  <span>{fmtTime(entry.published_at)}</span>
                  <span>·</span>
                  <span>{timeAgo(entry.minsAgo)}</span>
                </div>
              </div>
            </div>
            {hasScore && <div style={{ position: 'relative', flexShrink: 0 }}>
              <button onClick={() => setShowScore(s => !s)} title="查看质量分构成"
                style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, borderRadius: 9999 }}>
                <ScoreRing score={entry.quality_score} size={56} />
              </button>
              <Popover open={showScore} onClose={() => setShowScore(false)}>
                <ScoreBreakdown entry={entry} />
              </Popover>
            </div>}
          </div>

          {/* 推荐理由 */}
          {entry.reason && (
            <div style={{ display: 'flex', gap: 10, padding: '12px 14px', background: '#F7FAFF', border: '1px solid #D6E4FD', borderRadius: 8, marginBottom: 20 }}>
              <span style={{ flexShrink: 0, color: '#1456F0', marginTop: 1 }}><Icon name="sparkles" size={16} /></span>
              <p style={{ fontSize: 14, lineHeight: '22px', color: '#0F4DD1', margin: 0, textWrap: 'pretty' }}>
                <b style={{ fontWeight: 500 }}>推荐理由 </b>{entry.reason}
              </p>
            </div>
          )}

          {/* AI summary */}
          {entry.ai_ready !== false && <AISummary entry={entry} />}

          {isCompiled && (
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '10px 12px', background: '#FFF3E5', borderRadius: 6, marginBottom: 20 }}>
              <Icon name="info" size={15} color="#B45F00" style={{ marginTop: 2 }} />
              <span style={{ fontSize: 12, color: '#B45F00', lineHeight: '18px' }}>本文为英文报道的中文编译，关键数据请以原文为准。</span>
            </div>
          )}

          {/* body — rendered RSS content */}
          <div className={'rss-body' + (translated ? ' translated' : '')} dangerouslySetInnerHTML={{ __html: entry.body }} />

          {/* source footer */}
          <div style={{ marginTop: 40, padding: '16px 18px', background: '#F7F8FA', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 12 }}>
            <SourceMark short={entry.source_short} color={entry.source_color} size={32} radius={7} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, color: '#1F2329', fontWeight: 500 }}>{entry.source_name}</div>
              <div style={{ fontSize: 12, color: '#8F959E', marginTop: 1 }}>{meta.desc}</div>
            </div>
            <Button variant="secondary" size="default" icon="external-link" onClick={() => onOpenOriginal(entry)}>阅读原文</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Reader, ScoreBreakdown, AISummary, Popover });
