/* MaiAgent Partner Portal — Training & Certification */

const TrainingPage = ({ t, lang, onNav }) => {
  const [training, setTraining] = React.useState({ ...PARTNER_STATUS.training });
  const [activeId, setActiveId] = React.useState('A1');
  const [quizMode, setQuizMode] = React.useState(false);
  const [answers, setAnswers] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [score, setScore] = React.useState(null);

  const activeModule = TRAINING_MODULES.find(m => m.id === activeId);
  const doneCount = TRAINING_MODULES.filter(m => training[m.id]).length;
  const allDone = doneCount === TRAINING_MODULES.length;
  const quizPassed = training.quizPassed;

  const markDone = (id) => {
    setTraining(prev => ({ ...prev, [id]: true }));
    const idx = TRAINING_MODULES.findIndex(m => m.id === id);
    if (idx < TRAINING_MODULES.length - 1) setActiveId(TRAINING_MODULES[idx + 1].id);
  };

  const submitQuiz = () => {
    let correct = 0;
    QUIZ_QUESTIONS.forEach(q => {
      if (answers[q.id] === q.answer) correct++;
    });
    const s = Math.round((correct / QUIZ_QUESTIONS.length) * 100);
    setScore(s);
    setSubmitted(true);
    if (s >= 80) setTraining(prev => ({ ...prev, quizPassed: true }));
  };

  const retryQuiz = () => {
    setAnswers({});
    setSubmitted(false);
    setScore(null);
  };

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-header__title">
          <div className="page-header__eyebrow">{lang === 'zh' ? '夥伴中心' : 'Partner Hub'}</div>
          <h1>{t('train.title')}</h1>
          <div className="page-header__sub">{t('train.sub')}</div>
        </div>
        <div style={{ display: 'flex', align: 'center', gap: 10 }}>
          {quizPassed
            ? <Badge tone="green" dot lg>{lang === 'zh' ? 'Certified Partner ✓' : 'Certified Partner ✓'}</Badge>
            : <div style={{ fontSize: 13, color: 'var(--mai-fg-2)', fontWeight: 600 }}>{doneCount}/{TRAINING_MODULES.length} {lang === 'zh' ? '模組完成' : 'modules done'}</div>
          }
        </div>
      </div>

      {/* Certificate banner */}
      {quizPassed && (
        <div style={{ background: 'linear-gradient(120deg, #131838 0%, #1B2150 55%, #1F4FFF 130%)', borderRadius: 16, padding: '20px 28px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 20, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: '50%', background: 'radial-gradient(circle at 70% 50%, rgba(38,194,129,0.35) 0%, transparent 60%)', pointerEvents: 'none' }} />
          <div style={{ width: 52, height: 52, borderRadius: 16, background: 'rgba(38,194,129,0.2)', display: 'grid', placeItems: 'center', flexShrink: 0, position: 'relative', zIndex: 1 }}>
            <Icon name="award" size={28} style={{ color: 'var(--mai-green-bright)' }} />
          </div>
          <div style={{ flex: 1, position: 'relative', zIndex: 1 }}>
            <div style={{ fontWeight: 800, fontSize: 18, color: 'white', letterSpacing: '-0.01em' }}>{t('train.cert.title')}</div>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>{t('train.cert.desc')}</div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0, position: 'relative', zIndex: 1 }}>
            <Btn variant="primary" icon="download">{t('train.cert.download')}</Btn>
            <Btn variant="ghost" style={{ background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)', color: 'white' }} onClick={() => onNav('deals')}>{t('train.cert.go_deals')}</Btn>
          </div>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 16, alignItems: 'start' }}>

        {/* LEFT: Module list */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {/* Track A */}
          <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid #EEF0F8', background: '#FAFBFE' }}>
              <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--mai-fg)' }}>{t('train.track_a')}</div>
              <div style={{ fontSize: 11, color: 'var(--mai-fg-3)', marginTop: 2 }}>{t('train.track_a_sub')}</div>
            </div>
            {TRAINING_MODULES.filter(m => m.track === 'A').map(m => (
              <ModuleItem key={m.id} m={m} lang={lang} active={activeId === m.id && !quizMode} done={training[m.id]} onClick={() => { setActiveId(m.id); setQuizMode(false); }} />
            ))}
          </div>

          {/* Track B */}
          <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid #EEF0F8', background: '#FAFBFE' }}>
              <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--mai-fg)' }}>{t('train.track_b')}</div>
              <div style={{ fontSize: 11, color: 'var(--mai-fg-3)', marginTop: 2 }}>{t('train.track_b_sub')}</div>
            </div>
            {TRAINING_MODULES.filter(m => m.track === 'B').map(m => (
              <ModuleItem key={m.id} m={m} lang={lang} active={activeId === m.id && !quizMode} done={training[m.id]} onClick={() => { setActiveId(m.id); setQuizMode(false); }} />
            ))}
          </div>

          {/* Quiz button */}
          <div
            onClick={() => allDone && setQuizMode(true)}
            style={{ background: allDone ? (quizPassed ? 'rgba(38,194,129,0.08)' : 'var(--mai-fg)') : '#F4F6FF', border: '1px solid ' + (allDone ? (quizPassed ? 'rgba(38,194,129,0.25)' : 'var(--mai-fg)') : 'var(--mai-border)'), borderRadius: 16, padding: '16px', cursor: allDone ? 'pointer' : 'not-allowed', opacity: allDone ? 1 : 0.6, transition: 'all 180ms' }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name={quizPassed ? 'award' : 'file-text'} size={20} style={{ color: allDone ? (quizPassed ? 'var(--mai-green-deep)' : 'var(--mai-green-bright)') : 'var(--mai-fg-3)' }} />
              <div>
                <div style={{ fontWeight: 700, fontSize: 13, color: allDone ? (quizPassed ? 'var(--mai-green-deep)' : 'white') : 'var(--mai-fg-3)' }}>{t('train.quiz.title')}</div>
                <div style={{ fontSize: 11, color: allDone ? (quizPassed ? 'var(--mai-fg-3)' : 'rgba(255,255,255,0.65)') : 'var(--mai-fg-3)', marginTop: 2 }}>
                  {quizPassed ? (lang === 'zh' ? `得分 ${training.quizScore || 90} · 已通過` : `Score ${training.quizScore || 90} · Passed`) : t('train.quiz.sub')}
                </div>
              </div>
            </div>
          </div>

          {/* Overall progress */}
          <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, padding: '12px 14px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 12, fontWeight: 600, color: 'var(--mai-fg-3)' }}>
              <span>{lang === 'zh' ? '整體進度' : 'Overall'}</span>
              <span>{doneCount}/{TRAINING_MODULES.length}</span>
            </div>
            <Progress value={(doneCount / TRAINING_MODULES.length) * 100} variant="gradient" />
          </div>
        </div>

        {/* RIGHT: Video player / Quiz */}
        <div>
          {quizMode ? (
            <QuizPanel t={t} lang={lang} answers={answers} setAnswers={setAnswers} submitted={submitted} score={score} onSubmit={submitQuiz} onRetry={retryQuiz} passed={quizPassed} onNav={onNav} />
          ) : (
            <VideoPanel t={t} lang={lang} module={activeModule} done={training[activeId]} onMarkDone={() => markDone(activeId)} />
          )}
        </div>
      </div>
    </div>
  );
};

