// 结果页组件
function ResultPage({ questions, answers, onRestart, onBackToHome, userName, durationSec, onAdmin }) {
  const [showDetails, setShowDetails] = React.useState(false);

  // 计算得分
  const calcResult = () => {
    let totalScore = 0;
    let correctCount = 0;
    const details = [];

    questions.forEach((q) => {
      if (q.type === 'open') {
        details.push({ question: q, correct: null, userAnswer: answers[q.id] || '' });
        return;
      }

      let isCorrect = false;
      const userAns = answers[q.id];

      if (q.type === 'single') {
        isCorrect = userAns === q.answer;
      } else if (q.type === 'multiple') {
        const ua = Array.isArray(userAns) ? [...userAns].sort() : [];
        const ca = [...q.answer].sort();
        isCorrect = ua.length === ca.length && ua.every((v, i) => v === ca[i]);
      } else if (q.type === 'judge') {
        isCorrect = userAns === q.answer;
      } else if (q.type === 'match') {
        const ua = userAns || {};
        const ca = q.answer;
        isCorrect = Object.keys(ca).every(
          (k) => ua[k] === ca[k]
        );
      }

      if (isCorrect) {
        totalScore += q.score;
        correctCount++;
      }

      details.push({
        question: q,
        correct: isCorrect,
        userAnswer: userAns,
      });
    });

    return { totalScore, correctCount, details };
  };

  const result = React.useMemo(() => calcResult(), []);
  const { totalScore, correctCount, details } = result;
  const passed = totalScore >= 80;
  const maxScore = 100;

  const formatDuration = (secs) => {
    if (secs === undefined || secs === null) return '—';
    const h = Math.floor(secs / 3600);
    const m = Math.floor((secs % 3600) / 60);
    const s = secs % 60;
    const pad = (n) => String(n).padStart(2, '0');
    if (h > 0) return `${h} 小时 ${pad(m)} 分 ${pad(s)} 秒`;
    if (m > 0) return `${m} 分 ${pad(s)} 秒`;
    return `${s} 秒`;
  };

  const formatAnswer = (q, userAns) => {
    if (userAns === undefined || userAns === null) return '未作答';

    if (q.type === 'single') {
      const opt = q.options.find((o) => o.key === userAns);
      return opt ? `${opt.key}. ${opt.text}` : '未作答';
    }
    if (q.type === 'multiple') {
      const keys = Array.isArray(userAns) ? userAns : [];
      if (keys.length === 0) return '未作答';
      return keys
        .map((k) => {
          const opt = q.options.find((o) => o.key === k);
          return opt ? `${opt.key}. ${opt.text}` : k;
        })
        .join('、');
    }
    if (q.type === 'judge') {
      return userAns === true ? '正确' : userAns === false ? '错误' : '未作答';
    }
    if (q.type === 'match') {
      const ua = userAns || {};
      return q.brands
        .map((b) => {
          const matched = ua[b.key];
          const kw = q.keywords.find((k) => k.key === matched);
          return `${b.text} → ${kw ? kw.text : '未匹配'}`;
        })
        .join('；');
    }
    if (q.type === 'open') {
      return userAns || '未作答';
    }
    return '未作答';
  };

  const formatCorrectAnswer = (q) => {
    if (q.type === 'single') {
      const opt = q.options.find((o) => o.key === q.answer);
      return opt ? `${opt.key}. ${opt.text}` : q.answer;
    }
    if (q.type === 'multiple') {
      return q.answer
        .map((k) => {
          const opt = q.options.find((o) => o.key === k);
          return opt ? `${opt.key}. ${opt.text}` : k;
        })
        .join('、');
    }
    if (q.type === 'judge') {
      return q.answer ? '正确' : '错误';
    }
    if (q.type === 'match') {
      return q.brands
        .map((b) => {
          const kwKey = q.answer[b.key];
          const kw = q.keywords.find((k) => k.key === kwKey);
          return `${b.text} → ${kw ? kw.text : ''}`;
        })
        .join('；');
    }
    return '—';
  };

  // 环形进度
  const radius = 70;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (totalScore / maxScore) * circumference;

  return (
    <div style={resultStyles.wrapper}>
      <div style={resultStyles.container}>
        {/* 主结果卡 */}
        <div style={resultStyles.heroCard}>
          <div style={resultStyles.heroBg}></div>

          <div style={resultStyles.heroContent}>
            {/* 状态徽标 */}
            <div
              style={{
                ...resultStyles.statusBadge,
                background: passed ? '#e8f0e8' : '#f5e8e8',
                color: passed ? '#3a6a3a' : '#8a3a3a',
              }}
            >
              <svg
                viewBox="0 0 24 24"
                width="16"
                height="16"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{ marginRight: '6px' }}
              >
                {passed ? (
                  <polyline points="20 6 9 17 4 12" />
                ) : (
                  <>
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                  </>
                )}
              </svg>
              {passed ? '考核通过' : '未达合格线'}
            </div>

            {/* 环形分数 */}
            <div style={resultStyles.scoreRingWrap}>
              <svg width="180" height="180" viewBox="0 0 180 180">
                <circle
                  cx="90"
                  cy="90"
                  r={radius}
                  fill="none"
                  stroke="#e8dcc8"
                  strokeWidth="10"
                />
                <circle
                  cx="90"
                  cy="90"
                  r={radius}
                  fill="none"
                  stroke={passed ? '#6b9a6b' : '#c07a7a'}
                  strokeWidth="10"
                  strokeLinecap="round"
                  strokeDasharray={circumference}
                  strokeDashoffset={offset}
                  transform="rotate(-90 90 90)"
                  style={{ transition: 'stroke-dashoffset 1s ease-out' }}
                />
              </svg>
              <div style={resultStyles.scoreCenter}>
                <div style={resultStyles.scoreNum}>{totalScore}</div>
                <div style={resultStyles.scoreLabel}>分 / {maxScore}</div>
              </div>
            </div>

            {/* 统计信息 */}
            <div style={resultStyles.userInfoRow}>
              <div style={resultStyles.userInfoItem}>
                <span style={resultStyles.userInfoLabel}>姓名</span>
                <span style={resultStyles.userInfoValue}>{userName}</span>
              </div>
              <div style={resultStyles.userInfoItem}>
                <span style={resultStyles.userInfoLabel}>答题用时</span>
                <span style={resultStyles.userInfoValue}>{formatDuration(durationSec)}</span>
              </div>
            </div>

            {/* 统计信息 */}
            <div style={resultStyles.statsRow}>
              <div style={resultStyles.statItem}>
                <div style={resultStyles.statValue}>{correctCount}</div>
                <div style={resultStyles.statLabel}>答对题数</div>
              </div>
              <div style={resultStyles.statDivider}></div>
              <div style={resultStyles.statItem}>
                <div style={resultStyles.statValue}>{20 - correctCount}</div>
                <div style={resultStyles.statLabel}>答错题数</div>
              </div>
              <div style={resultStyles.statDivider}></div>
              <div style={resultStyles.statItem}>
                <div style={resultStyles.statValue}>80</div>
                <div style={resultStyles.statLabel}>合格分数</div>
              </div>
            </div>

            {/* 寄语 */}
            <div style={resultStyles.messageBox}>
              {passed ? (
                <>
                  恭喜你完成 Group y 品牌入职学习考核，
                  <strong style={{ color: '#8b6914' }}>欢迎加入 Group y 大家庭！</strong>
                  希望你在未来的工作中，与我们一起用食物创造连接、用空间创造温度、用服务创造记忆。
                </>
              ) : (
                <>
                  距离合格线还差 <strong style={{ color: '#b8860b' }}>{80 - totalScore} 分</strong>，
                  建议你重新学习品牌介绍内容，巩固对各品牌和理念的理解后再试一次。
                </>
              )}
            </div>
          </div>
        </div>

        {/* 操作按钮 */}
        <div style={resultStyles.actionRow}>
          <button
            style={resultStyles.secondaryBtn}
            onClick={() => setShowDetails(!showDetails)}
            className="gy-secondary-btn"
          >
            <svg
              viewBox="0 0 24 24"
              width="16"
              height="16"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              {showDetails ? (
                <polyline points="18 15 12 9 6 15" />
              ) : (
                <polyline points="6 9 12 15 18 9" />
              )}
            </svg>
            {showDetails ? '收起答题详情' : '查看答题详情'}
          </button>
          <div style={resultStyles.actionGroup}>
            <button
              style={resultStyles.ghostBtn}
              onClick={onBackToHome}
              className="gy-ghost-btn"
            >
              返回首页
            </button>
            <button
              style={resultStyles.primaryBtn}
              onClick={onRestart}
              className="gy-primary-btn"
            >
              <svg
                viewBox="0 0 24 24"
                width="16"
                height="16"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <polyline points="1 4 1 10 7 10" />
                <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" />
              </svg>
              重新答题
            </button>
          </div>
        </div>

        {/* 答题详情 */}
        {showDetails && (
          <div style={resultStyles.detailSection}>
            <div style={resultStyles.detailHeader}>
              <span style={resultStyles.detailTitle}>答题详情</span>
              <span style={resultStyles.detailSub}>
                共 {details.filter((d) => d.correct !== null).length} 道计分题
              </span>
            </div>

            <div style={resultStyles.detailList}>
              {details.map((d, i) => (
                <DetailItem
                  key={i}
                  index={i + 1}
                  detail={d}
                  formatAnswer={formatAnswer}
                  formatCorrectAnswer={formatCorrectAnswer}
                />
              ))}
            </div>
          </div>
        )}

        {/* 底部管理员入口 */}
        <div style={resultStyles.footerAdmin}>
          <button style={resultStyles.adminLink} onClick={onAdmin} className="gy-admin-link">
            管理员入口
          </button>
        </div>
      </div>
    </div>
  );
}

