// 知乎 — question detail page. Reads runtime data: getQuestion(qid) +
// getAnswers(qid) (see app/data-runtime.jsx). Author rows are clickable and
// route up to the parent screen via onAuthorTap so the phone state machine
// can swap in the AuthorProfile screen.

const Q_BG       = '#0E0F12';
const Q_CARD     = '#16181D';
const Q_TEXT     = '#EDEEF0';
const Q_MUTED    = '#7A8089';
const Q_DIM      = '#5A5F66';
const Q_DIVIDER  = '#1B1D22';
const Q_BLUE     = '#1772F6';
const Q_BLUE_SOFT= '#1B3556';

function QuestionDetail({ qid, onBack, onAuthorTap }) {
  const QUESTION = getQuestion(qid);
  const ANSWERS_LIST = getAnswers(qid);
  const scrollRef = React.useRef(null);
  const authorRowRefs = React.useRef({});
  const [showComments, setShowComments] = React.useState(null);
  const [activeIdx, setActiveIdx] = React.useState(-1);

  React.useEffect(() => {
    setActiveIdx(-1);
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [qid]);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => {
      const containerTop = el.getBoundingClientRect().top;
      let idx = -1;
      ANSWERS_LIST.forEach((a, i) => {
        const ref = authorRowRefs.current[a.id];
        if (!ref) return;
        const top = ref.getBoundingClientRect().top - containerTop;
        if (top < 0) idx = i;
      });
      setActiveIdx(idx);
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, [qid]);

  if (!QUESTION) {
    return (
      <div style={{ position: 'absolute', inset: 0, background: Q_BG, color: Q_TEXT,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12 }}>
        未找到该问题 ({qid})
      </div>
    );
  }

  return (
    <div style={{
      position: 'absolute', inset: 0, background: Q_BG,
      color: Q_TEXT, display: 'flex', flexDirection: 'column',
      fontFamily: '"PingFang SC", "Noto Sans SC", -apple-system, system-ui',
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '4px 12px 6px', flexShrink: 0,
      }}>
        <div onClick={onBack} style={{
          fontSize: 18, color: Q_TEXT, cursor: 'pointer',
          width: 16, height: 22, display: 'flex',
          alignItems: 'center', justifyContent: 'center',
        }}>‹</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, color: Q_TEXT }}>
          <span style={{ cursor: 'pointer' }}>👥 邀请回答</span>
          <span style={{ cursor: 'pointer' }}>✎ 写回答</span>
          <span style={{ cursor: 'pointer', fontSize: 14 }}>⌕</span>
        </div>
      </div>

      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        paddingBottom: 56,
      }}>
        <div style={{ padding: '4px 12px 6px' }}>
          <div style={{
            display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8,
          }}>
            <h1 style={{
              margin: 0, fontSize: 13, fontWeight: 700,
              color: Q_TEXT, lineHeight: 1.35, flex: 1,
            }}>{QUESTION.title}</h1>
            <div style={{
              width: 18, height: 18, borderRadius: 9,
              background: Q_CARD, color: Q_MUTED, fontSize: 9,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>⌄</div>
          </div>
          <div style={{ fontSize: 9, color: Q_MUTED, marginTop: 3 }}>
            知乎 · {QUESTION.totalAnswers} 个回答 · {QUESTION.followers.toLocaleString()} 个关注 ›
          </div>
        </div>

        {ANSWERS_LIST.length === 0 ? (
          <div style={{ padding: '40px 20px', textAlign: 'center', color: Q_MUTED, fontSize: 11 }}>
            暂无回答
          </div>
        ) : (
          ANSWERS_LIST.map((a, idx) => {
            const persona = getPersona(a.authorId);
            return (
              <AnswerCard key={a.id} answer={a} persona={persona}
                last={idx === ANSWERS_LIST.length - 1}
                isTopAnswer={idx === 0}
                authorRef={(el) => { authorRowRefs.current[a.id] = el; }}
                onCommentTap={() => setShowComments(a.id)}
                onAuthorTap={() => onAuthorTap && onAuthorTap(a.authorId)}/>
            );
          })
        )}
      </div>

      {activeIdx >= 0 && (
        <StickyBottomBar answer={ANSWERS_LIST[activeIdx]}
          persona={getPersona(ANSWERS_LIST[activeIdx].authorId)}
          onCommentTap={() => setShowComments(ANSWERS_LIST[activeIdx].id)}
          onAuthorTap={() => onAuthorTap && onAuthorTap(ANSWERS_LIST[activeIdx].authorId)}/>
      )}

      {showComments && (
        <CommentsSheet answer={ANSWERS_LIST.find(a => a.id === showComments)}
          persona={getPersona(ANSWERS_LIST.find(a => a.id === showComments)?.authorId)}
          onClose={() => setShowComments(null)}/>
      )}
    </div>
  );
}