const ModuleItem = ({ m, lang, active, done, onClick }) => (
  <div
    onClick={onClick}
    style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px', cursor: 'pointer', background: active ? '#F4F6FF' : 'white', borderLeft: active ? '3px solid var(--mai-blue)' : '3px solid transparent', transition: 'all 150ms' }}
  >
    <div style={{ width: 22, height: 22, borderRadius: 999, display: 'grid', placeItems: 'center', flexShrink: 0, background: done ? 'var(--mai-green)' : active ? 'var(--mai-fg)' : '#F1F3FA', color: done || active ? 'white' : 'var(--mai-fg-3)', fontSize: 10, fontWeight: 700 }}>
      {done ? <Icon name="check" size={12} /> : m.id}
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontWeight: 600, fontSize: 12.5, color: done ? 'var(--mai-fg-2)' : active ? 'var(--mai-fg)' : 'var(--mai-fg-2)', lineHeight: 1.3 }}>{lang === 'zh' ? m.titleZh : m.titleEn}</div>
      <div style={{ fontSize: 11, color: 'var(--mai-fg-3)', marginTop: 2 }}>{m.duration}</div>
    </div>
    {done && <Icon name="check-circle" size={14} style={{ color: 'var(--mai-green)', flexShrink: 0 }} />}
  </div>
);

