/* FreeAssessment.jsx — 4-step multi-step form (grade → questions → time → confirm)
   New compound component. Reuses chip, radio, button, input, card, modal,
   and stepper-dot tokens. The final step uses the Kakao-yellow button —
   the ONE allowed exception to the single-purple-interactive rule
   (Kakao brand guidelines mandate the yellow + black wordmark).
   Rationale: spec §4.1 — strongest lead-collection tool on the site
   (CMS / 필즈 patterns). */

const GRADES = [
  ['초1', 'G1'], ['초2', 'G2'], ['초3', 'G3'],
  ['초4', 'G4'], ['초5', 'G5'], ['초6', 'G6'],
];

const QUESTIONS = [
  { id: 'q1', text: 'fa.q1', choices: [
    [['1/12','1/12'], false], [['2/12','2/12'], false], [['3/8','3/8'], true], [['5/8','5/8'], false],
  ]},
  { id: 'q2', text: 'fa.q2', choices: [
    [['전부 저축','Save it all'], false],
    [['절반 저축','Save half'], true],
    [['저축 안 함','Don\'t save'], false],
    [['모르겠어요','Not sure'], false],
  ]},
  { id: 'q3', text: 'fa.q3', choices: [
    [['8가지','8'], false], [['16가지','16'], false], [['24가지','24'], true], [['64가지','64'], false],
  ]},
];

const TIMESLOTS = [
  ['평일 오전 10:00', 'Weekday 10:00 AM'],
  ['평일 오전 11:00', 'Weekday 11:00 AM'],
  ['평일 오후 14:00', 'Weekday 2:00 PM'],
  ['평일 오후 16:00', 'Weekday 4:00 PM'],
  ['주말 오전 10:00', 'Weekend 10:00 AM'],
  ['주말 오후 14:00', 'Weekend 2:00 PM'],
];