// ─── Author row ──────────────────────────────────────────────────────
function AuthorRow({ persona, onAuthorTap, showFollow = true, showShare = true, isMirror = false }) {
  if (!persona) {
    return (
      <div style={{ padding: '8px 14px', fontSize: 10, color: Q_MUTED }}>
        匿名用户
      </div>
    );
  }
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start',
      padding: '7px 12px 3px',
    }}>
      <div onClick={onAuthorTap} style={{ cursor: 'pointer' }}>
        <AuthorAvatar persona={persona} size={22}/>
      </div>
      <div onClick={onAuthorTap} style={{
        flex: 1, marginLeft: 7, minWidth: 0, cursor: 'pointer',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 3,
          fontSize: 10, color: Q_TEXT, fontWeight: 500,
        }}>
          <span>{persona.name}</span>
          {persona.credential === 'verified' && <CredentialBadge kind="v"/>}
          {persona.credential === 'kol' && <CredentialBadge kind="kol"/>}
          {persona.credential === 'expert' && persona.badges?.length > 0 && <CredentialBadge kind="col"/>}
          {isMirror && <MirrorBadge/>}
        </div>
        {(persona.credential === 'verified' && persona.credentialText) ? (
          <div style={{ fontSize: 8.5, color: Q_MUTED, marginTop: 1.5, lineHeight: 1.4 }}>
            {persona.credentialText}
          </div>
        ) : persona.bio ? (
          <div style={{
            fontSize: 8.5, color: Q_MUTED, marginTop: 1.5, lineHeight: 1.4,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {persona.bio}
          </div>
        ) : null}
      </div>
      {showFollow && (
        <div style={{
          padding: '2px 9px', borderRadius: 11,
          background: Q_BLUE_SOFT, color: Q_BLUE,
          fontSize: 9, fontWeight: 500, cursor: 'pointer',
          flexShrink: 0, alignSelf: 'flex-start', marginTop: 2,
        }}>+ 关注</div>
      )}
      {showShare && (
        <div style={{
          marginLeft: 7, color: Q_MUTED, fontSize: 12, alignSelf: 'flex-start',
          marginTop: 2, cursor: 'pointer',
        }}>↗</div>
      )}
    </div>
  );
}

function CredentialBadge({ kind }) {
  const map = {
    v:   { bg: '#1A3E5C', color: '#5BB0FF', text: '✓' },
    kol: { bg: '#3F2A1A', color: '#E8B47A', text: '★' },
    col: { bg: '#3F2A1A', color: '#E8B47A', text: '专' },
  };
  const m = map[kind];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 11, height: 11, borderRadius: '50%',
      background: m.bg, color: m.color, fontSize: 7, fontWeight: 700,
      lineHeight: 1,
    }}>{m.text}</span>
  );
}

// 镜像答案标识 — 名字后面的红色"镜像"方框
function MirrorBadge() {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      padding: '0 4px', height: 12, marginLeft: 2,
      border: '1px solid #F0354B',
      borderRadius: 2,
      color: '#F0354B', fontSize: 8, fontWeight: 700,
      letterSpacing: 0.5, lineHeight: 1,
    }}>镜像</span>
  );
}

