// quiz.jsx — 가설 성향 자기보고 (5축 · 22유형 훅, 코드 채점, AI 0)
// 5축: 충동↔분석 / 고위험↔안전 / 외부자극↔동기뚜렷 / 추종↔독자 / 조급↔여유
const QC = window.KEITTA_COLORS;

// 각 보기에 축 성향 태그. 결과는 태그 집계로 성향 그룹 판별.
const QUIZ = [
  { q: '관심 종목이 하루 +15% 급등. 관련 뉴스는 아직 없어요. 나는?',
    a: [ ['일단 조금이라도 산다', 'impulse'], ['이유를 찾을 때까지 관망', 'analyze'], ['오른 건 언젠가 떨어진다, 관심 끈다', 'safe'] ] },
  { q: '투자를 결정할 때 가장 크게 작용하는 건?',
    a: [ ['커뮤니티·분위기', 'external'], ['내 원칙·체크리스트', 'independent'], ['전문가·뉴스', 'follow'] ] },
  { q: '괜찮아 보이는 기회가 왔어요. 나는?',
    a: [ ['늦기 전에 지금 들어간다', 'hasty'], ['며칠 지켜보고 판단한다', 'patient'], ['비중을 작게 시험 삼아', 'safe'] ] },
  { q: '한 종목에 얼마나 담을 수 있나요?',
    a: [ ['확신 서면 크게 간다', 'risk'], ['정해둔 비중 안에서만', 'safe'], ['상황 보며 조절한다', 'analyze'] ] },
  { q: '손실이 났을 때 나는?',
    a: [ ['빨리 만회할 종목을 찾는다', 'hasty'], ['왜 틀렸는지 기록한다', 'analyze'], ['한동안 거래를 쉰다', 'patient'] ] },
];

// 성향 그룹(가설) — 22유형 아님. 자기보고 기반 4그룹.
const GROUPS = [
  { keys: ['impulse','hasty','external','follow','risk'], emoji: '🌊', name: '직감·속도형',
    desc: '기회에 빠르게 반응하는 성향이 보여요. 속도는 강점이지만, "왜"를 한 줄 남기면 반응이 판단이 됩니다.' },
  { keys: ['safe','patient'], emoji: '🛡️', name: '신중·보존형',
    desc: '잃지 않으려는 감각이 앞서는 성향이에요. 그 신중함이 때로 좋은 기회를 지나치게 하기도 해요.' },
  { keys: ['risk','independent'], emoji: '🧭', name: '확신·독자형',
    desc: '자기 기준으로 밀어붙이는 힘이 보여요. 반대 시나리오를 함께 적으면 그 힘이 더 단단해집니다.' },
  { keys: ['analyze','independent','patient'], emoji: '⚖️', name: '분석·균형형',
    desc: '근거와 감정을 분리하려는 성향이에요. 판단을 기록으로 남길수록 이 성향은 더 또렷해져요.' },
];