function DetailItem({ index, detail, formatAnswer, formatCorrectAnswer }) {
  const { question: q, correct, userAnswer } = detail;
  const [expanded, setExpanded] = React.useState(false);

  // 开放题特殊处理
  if (correct === null) {
    return (
      <div style={detailStyles.cardOpen}>
        <div style={detailStyles.cardHeader} onClick={() => setExpanded(!expanded)}>
          <div style={detailStyles.qInfo}>
            <span style={{ ...detailStyles.qNum, background: '#f0ebe0', color: '#7a6a50' }}>
              {index}
            </span>
            <span style={detailStyles.qCategory}>{q.category}</span>
          </div>
          <div style={detailStyles.openBadge}>开放题 · 不计分</div>
        </div>
        {expanded && (
          <div style={detailStyles.cardBody}>
            <div style={detailStyles.qText}>{q.question}</div>
            <div style={detailStyles.answerRow}>
              <span style={detailStyles.answerLabel}>你的回答：</span>
              <span style={detailStyles.answerText}>{userAnswer || '未作答'}</span>
            </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div
      style={{
        ...detailStyles.card,
        borderLeftColor: correct ? '#6b9a6b' : '#c07a7a',
      }}
    >
      <div style={detailStyles.cardHeader} onClick={() => setExpanded(!expanded)}>
        <div style={detailStyles.qInfo}>
          <span
            style={{
              ...detailStyles.qNum,
              background: correct ? '#e8f0e8' : '#f5e8e8',
              color: correct ? '#3a6a3a' : '#8a3a3a',
            }}
          >
            {index}
          </span>
          <span style={detailStyles.qCategory}>{q.category}</span>
          <span style={detailStyles.qScore}>{q.score} 分</span>
        </div>
        <div
          style={{
            ...detailStyles.resultTag,
            background: correct ? '#e8f0e8' : '#f5e8e8',
            color: correct ? '#3a6a3a' : '#8a3a3a',
          }}
        >
          {correct ? '答对' : '答错'}
        </div>
      </div>

      {expanded && (
        <div style={detailStyles.cardBody}>
          <div style={detailStyles.qText}>{q.question}</div>

          <div style={detailStyles.answerRow}>
            <span style={detailStyles.answerLabel}>你的回答：</span>
            <span
              style={{
                ...detailStyles.answerText,
                color: correct ? '#3a6a3a' : '#8a3a3a',
              }}
            >
              {formatAnswer(q, userAnswer)}
            </span>
          </div>

          {!correct && (
            <div style={detailStyles.answerRow}>
              <span style={detailStyles.answerLabel}>正确答案：</span>
              <span style={{ ...detailStyles.answerText, color: '#3a6a3a', fontWeight: 500 }}>
                {formatCorrectAnswer(q)}
              </span>
            </div>
          )}

          <div style={detailStyles.explanation}>
            <span style={detailStyles.explanationLabel}>解析：</span>
            {q.explanation}
          </div>
        </div>
      )}
    </div>
  );
}

const resultStyles = {
  wrapper: {
    minHeight: '100vh',
    background: '#f5efe6',
    fontFamily:
      '"Source Han Serif CN", "Noto Serif SC", "Songti SC", serif',
    padding: '40px 20px',
  },
  container: {
    maxWidth: '720px',
    margin: '0 auto',
  },
  heroCard: {
    background: '#fff',
    borderRadius: '4px',
    boxShadow:
      '0 1px 3px rgba(60, 40, 20, 0.06), 0 8px 32px rgba(60, 40, 20, 0.08)',
    position: 'relative',
    overflow: 'hidden',
    marginBottom: '24px',
  },
  heroBg: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: '120px',
    background:
      'linear-gradient(135deg, #faf3e0 0%, #f5e8d0 50%, #ece0c8 100%)',
  },
  heroContent: {
    position: 'relative',
    padding: '40px 48px 36px',
    textAlign: 'center',
  },
  statusBadge: {
    display: 'inline-flex',
    alignItems: 'center',
    padding: '6px 16px',
    borderRadius: '20px',
    fontSize: '13px',
    fontWeight: '500',
    letterSpacing: '2px',
    marginBottom: '24px',
  },
  scoreRingWrap: {
    position: 'relative',
    width: '180px',
    height: '180px',
    margin: '0 auto 28px',
  },
  scoreCenter: {
    position: 'absolute',
    inset: 0,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  scoreNum: {
    fontSize: '48px',
    fontWeight: '600',
    color: '#3d2e15',
    lineHeight: 1,
  },
  scoreLabel: {
    fontSize: '13px',
    color: '#9a8570',
    marginTop: '4px',
  },
  userInfoRow: {
    display: 'flex',
    justifyContent: 'center',
    gap: '32px',
    marginBottom: '20px',
    padding: '12px 20px',
    background: '#faf6ed',
    borderRadius: '2px',
  },
  userInfoItem: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  userInfoLabel: {
    fontSize: '12px',
    color: '#9a8570',
    letterSpacing: '1px',
  },
  userInfoValue: {
    fontSize: '14px',
    fontWeight: '600',
    color: '#3d2e15',
  },
  statsRow: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    gap: '32px',
    marginBottom: '28px',
    padding: '20px 0',
    borderTop: '1px solid #f0e8d8',
    borderBottom: '1px solid #f0e8d8',
  },
  statItem: {
    textAlign: 'center',
  },
  statValue: {
    fontSize: '24px',
    fontWeight: '600',
    color: '#5c4a2e',
    lineHeight: 1,
    marginBottom: '4px',
  },
  statLabel: {
    fontSize: '12px',
    color: '#9a8570',
    letterSpacing: '1px',
  },
  statDivider: {
    width: '1px',
    height: '32px',
    background: '#e8dcc8',
  },
  messageBox: {
    fontSize: '14px',
    color: '#5c4a2e',
    lineHeight: '1.9',
    textAlign: 'left',
    padding: '16px 20px',
    background: '#faf6ed',
    borderRadius: '2px',
    borderLeft: '3px solid #d4a853',
  },
  actionRow: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '24px',
    gap: '16px',
  },
  actionGroup: {
    display: 'flex',
    gap: '12px',
  },
  secondaryBtn: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: '6px',
    padding: '10px 18px',
    border: '1px solid #d8cfc0',
    background: '#fff',
    color: '#5c4a2e',
    borderRadius: '2px',
    cursor: 'pointer',
    fontSize: '13px',
    fontFamily: 'inherit',
    transition: 'all 0.2s',
  },
  ghostBtn: {
    padding: '10px 20px',
    border: '1px solid #d8cfc0',
    background: '#fff',
    color: '#5c4a2e',
    borderRadius: '2px',
    cursor: 'pointer',
    fontSize: '14px',
    fontFamily: 'inherit',
    transition: 'all 0.2s',
  },
  primaryBtn: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: '6px',
    padding: '10px 22px',
    border: 'none',
    background: 'linear-gradient(135deg, #8b6914, #b8860b)',
    color: '#fff',
    borderRadius: '2px',
    cursor: 'pointer',
    fontSize: '14px',
    fontWeight: '500',
    fontFamily: 'inherit',
    transition: 'all 0.2s',
    boxShadow: '0 2px 8px rgba(139, 105, 20, 0.2)',
  },
  detailSection: {
    background: '#fff',
    borderRadius: '4px',
    boxShadow: '0 2px 8px rgba(60, 40, 20, 0.06)',
    overflow: 'hidden',
  },
  detailHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'baseline',
    padding: '20px 28px',
    borderBottom: '1px solid #f0e8d8',
    background: '#faf6ed',
  },
  detailTitle: {
    fontSize: '16px',
    fontWeight: '600',
    color: '#3d2e15',
    letterSpacing: '1px',
  },
  detailSub: {
    fontSize: '12px',
    color: '#9a8570',
  },
  detailList: {
    padding: '16px 20px',
  },
  footerAdmin: {
    textAlign: 'center',
    marginTop: '24px',
  },
  adminLink: {
    background: 'none',
    border: 'none',
    color: '#a08060',
    fontSize: '12px',
    cursor: 'pointer',
    fontFamily: 'inherit',
    letterSpacing: '2px',
    opacity: 0.5,
    transition: 'opacity 0.2s',
    padding: '8px',
  },
};