const FreeAssessment = ({ onComplete }) => {
  const t = window.useT();
  const { lang } = React.useContext(window.LangContext);
  const pick = pair => pair[lang === 'ko' ? 0 : 1];

  const [step, setStep] = React.useState(1);
  const [grade, setGrade] = React.useState(null);
  const [answers, setAnswers] = React.useState({});
  const [slot, setSlot] = React.useState(null);

  const next = () => setStep(s => Math.min(4, s + 1));
  const prev = () => setStep(s => Math.max(1, s - 1));

  const canNext =
    step === 1 ? !!grade :
    step === 2 ? Object.keys(answers).length === QUESTIONS.length :
    step === 3 ? !!slot :
    true;

  const isKo = lang === 'ko';
  const remaining = QUESTIONS.length - Object.keys(answers).length;
  const helperFor =
    step === 1 && !grade ? (isKo ? '학년을 먼저 선택해 주세요' : 'Please select a grade first') :
    step === 2 && remaining > 0 ? (isKo ? `${remaining}문항 더 풀어주세요` : `${remaining} more question${remaining === 1 ? '' : 's'} to go`) :
    step === 3 && !slot ? (isKo ? '상담 가능한 시간을 선택해 주세요' : 'Please pick a consultation time') : '';

  const stepLabels = [t('fa.step.1'), t('fa.step.2'), t('fa.step.3'), t('fa.step.4')];

  return (
    <section id="assessment" className="section" style={{
      background: 'linear-gradient(180deg, #F8FAFC 0%, #ffffff 100%)',
    }}>
      <div className="section-inner" style={{ maxWidth: 760 }}>
        <div style={{ textAlign: 'center' }}>
          <div className="label-ko" style={{ marginBottom: 16, justifyContent: 'center', display: 'inline-flex' }}>{t('fa.eyebrow')}</div>
          <h2 style={{
            fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
            fontSize: 'clamp(15px, 4.6vw, 38px)', fontWeight: 700, letterSpacing: '-0.4px',
            color: '#0B1727', margin: 0, lineHeight: 1.22,
            whiteSpace: 'nowrap',
          }}>{t('fa.h2')}</h2>
        </div>

        {/* Stepper — single horizontal row, no wrap.
            On narrow widths the per-step labels collapse so 4 dots + 3
            connectors always fit in one line; the current step name is
            promoted to a bigger label above the row instead.
            That kills the "확인 alone on a second line" wrap bug. */}
        <div className="assess-stepper" style={{ margin: '40px auto 24px', textAlign: 'center' }}>
          {/* Compact current-step header — visible only when the per-step
              labels are hidden (mobile/tablet). Pure CSS toggle. */}
          <div className="assess-stepper-current" aria-hidden="true">
            <span className="assess-stepper-current-eyebrow">STEP {step} / 4</span>
            <span className="assess-stepper-current-name">{stepLabels[step-1]}</span>
          </div>

          <div className="assess-stepper-row" style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 6, flexWrap: 'nowrap',
          }}>
            {[1,2,3,4].map(n => (
              <React.Fragment key={n}>
                <div className="assess-step-pair" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span className={`step-dot ${step > n ? 'is-done' : step === n ? 'is-active' : ''}`}>
                    {step > n && (
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                        stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"
                        style={{ display: 'block' }}>
                        <polyline points="20 6 9 17 4 12"/>
                      </svg>
                    )}
                  </span>
                  <span className="assess-step-label" style={{
                    fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
                    fontSize: 13, fontWeight: step === n ? 700 : 500,
                    color: step >= n ? '#0B1727' : '#94A3B8',
                    whiteSpace: 'nowrap',
                  }}>{stepLabels[n-1]}</span>
                </div>
                {n < 4 && <span className="assess-step-connector" style={{
                  width: 32, height: 2,
                  background: step > n ? '#6D28D9' : '#E2E8F0',
                  borderRadius: 2,
                  transition: 'background 200ms ease',
                  flexShrink: 0,
                }} />}
              </React.Fragment>
            ))}
          </div>

          <style>{`
            /* Default (desktop ≥760px) — per-step labels shown, current
               header hidden. */
            .assess-stepper-current { display: none; }

            /* Narrow widths — drop per-step text, promote current step to
               a header above the row. 4 dots + 3 connectors always fit. */
            @media (max-width: 760px) {
              .assess-step-label { display: none; }
              .assess-step-pair { gap: 0 !important; }
              .assess-step-connector { width: 20px !important; }
              .assess-stepper-current {
                display: flex !important;
                flex-direction: column;
                align-items: center;
                gap: 4px;
                margin-bottom: 16px;
              }
              .assess-stepper-current-eyebrow {
                font-family: var(--font-mono);
                font-size: 10.5px;
                font-weight: 700;
                letter-spacing: 0.14em;
                color: #94A3B8;
              }
              .assess-stepper-current-name {
                font-family: var(--font-sans);
                font-feature-settings: "ss01";
                font-size: 16px;
                font-weight: 700;
                letter-spacing: -0.2px;
                color: #6D28D9;
              }
            }
          `}</style>
        </div>

        {/* Card */}
        <div className="card" style={{
          padding: 36,
          background: '#fff',
          boxShadow: '0 1px 2px rgba(15,23,42,0.04), 0 24px 56px -24px rgba(15,23,42,0.16)',
        }}>

          {step === 1 && (
            <div className="assess-step1">
              <div className="assess-step1-title" style={{
                fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
                fontSize: 22, fontWeight: 700, letterSpacing: '-0.22px',
                color: '#0B1727', marginBottom: 8,
              }}>{isKo ? '자녀 학년을 선택해 주세요' : 'Please select your child\'s grade'}</div>
              <div className="assess-step1-desc" style={{ fontSize: 14, color: '#475569', marginBottom: 22 }}>
                {isKo ? '학년에 맞는 진단 문항이 자동으로 출제됩니다.' : 'Diagnostic questions are tailored to the selected grade.'}
              </div>
              <div className="assess-step1-chips" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {GRADES.map(g => (
                  <button key={g[1]} className="chip"
                    aria-pressed={grade === g[1]}
                    onClick={() => setGrade(g[1])}
                    style={{ minWidth: 68, textAlign: 'center', justifyContent: 'center', padding: '12px 18px', fontSize: 14 }}
                  >{lang === 'ko' ? g[0] : g[1]}</button>
                ))}
              </div>
              <style>{`
                @media (max-width: 767px) {
                  .assess-step1 { text-align: center; }
                  .assess-step1-chips { justify-content: center; }
                }
              `}</style>
            </div>
          )}

          {step === 2 && (
            <div>
              <div style={{
                fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
                fontSize: 20, fontWeight: 700, color: '#0B1727', marginBottom: 6,
              }}>{isKo ? `${QUESTIONS.length}문항 진단 · 약 2분 소요` : `${QUESTIONS.length}-question diagnostic · about 2 min`}</div>
              <div style={{ fontSize: 13.5, color: '#475569', marginBottom: 26, lineHeight: 1.6 }}>
                {isKo ? '정답 여부에 따라 자녀의 강점/취약점을 분석합니다.' : 'Answers reveal your child\'s strengths and weak spots.'}
              </div>

              {QUESTIONS.map((q, qi) => (
                <div key={q.id} style={{
                  marginBottom: 24, paddingBottom: 24,
                  borderBottom: qi === QUESTIONS.length - 1 ? '0' : '1px solid #F1F5F9',
                }}>
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '4px 9px', borderRadius: 6,
                    background: 'rgba(109,40,217,0.10)',
                    fontFamily: 'var(--font-mono)', fontSize: 11,
                    color: '#6D28D9', textTransform: 'uppercase',
                    letterSpacing: '0.06em', marginBottom: 10, fontWeight: 700,
                  }}>Q{qi + 1} / {QUESTIONS.length}</div>
                  <div style={{
                    fontSize: 17, fontWeight: 600,
                    color: '#0B1727', marginBottom: 14, lineHeight: 1.55,
                  }}>{t(q.text)}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {q.choices.map((c, ci) => {
                      const checked = answers[q.id] === ci;
                      return (
                        <label key={ci} style={{
                          display: 'flex', alignItems: 'center', gap: 12,
                          padding: '14px 16px',
                          border: `1.5px solid ${checked ? '#6D28D9' : '#E2E8F0'}`,
                          background: checked ? 'rgba(109,40,217,0.06)' : '#fff',
                          borderRadius: 10, cursor: 'pointer',
                          transition: 'all 140ms cubic-bezier(0.25,0.1,0.25,1)',
                        }}>
                          <input type="radio" name={q.id} checked={checked}
                            onChange={() => setAnswers(a => ({ ...a, [q.id]: ci }))}
                            style={{ accentColor: '#6D28D9', width: 18, height: 18 }}
                          />
                          <span style={{ fontSize: 15, fontWeight: checked ? 600 : 500, color: '#1E293B' }}>{isKo ? c[0][0] : c[0][1]}</span>
                        </label>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}

          {step === 3 && (
            <div>
              <div style={{
                fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
                fontSize: 22, fontWeight: 700, letterSpacing: '-0.22px',
                color: '#0B1727', marginBottom: 8,
              }}>{isKo ? '상담 가능한 시간을 골라주세요' : 'Pick a time that works for you'}</div>
              <div style={{ fontSize: 14, color: '#475569', marginBottom: 22 }}>
                {isKo ? '선택하신 시간에 카카오톡으로 상담 안내를 보내드립니다.' : 'We\'ll send the consultation details by KakaoTalk at the time you chose.'}
              </div>
              <div className="time-grid" style={{
                display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8,
              }}>
                {TIMESLOTS.map(s => (
                  <button key={s[0]} className="chip"
                    aria-pressed={slot === s[0]}
                    onClick={() => setSlot(s[0])}
                    style={{ textAlign: 'left', justifyContent: 'flex-start', padding: '12px 16px', fontSize: 14 }}
                  >{isKo ? s[0] : s[1]}</button>
                ))}
              </div>
              <input placeholder={isKo ? '이름 또는 자녀 이름 (선택)' : 'Your name or child\'s name (optional)'} style={{
                marginTop: 22, width: '100%',
                fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
                fontSize: 15, fontWeight: 500,
                padding: '14px 16px',
                border: '1.5px solid #E2E8F0', borderRadius: 10,
                outline: 'none', color: '#0B1727',
                transition: 'border-color 140ms ease',
              }} onFocus={e => e.target.style.borderColor = '#6D28D9'}
                 onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
            </div>
          )}

          {step === 4 && (
            <div style={{ textAlign: 'center', padding: '14px 0' }}>
              <div style={{
                width: 64, height: 64, borderRadius: '50%',
                background: 'rgba(21,190,83,0.16)',
                color: '#15803D',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                marginBottom: 18,
                boxShadow: '0 0 0 6px rgba(21,190,83,0.08)',
              }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 6L9 17l-5-5"/>
                </svg>
              </div>
              <div style={{
                fontFamily: 'var(--font-sans)', fontFeatureSettings: '"ss01"',
                fontSize: 'clamp(14px, 3.4vw, 26px)', fontWeight: 700, color: '#0B1727', letterSpacing: '-0.3px',
                whiteSpace: 'nowrap',
              }}>{isKo ? '거의 끝났습니다.' : 'Almost done.'}</div>
              <div style={{ fontSize: 15, fontWeight: 500, color: '#475569', marginTop: 12, lineHeight: 1.70 }}>
                {isKo ? (
                  <>카카오로 로그인하면 진단 결과 + 예약 확정 카톡이 즉시 도착합니다.<br/>다음 단계에서 재가입은 필요 없습니다.</>
                ) : (
                  <>Sign in with Kakao to get your diagnostic result and booking confirmation by KakaoTalk instantly.<br/>No re-registration needed.</>
                )}
              </div>
              <div style={{ marginTop: 26 }}>
                <Button variant="kakao" size="lg" onClick={onComplete}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <ellipse cx="12" cy="11" rx="9" ry="7" fill="#191600"/>
                    <path d="M9 17l1.5-3" stroke="#191600" strokeWidth="2"/>
                  </svg>
                  {t('fa.book')}
                </Button>
              </div>
            </div>
          )}

          {/* Footer nav with helper text for disabled state */}
          <div style={{
            marginTop: 32, paddingTop: 22, borderTop: '1px solid #EEF2F7',
            display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap',
          }}>
            <Button variant="secondary" size="md" onClick={prev}
              {...(step === 1 ? { style: { visibility: 'hidden' } } : {})}>
              ← {t('fa.prev')}
            </Button>
            {helperFor && step < 4 && (
              <span style={{
                fontSize: 13, color: '#94A3B8', fontWeight: 500,
                marginLeft: 'auto', marginRight: 0,
              }}>{helperFor}</span>
            )}
            {step < 4 && (
              <Button variant="primary" size="md" onClick={next}
                {...(canNext ? { style: { marginLeft: helperFor ? 0 : 'auto' } } : { 'data-disabled': 'true', style: { marginLeft: helperFor ? 0 : 'auto' } })}>
                {t('fa.next')} →
              </Button>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .time-grid { grid-template-columns: 1fr 1fr !important; }
        }
      `}</style>
    </section>
  );
};

window.FreeAssessment = FreeAssessment;