const VideoPanel = ({ t, lang, module: m, done, onMarkDone }) => {
  const [playing, setPlaying] = React.useState(false);
  if (!m) return null;
  return (
    <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
      {/* Video area */}
      <div style={{ position: 'relative', background: '#0E1230', aspectRatio: '16/9' }}>
        {playing ? (
          <iframe
            style={{ width: '100%', height: '100%', border: 'none', position: 'absolute', inset: 0 }}
            src={`https://www.youtube.com/embed/${m.youtubeId}?autoplay=1&rel=0`}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
          />
        ) : (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, cursor: 'pointer' }} onClick={() => setPlaying(true)}>
            <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 50% 40%, rgba(38,194,129,0.15) 0%, transparent 60%)' }} />
            <div style={{ width: 72, height: 72, borderRadius: 999, background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(8px)', display: 'grid', placeItems: 'center', border: '2px solid rgba(255,255,255,0.25)', transition: 'transform 200ms', position: 'relative' }}>
              <Icon name="play" size={30} style={{ color: 'white', marginLeft: 4 }} />
            </div>
            <div style={{ color: 'white', fontWeight: 700, fontSize: 15, position: 'relative' }}>{t('train.watch')}</div>
            <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 12, position: 'relative' }}>{m.duration}</div>
          </div>
        )}
      </div>

      {/* Module info */}
      <div style={{ padding: '20px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--mai-fg)', letterSpacing: '-0.01em', marginBottom: 6 }}>{lang === 'zh' ? m.titleZh : m.titleEn}</div>
            <div style={{ fontSize: 13.5, color: 'var(--mai-fg-2)', lineHeight: 1.5 }}>{lang === 'zh' ? m.descZh : m.descEn}</div>
          </div>
          <div style={{ flexShrink: 0 }}>
            <Badge tone={m.track === 'A' ? 'blue' : 'violet'}>Track {m.track}</Badge>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 14, paddingTop: 16, borderTop: '1px solid #F1F3FA' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--mai-fg-3)' }}>
            <Icon name="clock" size={14} /> {m.duration}
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            {done ? (
              <Badge tone="green" dot lg>{t('train.completed')}</Badge>
            ) : (
              <Btn variant="primary" icon="check" onClick={onMarkDone}>{t('train.mark_done')}</Btn>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const QuizPanel = ({ t, lang, answers, setAnswers, submitted, score, onSubmit, onRetry, passed, onNav }) => {
  const allAnswered = QUIZ_QUESTIONS.every(q => answers[q.id] !== undefined);

  if (submitted && score >= 80) {
    return (
      <div style={{ background: 'white', border: '1px solid rgba(38,194,129,0.3)', borderRadius: 16, padding: '40px', textAlign: 'center' }}>
        <div style={{ width: 80, height: 80, borderRadius: 999, background: 'rgba(38,194,129,0.12)', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}>
          <Icon name="award" size={40} style={{ color: 'var(--mai-green-deep)' }} />
        </div>
        <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--mai-fg)', marginBottom: 8 }}>{t('train.quiz.pass')}</div>
        <div style={{ fontSize: 14, color: 'var(--mai-fg-3)', marginBottom: 20 }}>{t('train.quiz.score')}: <strong style={{ color: 'var(--mai-green-deep)', fontSize: 20 }}>{score}</strong> / 100 &nbsp;·&nbsp; {t('train.quiz.pass_score')}</div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <Btn variant="primary" icon="download">{t('train.cert.download')}</Btn>
          <Btn variant="ghost" icon="shield" onClick={() => onNav('deals')}>{t('train.cert.go_deals')}</Btn>
        </div>
      </div>
    );
  }

  if (submitted && score < 80) {
    return (
      <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, padding: '40px', textAlign: 'center' }}>
        <div style={{ width: 80, height: 80, borderRadius: 999, background: '#FEF2F2', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}>
          <Icon name="x-circle" size={40} style={{ color: '#EF4444' }} />
        </div>
        <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--mai-fg)', marginBottom: 8 }}>{t('train.quiz.fail')}</div>
        <div style={{ fontSize: 14, color: 'var(--mai-fg-3)', marginBottom: 20 }}>{t('train.quiz.score')}: <strong style={{ color: '#EF4444', fontSize: 20 }}>{score}</strong> / 100 &nbsp;·&nbsp; {t('train.quiz.pass_score')}</div>
        <Btn variant="primary" icon="refresh-cw" onClick={onRetry}>{t('train.quiz.retry')}</Btn>
      </div>
    );
  }

  return (
    <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
      <div style={{ padding: '20px 24px', borderBottom: '1px solid #EEF0F8', background: 'linear-gradient(135deg, #131838, #1B2150)' }}>
        <div style={{ fontSize: 18, fontWeight: 800, color: 'white', marginBottom: 4 }}>{t('train.quiz.title')}</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>{t('train.quiz.sub')}</div>
      </div>
      <div style={{ padding: '24px', display: 'flex', flexDirection: 'column', gap: 24, maxHeight: '60vh', overflowY: 'auto' }}>
        {QUIZ_QUESTIONS.map((q, qi) => (
          <div key={q.id}>
            <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--mai-fg)', marginBottom: 10, lineHeight: 1.4 }}>
              <span style={{ color: 'var(--mai-fg-3)', marginRight: 6 }}>Q{qi + 1}.</span>
              {lang === 'zh' ? q.qZh : q.qEn}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {(lang === 'zh' ? q.optsZh : q.optsEn).map((opt, oi) => (
                <div
                  key={oi}
                  onClick={() => setAnswers(prev => ({ ...prev, [q.id]: oi }))}
                  style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 10, border: '1px solid ' + (answers[q.id] === oi ? 'var(--mai-blue)' : 'var(--mai-border)'), background: answers[q.id] === oi ? '#EEF2FF' : 'white', cursor: 'pointer', transition: 'all 150ms', fontSize: 13.5 }}
                >
                  <div style={{ width: 20, height: 20, borderRadius: 999, border: '2px solid ' + (answers[q.id] === oi ? 'var(--mai-blue)' : '#D1D5DB'), display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                    {answers[q.id] === oi && <div style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--mai-blue)' }} />}
                  </div>
                  {opt}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: '16px 24px', borderTop: '1px solid #EEF0F8', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 12.5, color: 'var(--mai-fg-3)' }}>{Object.keys(answers).length} / {QUIZ_QUESTIONS.length} {lang === 'zh' ? '題已作答' : 'answered'}</div>
        <Btn variant="primary" onClick={onSubmit} disabled={!allAnswered}>{t('train.quiz.submit')}</Btn>
      </div>
    </div>
  );
};

window.TrainingPage = TrainingPage;