// ─── Answer card ─────────────────────────────────────────────────────
// realtimeReply (镜像 tour 末段): 答主点了"现在去更新"以后, LLM 生成的"二次作答"
// 文本. 用户反馈"应该出现在评估卡片下方", 不是作为独立卡片插在 AnswerCard 后面.
// 所以这里把它嵌进 EvalPanel 跟 paragraphs 之间, 用一个"答主二次作答" header 区分.
function AnswerCard({ answer, persona, last, onCommentTap, onAuthorTap, authorRef, isTopAnswer, isMirror = false, onSourceTap, onLike, realtimeReply }) {
  // Split body into paragraphs on \n\n boundaries so blank lines render.
  const paragraphs = answer.body.split(/\n+/);
  // Like / star reactions — once clicked, stay highlighted, not clickable again.
  const [liked, setLiked] = React.useState(false);
  const [starred, setStarred] = React.useState(false);
  // 点赞 emit (用于 tour: 点赞 → 触发右屏唤醒序列). 只 emit 一次.
  // 把完整答案信息 + persona 透出, tour 后期 LLM 用做生成上下文 + 定位插入点.
  const handleLike = () => {
    if (liked) return;
    setLiked(true);
    if (onLike) onLike({
      answerId: answer.id,
      authorId: answer.authorId,
      persona,
      answer,    // 完整答案 (body / qid / voteUp / 等), LLM 当上下文用
    });
  };
  return (
    <div data-author-id={answer.authorId} style={{
      borderBottom: !last ? `6px solid #07080A` : 'none',
      paddingBottom: 6,
    }}>
      <div ref={authorRef}>
        <AuthorRow persona={persona} onAuthorTap={onAuthorTap} isMirror={isMirror}/>
      </div>

      <div style={{
        padding: '0 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontSize: 8.5, color: Q_MUTED, marginBottom: 5,
      }}>
        <span>{answer.voteUp.toLocaleString()} 人赞同了该回答 ›</span>
        {answer.listened != null && (
          <span style={{ color: Q_BLUE }}>🎧 {answer.listened} 人听过</span>
        )}
      </div>

      {/* 评级面板 — 镜像答案专属. 显示 4 个维度 + 原帖链接 + AI 推荐理由. */}
      {isMirror && (() => {
        const sourceQid = answer.qid || answer.id.split('-')[0];
        const sourceTitle = typeof getQuestion === 'function' ? getQuestion(sourceQid)?.title : null;
        return (
          <EvalPanel
            answer={{
              ...answer,
              keywords: answer.keywords || (typeof getKeywords === 'function' ? getKeywords(answer.id) : []),
            }}
            persona={persona}
            topicAvgVotes={typeof getTopicAvg === 'function' ? getTopicAvg(sourceQid) : 1}
            sourceQuestion={sourceTitle}
            onSourceTap={onSourceTap ? () => onSourceTap(sourceQid) : null}
            recommendation={answer.recommendation}/>
        );
      })()}

      {/* 答主二次作答 — 评估卡片下方, 原回答正文上方. 用户专门要求放在这里. */}
      {realtimeReply && realtimeReply.body && (
        <RealtimeReplyInline reply={realtimeReply}/>
      )}

      <div style={{ padding: '8px 12px 0' }}>
        {/* 如果有 realtime reply, 给原回答 body 加一个"以下为原回答" 小灰字标签, 让用户清楚区分新旧 */}
        {realtimeReply && realtimeReply.body && (
          <div style={{
            fontSize: 9, color: Q_DIM, marginBottom: 6,
            letterSpacing: 0.5,
          }}>— 以下为答主原回答 —</div>
        )}
        {paragraphs.map((p, i) => (
          <p key={i} style={{
            margin: i === 0 ? 0 : '6px 0 0',
            fontSize: 10.5, color: Q_TEXT, lineHeight: 1.65,
          }}>{renderInlineEmphasis(p)}</p>
        ))}
      </div>

      {answer.images && answer.images.length > 0 && (
        <div style={{ padding: '8px 12px 0', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {answer.images.map((src, i) => (
            <img key={i} src={imageUrl(src, 600, 400)}
              alt="" loading="lazy"
              style={{
                width: '100%', maxHeight: 180, borderRadius: 4,
                objectFit: 'cover', display: 'block',
              }}/>
          ))}
        </div>
      )}

      <div style={{
        padding: '7px 12px 0', fontSize: 8.5, color: Q_DIM,
      }}>
        发布于 {answer.publishDate}{persona?.region ? ` · 来自${persona.region}` : ''}
      </div>

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '5px 12px 8px',
      }}>
        <div style={{
          padding: '3px 9px', borderRadius: 12, background: Q_CARD,
          fontSize: 8.5, color: Q_MUTED,
        }}>留下你的声音</div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <ReactIcon kind="up"   count={answer.voteUp + (liked ? 1 : 0)}
            active={liked}   onClick={handleLike}/>
          <ReactIcon kind="down"/>
          <ReactIcon kind="star" count={answer.stars + (starred ? 1 : 0)}
            active={starred} onClick={() => setStarred(true)}/>
          <ReactIcon kind="comment" count={answer.commentCount} onClick={onCommentTap}/>
          <span style={{ color: Q_MUTED, fontSize: 11 }}>⋮</span>
        </div>
      </div>
    </div>
  );
}