const detailStyles = {
  card: {
    marginBottom: '10px',
    border: '1px solid #e8dcc8',
    borderLeftWidth: '4px',
    borderRadius: '2px',
    background: '#fff',
    cursor: 'pointer',
    transition: 'box-shadow 0.2s',
  },
  cardOpen: {
    marginBottom: '10px',
    border: '1px solid #e0d8c8',
    borderLeftWidth: '4px',
    borderLeftColor: '#c4a878',
    borderRadius: '2px',
    background: '#fdfaf0',
    cursor: 'pointer',
  },
  cardHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '12px 16px',
  },
  qInfo: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
  },
  qNum: {
    width: '28px',
    height: '28px',
    borderRadius: '50%',
    fontSize: '13px',
    fontWeight: '600',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  qCategory: {
    fontSize: '13px',
    color: '#5c4a2e',
    fontWeight: '500',
  },
  qScore: {
    fontSize: '12px',
    color: '#9a8570',
  },
  resultTag: {
    padding: '4px 10px',
    borderRadius: '2px',
    fontSize: '12px',
    fontWeight: '500',
    letterSpacing: '1px',
  },
  openBadge: {
    fontSize: '12px',
    color: '#9a8570',
  },
  cardBody: {
    padding: '0 16px 16px 54px',
    borderTop: '1px solid #f0e8d8',
    paddingTop: '12px',
  },
  qText: {
    fontSize: '14px',
    color: '#3d2e15',
    lineHeight: '1.7',
    marginBottom: '12px',
    fontWeight: '500',
  },
  answerRow: {
    display: 'flex',
    gap: '8px',
    marginBottom: '8px',
    fontSize: '13px',
    lineHeight: '1.7',
  },
  answerLabel: {
    color: '#8b7355',
    flexShrink: 0,
  },
  answerText: {
    color: '#5c4a2e',
    flex: 1,
  },
  explanation: {
    marginTop: '12px',
    padding: '10px 14px',
    background: '#faf6ed',
    borderRadius: '2px',
    fontSize: '13px',
    color: '#6b5a40',
    lineHeight: '1.7',
  },
  explanationLabel: {
    color: '#8b6914',
    fontWeight: '600',
  },
};

window.ResultPage = ResultPage;