function Quiz() {
  const { Section, SectionLabel } = window.LandingSections1;
  const [step, setStep] = React.useState(0);
  const [tags, setTags] = React.useState([]);
  const [sel, setSel] = React.useState(null);
  const accent = QC.body;

  const choose = (i) => setSel(i);
  const next = () => {
    if (sel == null) return;
    setTags(t => [...t, QUIZ[qi].a[sel][1]]);
    setSel(null);
    setStep(s => s + 1);
  };
  const restart = () => { setTags([]); setSel(null); setStep(0); };

  // 그룹 판별: 태그가 각 그룹 keys에 몇 개 걸리는지
  const scores = GROUPS.map(g => tags.filter(t => g.keys.includes(t)).length);
  const group = GROUPS[scores.indexOf(Math.max(...scores))] || GROUPS[3];
  const qi = step - 1;

  const card = { background:'#FFFFFF', border:'1px solid rgba(124,92,252,0.16)', borderRadius:20, padding:'32px 32px', boxShadow:'0 20px 50px rgba(124,92,252,0.10)', maxWidth:600, margin:'0 auto' };

  return (
    <Section bg="#FFFFFF" id="quiz">
      <div style={{ textAlign:'center', marginBottom:30 }}>
        <SectionLabel>QUIZ</SectionLabel>
        <h2 style={{ fontFamily:"'Fraunces', serif", fontWeight:600, fontSize:38, letterSpacing:'-0.02em', color:'#241C3D', margin:'10px 0 8px', lineHeight:1.15 }}>
          나는 어떤 <span style={{ color:accent }}>판단 성향</span>일까?
        </h2>
        <p style={{ fontSize:15, color:'#6A6480', fontWeight:500, margin:0 }}>5개 질문 · 30초 · 가입 없이</p>
      </div>

      <div style={card}>
        {step === 0 && (
          <div style={{ textAlign:'center', padding:'8px 0' }}>
            <div style={{ fontSize:52, marginBottom:14 }}>🧭</div>
            <p style={{ fontSize:16, lineHeight:1.6, color:'#241C3D', fontWeight:500, margin:'0 0 24px' }}>
              점수를 매기는 검사가 아니에요.<br/>당신이 판단할 때 <b style={{ color:accent }}>어디에 기우는지</b>를 비춰봐요.
            </p>
            <button onClick={() => setStep(1)} style={{ padding:'15px 30px', borderRadius:13, border:0, background:accent, color:'#fff', fontSize:15, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>시작하기</button>
          </div>
        )}

        {step >= 1 && step <= 5 && (
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:22 }}>
              {[1,2,3,4,5].map(n => (
                <div key={n} style={{ flex:1, height:4, borderRadius:2, background: n <= step ? accent : 'rgba(124,92,252,0.15)' }}/>
              ))}
            </div>
            <div style={{ fontSize:12, fontWeight:800, letterSpacing:'0.14em', color:accent, marginBottom:12 }}>Q{step} / 5</div>
            <p style={{ fontSize:19, lineHeight:1.5, color:'#241C3D', fontWeight:600, margin:'0 0 22px' }}>{QUIZ[qi].q}</p>
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {QUIZ[qi].a.map(([label, tag], i) => {
                const on = sel === i;
                return (
                <button key={i} onClick={() => choose(i)}
                  style={{ display:'flex', alignItems:'center', gap:12, padding:'16px 18px', borderRadius:13, border:`1.5px solid ${on ? accent : 'rgba(124,92,252,0.2)'}`, background: on ? 'rgba(124,92,252,0.08)' : '#fff', cursor:'pointer', textAlign:'left', fontFamily:'inherit', transition:'all .15s' }}
                  onMouseOver={e=>{ if(!on){ e.currentTarget.style.borderColor=accent; e.currentTarget.style.background='rgba(124,92,252,0.04)'; } }}
                  onMouseOut={e=>{ if(!on){ e.currentTarget.style.borderColor='rgba(124,92,252,0.2)'; e.currentTarget.style.background='#fff'; } }}>
                  <span style={{ width:26, height:26, borderRadius:'50%', flexShrink:0, border:`1.5px solid ${accent}`, background: on ? accent : '#fff', color: on ? '#fff' : accent, display:'flex', alignItems:'center', justifyContent:'center', fontSize:12, fontWeight:800 }}>{on ? '✓' : 'ABC'[i]}</span>
                  <span style={{ fontSize:15.5, fontWeight:600, color:'#241C3D' }}>{label}</span>
                </button>
              );})}
            </div>
            <button onClick={next} disabled={sel == null}
              style={{ width:'100%', marginTop:20, padding:'15px 0', borderRadius:13, border:0, background: sel == null ? 'rgba(124,92,252,0.2)' : accent, color:'#fff', fontSize:15, fontWeight:700, cursor: sel == null ? 'not-allowed' : 'pointer', fontFamily:'inherit', transition:'all .15s' }}>
              {step === 5 ? '결과 보기' : '다음'}
            </button>
          </div>
        )}

        {step === 6 && (
          <div style={{ textAlign:'center', padding:'6px 0' }}>
            <div style={{ fontSize:13, fontWeight:800, letterSpacing:'0.14em', color:accent, marginBottom:16 }}>당신의 성향</div>
            <div style={{ fontSize:64, marginBottom:8 }}>{group.emoji}</div>
            <div style={{ fontFamily:"'Fraunces', serif", fontSize:30, fontWeight:600, color:'#241C3D', marginBottom:14 }}>{group.name}</div>
            <p style={{ fontSize:15.5, lineHeight:1.65, color:'#4A4460', fontWeight:500, maxWidth:440, margin:'0 auto 8px' }}>{group.desc}</p>
            <p style={{ fontSize:12.5, color:'#8A82A6', fontWeight:600, margin:'0 auto 22px' }}>고정된 성격이 아니라, 훈련되는 판단 습관입니다.</p>

            {/* 22유형 훅 */}
            <div style={{ background:'#F3EEFF', borderRadius:14, padding:'18px 20px', textAlign:'left', marginBottom:20 }}>
              <p style={{ margin:0, fontSize:14, lineHeight:1.65, color:'#3A3352' }}>
                이건 <b>'설문 속 당신'</b>입니다. Keitta의 <b style={{ color:accent }}>22가지 투자 유형</b>은 설문으로 얻을 수 없어요 — 당신의 <b>실제 판단 기록</b>만이 증명합니다. 설문 속 나와 판단 속 나는, 자주 다릅니다.
              </p>
            </div>

            <a href="#beta" style={{ display:'block', textAlign:'center', padding:'16px 0', borderRadius:14, background:accent, color:'#fff', fontSize:15.5, fontWeight:700, textDecoration:'none', marginBottom:12 }}>판단 속 나를 확인하러 가기 → 베타 신청</a>
            <button onClick={restart} style={{ border:0, background:'transparent', color:accent, fontSize:13.5, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>↺ 다시 검사하기</button>
          </div>
        )}
      </div>
    </Section>
  );
}

window.LandingQuiz = { Quiz };