// ─── 答主二次作答 inline block (放在 EvalPanel 下方, 原 body 上方) ─────────
// reply = { body, ts, author }
// 不要写"答主真人回复 · 刚刚 · 答主名" 这种像独立卡片的 header — 因为这一段
// 现在是同一个答主卡片的一部分, 不需要重复署名. 只一行 caption + body.
function RealtimeReplyInline({ reply }) {
  return (
    <div style={{
      margin: '8px 12px 0',
      borderRadius: 8,
      overflow: 'hidden',
      border: '1px solid #1772F6',
      background: 'rgba(23, 114, 246, 0.07)',
      animation: 'realtime-inline-pop 540ms cubic-bezier(0.22, 1.4, 0.4, 1)',
    }}>
      <div style={{
        padding: '6px 10px',
        background: 'linear-gradient(135deg, rgba(23, 114, 246, 0.95) 0%, rgba(8, 88, 192, 0.95) 100%)',
        color: '#fff',
        fontSize: 10, fontWeight: 600, letterSpacing: 0.5,
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <span style={{ fontSize: 11 }}>⚡</span>
        <span>答主刚刚 (在你提问后) 二次作答</span>
      </div>
      <div style={{
        padding: '8px 12px 10px',
        fontSize: 10.5, color: Q_TEXT, lineHeight: 1.65,
        whiteSpace: 'pre-wrap',
      }}>{reply.body}</div>
      <style>{`
        @keyframes realtime-inline-pop {
          0%   { opacity: 0; transform: translateY(10px) scale(0.98); }
          100% { opacity: 1; transform: translateY(0) scale(1); }
        }
      `}</style>
    </div>
  );
}

// Render **bold** segments inline.
function renderInlineEmphasis(text) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((part, i) => {
    if (part.startsWith('**') && part.endsWith('**')) {
      return <strong key={i} style={{ fontWeight: 700, color: '#fff' }}>{part.slice(2, -2)}</strong>;
    }
    return <React.Fragment key={i}>{part}</React.Fragment>;
  });
}

function ReactIcon({ kind, count, onClick, active }) {
  // Filled glyph + blue color when `active` is true. When active, the icon
  // becomes non-interactive (cursor + click guarded by the parent passing
  // a no-op handler).
  const glyphMap = active
    ? { up: '▲', down: '▼', star: '★', comment: '●' }
    : { up: '△', down: '▽', star: '☆', comment: '◌' };
  const color = active ? Q_BLUE : Q_MUTED;
  const countColor = active ? Q_BLUE : Q_MUTED;
  return (
    <div onClick={active ? undefined : onClick} style={{
      position: 'relative',
      cursor: active ? 'default' : (onClick ? 'pointer' : 'default'),
      color, fontSize: 12, padding: '2px 4px',
      transition: 'color 0.15s',
    }}>
      <span>{glyphMap[kind]}</span>
      {count != null && (
        <span style={{
          position: 'absolute', top: -2, right: -10,
          fontSize: 7.5, color: countColor,
          fontFamily: '"DIN Alternate", system-ui',
          transition: 'color 0.15s',
        }}>{count.toLocaleString()}</span>
      )}
    </div>
  );
}

// ─── Sticky bottom bar ───────────────────────────────────────────────
function StickyBottomBar({ answer, persona, onCommentTap, onAuthorTap }) {
  if (!persona) return null;
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      background: Q_BG, borderTop: `1px solid ${Q_DIVIDER}`,
      padding: '6px 10px 18px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    }}>
      <div onClick={onAuthorTap} style={{ display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer' }}>
        <AuthorAvatar persona={persona} size={18}/>
        <span style={{ fontSize: 9, color: Q_TEXT }}>{persona.name}</span>
        <span style={{ fontSize: 9, color: Q_BLUE, cursor: 'pointer' }}>+ 关注</span>
      </div>
      <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
        <ReactIcon kind="up" count={answer.voteUp}/>
        <ReactIcon kind="down"/>
        <ReactIcon kind="star" count={answer.stars}/>
        <ReactIcon kind="comment" count={answer.commentCount} onClick={onCommentTap}/>
        <span style={{ color: Q_MUTED, fontSize: 12 }}>⋮</span>
      </div>
    </div>
  );
}

// ─── Comments sheet ──────────────────────────────────────────────────
function CommentsSheet({ answer, persona, onClose }) {
  if (!answer || !persona) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)',
      zIndex: 10, display: 'flex', flexDirection: 'column',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        marginTop: 60, flex: 1, background: Q_BG,
        borderRadius: '14px 14px 0 0', display: 'flex', flexDirection: 'column',
        boxShadow: '0 -10px 24px rgba(0,0,0,0.4)',
      }}>
        <div style={{
          padding: '10px 14px 4px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          borderBottom: `1px solid ${Q_DIVIDER}`,
        }}>
          <div style={{ fontSize: 10, color: Q_TEXT }}>
            评论
          </div>
          <div onClick={onClose} style={{
            width: 18, height: 18, borderRadius: 9, background: Q_CARD,
            color: Q_MUTED, fontSize: 10, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>✕</div>
        </div>

        <div style={{
          padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 8,
          borderBottom: `1px solid ${Q_DIVIDER}`,
        }}>
          <AuthorAvatar persona={persona} size={26}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, color: Q_TEXT, fontWeight: 500 }}>
              {persona.name} <span style={{ fontSize: 8, padding: '0 3px', border: `1px solid ${Q_MUTED}`, color: Q_MUTED, marginLeft: 4 }}>作者</span>
            </div>
            <div style={{ fontSize: 9, color: Q_MUTED, marginTop: 2 }}>{persona.bio}</div>
          </div>
          <div style={{ padding: '3px 10px', borderRadius: 11, background: Q_BLUE_SOFT, color: Q_BLUE, fontSize: 10 }}>+ 关注</div>
        </div>

        <div style={{
          padding: '8px 14px', fontSize: 11,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <span style={{ color: Q_TEXT, fontWeight: 600 }}>评论 {answer.commentCount}</span>
          <div style={{
            padding: '2px 10px', borderRadius: 10,
            background: Q_CARD, color: Q_TEXT, fontSize: 10,
          }}>默认</div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '0 14px 60px' }}>
          <div style={{ padding: '20px 0', textAlign: 'center', color: Q_MUTED, fontSize: 11 }}>
            暂无更多评论
          </div>
        </div>

        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          background: Q_BG, borderTop: `1px solid ${Q_DIVIDER}`,
          padding: '8px 14px 18px', display: 'flex', alignItems: 'center', gap: 8,
        }}>
          {typeof UserAvatar === 'function' && <UserAvatar size={22}/>}
          <div style={{
            flex: 1, height: 26, borderRadius: 13, background: Q_CARD,
            padding: '0 12px', display: 'flex', alignItems: 'center',
            justifyContent: 'space-between', fontSize: 10, color: Q_MUTED,
          }}>
            <span>理性发言，友善互动</span>
            <span style={{ fontSize: 12 }}>😯</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { QuestionDetail, AnswerCard, AuthorRow, MirrorBadge });
