// 돼지엄마 — Notification + Search + Signup/Onboarding/Verification

// ───────── NOTIFICATION ─────────
function NotificationScreen({ onBack, t }) {
  const [items, setItems] = useState(D.notifications);
  const unreadCount = items.filter((n) => n.unread).length;

  const markAllRead = () => setItems(items.map((n) => ({ ...n, unread: false })));
  const toggleRead = (id) => setItems(items.map((n) => n.id === id ? { ...n, unread: !n.unread } : n));

  const dotColor = (c) => ({
    primary: 'var(--c-primary)', verified: 'var(--c-verified)', senior: 'var(--c-senior)',
    success: 'var(--c-success)', honor: '#A77A00',
  }[c] || 'var(--c-primary)');

  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%' }}>
      <div style={{ height: 52, display: 'flex', alignItems: 'center', padding: '0 8px 0 16px', borderBottom: '1px solid var(--c-border)', background: 'var(--c-bg-primary)', position: 'sticky', top: 0, zIndex: 10 }}>
        <button onClick={onBack} style={{ width: 36, height: 36, marginLeft: -8, display: 'grid', placeItems: 'center', border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--c-text-primary)' }}>
          <Icon name="chevL" size={22} />
        </button>
        <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--c-text-primary)', flex: 1 }}>알림 {unreadCount > 0 && <span style={{ color: 'var(--c-primary)', fontVariantNumeric: 'tabular-nums' }}>{unreadCount}</span>}</div>
        {unreadCount > 0 && (
          <button onClick={markAllRead} style={{ padding: '6px 10px', border: 0, background: 'transparent', cursor: 'pointer', fontSize: 12.5, color: 'var(--c-text-sub)', fontWeight: 600 }}>모두 읽음</button>
        )}
      </div>

      <div style={{ padding: '8px 16px 100px' }}>
        {unreadCount === 0 && items.length === 0 && (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--c-text-tertiary)' }}>
            <div style={{ fontSize: 40, marginBottom: 10 }}>🔔</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--c-text-sub)' }}>새 알림이 없어요</div>
          </div>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {items.map((n) => (
            <div key={n.id} onClick={() => toggleRead(n.id)} style={{
              padding: 14, borderRadius: 10, cursor: 'pointer',
              background: n.unread ? 'var(--c-bg-primary)' : 'transparent',
              border: n.unread ? '1px solid var(--c-border-soft)' : '1px solid transparent',
              display: 'flex', gap: 12, alignItems: 'flex-start',
              boxShadow: n.unread ? 'var(--card-shadow)' : 'none',
            }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: dotColor(n.color) + '20', display: 'grid', placeItems: 'center', flexShrink: 0, fontSize: 16 }}>
                {n.type === 'review_published' && '⭐'}
                {n.type === 'comment_on_post' && '💬'}
                {n.type === 'consultation_reminder' && '📅'}
                {n.type === 'event_subscribed' && '🎫'}
                {n.type === 'review_helpful' && '👍'}
                {n.type === 'trust_level_up' && '👑'}
                {n.type === 'consultation_payout' && '💰'}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--c-text-primary)' }}>{n.title}</span>
                  {n.unread && <span style={{ width: 7, height: 7, borderRadius: 4, background: dotColor(n.color), flexShrink: 0 }} />}
                </div>
                <div style={{ fontSize: 12.5, lineHeight: 1.5, color: 'var(--c-text-sub)', marginBottom: 6, textWrap: 'pretty' }}>{n.body}</div>
                <div style={{ fontSize: 11, color: 'var(--c-text-tertiary)' }}>{n.meta}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ───────── SEARCH ─────────
function SearchScreen({ onBack, onPost, onConsult, t }) {
  const [q, setQ] = useState('');
  const [recent, setRecent] = useState(D.searchRecent);
  const focused = q.length >= 1;

  const search = (text) => {
    setQ(text);
    if (text && !recent.includes(text)) setRecent([text, ...recent].slice(0, 5));
  };

  // simple in-memory search across boards/institutions/consultants
  const lowerQ = q.toLowerCase();
  const postHits = q ? D.boardPosts.filter((p) => p.title.toLowerCase().includes(lowerQ)).slice(0, 5) : [];
  const instHits = q ? D.reviewSearch.filter((r) => r.name.toLowerCase().includes(lowerQ) || r.cat.toLowerCase().includes(lowerQ)).slice(0, 3) : [];
  const expertHits = q ? D.consultants.filter((c) => c.name.toLowerCase().includes(lowerQ) || c.tags.some((tg) => tg.toLowerCase().includes(lowerQ))).slice(0, 3) : [];
  const totalHits = postHits.length + instHits.length + expertHits.length;

  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%' }}>
      {/* Search input */}
      <div style={{ padding: 12, background: 'var(--c-bg-primary)', borderBottom: '1px solid var(--c-border)', position: 'sticky', top: 0, zIndex: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
        <button onClick={onBack} style={{ width: 36, height: 36, display: 'grid', placeItems: 'center', border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--c-text-primary)', flexShrink: 0 }}>
          <Icon name="chevL" size={22} />
        </button>
        <div style={{ flex: 1, position: 'relative' }}>
          <input value={q} onChange={(e) => setQ(e.target.value)} autoFocus
            placeholder="학부모, 기관, 게시글 검색"
            style={{ width: '100%', height: 40, padding: '0 36px 0 36px', borderRadius: 20, border: '1px solid var(--c-border)', background: 'var(--c-bg-secondary)', fontSize: 14, color: 'var(--c-text-primary)', outline: 'none' }} />
          <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--c-text-tertiary)' }}>
            <Icon name="search" size={16} />
          </span>
          {q && (
            <button onClick={() => setQ('')} style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', width: 24, height: 24, borderRadius: 12, border: 0, background: 'var(--c-text-tertiary)', color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
              <Icon name="close" size={14} stroke={3} />
            </button>
          )}
        </div>
      </div>

      <div style={{ padding: '8px 16px 100px' }}>
        {!focused && (
          <>
            {recent.length > 0 && (
              <div style={{ padding: '12px 4px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-text-sub)' }}>최근 검색</div>
                  <button onClick={() => setRecent([])} style={{ border: 0, background: 'transparent', fontSize: 12, color: 'var(--c-text-tertiary)', cursor: 'pointer' }}>전체 삭제</button>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {recent.map((r) => (
                    <div key={r} onClick={() => search(r)} style={{ padding: '10px 4px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14, color: 'var(--c-text-primary)' }}>
                      <Icon name="search" size={14} color="var(--c-text-tertiary)" />
                      <span style={{ flex: 1 }}>{r}</span>
                      <button onClick={(e) => { e.stopPropagation(); setRecent(recent.filter((x) => x !== r)); }} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--c-text-tertiary)' }}>
                        <Icon name="close" size={14} />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div style={{ padding: '12px 4px' }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 10 }}>🔥 인기 검색</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {D.searchTrending.map((s) => (
                  <button key={s} onClick={() => search(s)} style={{
                    padding: '8px 12px', borderRadius: 16, border: '1px solid var(--c-border)', background: 'var(--c-bg-primary)',
                    fontSize: 13, fontWeight: 500, color: 'var(--c-text-sub)', cursor: 'pointer',
                  }}>{s}</button>
                ))}
              </div>
            </div>
          </>
        )}

        {focused && (
          <>
            {totalHits === 0 && (
              <div style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--c-text-tertiary)' }}>
                <div style={{ fontSize: 40, marginBottom: 10 }}>🔍</div>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--c-text-sub)' }}>"{q}" 결과가 없어요</div>
                <div style={{ fontSize: 12, marginTop: 4 }}>다른 키워드로 시도해보세요</div>
              </div>
            )}
            {postHits.length > 0 && (
              <SearchSection title={`📝 게시글 ${postHits.length}`}>
                {postHits.map((p) => (
                  <div key={p.id} onClick={() => onPost && onPost(p.id)} style={{ padding: '10px 4px', cursor: 'pointer', borderBottom: '1px solid var(--c-border-soft)' }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--c-text-primary)', lineHeight: 1.4, marginBottom: 4, textWrap: 'pretty' }}>
                      {highlight(p.title, q)}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--c-text-sub)' }}>{p.author} · {p.meta}</div>
                  </div>
                ))}
              </SearchSection>
            )}
            {instHits.length > 0 && (
              <SearchSection title={`🏛 기관 ${instHits.length}`}>
                {instHits.map((r) => (
                  <div key={r.id} style={{ padding: '10px 4px', cursor: 'pointer', borderBottom: '1px solid var(--c-border-soft)', display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--c-bg-secondary)', display: 'grid', placeItems: 'center', fontSize: 18, flexShrink: 0 }}>🏢</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--c-text-primary)' }}>{highlight(r.name, q)}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--c-text-sub)' }}>{r.cat} · ★ {r.rating} ({r.count})</div>
                    </div>
                  </div>
                ))}
              </SearchSection>
            )}
            {expertHits.length > 0 && (
              <SearchSection title={`👤 컨설턴트 ${expertHits.length}`}>
                {expertHits.map((c) => (
                  <div key={c.id} onClick={() => onConsult && onConsult(c.id)} style={{ padding: '10px 4px', cursor: 'pointer', borderBottom: '1px solid var(--c-border-soft)', display: 'flex', alignItems: 'center', gap: 10 }}>
                    <Avatar initial={c.avatar} bg={c.avatarBg} size={36} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--c-text-primary)' }}>{highlight(c.name, q)}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--c-text-sub)' }}>{c.tags[0]} · ★ {c.rating}</div>
                    </div>
                  </div>
                ))}
              </SearchSection>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function SearchSection({ title, children }) {
  return (
    <div style={{ padding: '12px 4px' }}>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 6 }}>{title}</div>
      {children}
    </div>
  );
}

function highlight(text, q) {
  if (!q) return text;
  const idx = text.toLowerCase().indexOf(q.toLowerCase());
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <span style={{ color: 'var(--c-primary)', fontWeight: 800 }}>{text.slice(idx, idx + q.length)}</span>
      {text.slice(idx + q.length)}
    </>
  );
}

// ───────── SIGNUP / ONBOARDING / VERIFICATION ─────────
function SignupFlowScreen({ onCancel, onComplete, t }) {
  const [step, setStep] = useState(0); // 0:welcome 1:phone 2:terms 3:childInfo 4:verifyOptional 5:done
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [codeSent, setCodeSent] = useState(false);
  const [terms, setTerms] = useState({ service: false, privacy: false, marketing: false });
  const [region, setRegion] = useState('');
  const [grade, setGrade] = useState('');
  const [verifyChoice, setVerifyChoice] = useState(null); // 'now' | 'later'

  const allTerms = terms.service && terms.privacy;

  const next = () => setStep(step + 1);
  const back = () => setStep(Math.max(0, step - 1));

  // ── Welcome ──
  if (step === 0) {
    return (
      <div style={{ background: 'var(--c-bg-primary)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={{ height: 52, display: 'flex', alignItems: 'center', padding: '0 8px 0 16px' }}>
          <button onClick={onCancel} style={{ width: 36, height: 36, marginLeft: -8, display: 'grid', placeItems: 'center', border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--c-text-primary)' }}>
            <Icon name="close" size={22} />
          </button>
        </div>
        <div style={{ flex: 1, padding: '20px 24px 40px', display: 'flex', flexDirection: 'column' }}>
          <div style={{ flex: 1 }}>
            <div style={{ marginTop: 40, fontSize: 28, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.03em', lineHeight: 1.25, textWrap: 'pretty' }}>
              학부모만 들어올 수 있는<br />
              <span style={{ color: 'var(--c-primary)' }}>진짜 정보가 있는 곳</span>
            </div>
            <div style={{ marginTop: 16, fontSize: 14.5, lineHeight: 1.65, color: 'var(--c-text-sub)', textWrap: 'pretty' }}>
              4,219명의 검증된 학부모와 솔직하게 나누세요.<br />
              합격기·학원 평가·컨설턴트 후기 모두 인증된 1차 정보입니다.
            </div>

            <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                { i: '✓', t: '자녀 재학증명서 인증', s: '학부모만 가입 가능 (광고·자작 후기 X)' },
                { i: '🔒', t: '익명성 끝까지 보호', s: '"강남구 고2 학부모"로만 노출' },
                { i: '⭐', t: '검증된 컨설턴트와 1:1', s: 'Harvard MBA·전 입학사정관' },
                { i: '🤖', t: 'AI 학부모 비서', s: '검증된 1차 정보 기반' },
              ].map((b, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 8, background: 'rgba(44,91,255,.10)', color: 'var(--c-primary)', display: 'grid', placeItems: 'center', fontSize: 16, fontWeight: 700, flexShrink: 0 }}>{b.i}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--c-text-primary)' }}>{b.t}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--c-text-sub)' }}>{b.s}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <Button kind="primary" full size="lg" onClick={next}>시작하기</Button>
          <div style={{ marginTop: 12, textAlign: 'center', fontSize: 12, color: 'var(--c-text-sub)' }}>
            이미 계정이 있으신가요? <span style={{ color: 'var(--c-primary)', fontWeight: 700 }}>로그인</span>
          </div>
        </div>
      </div>
    );
  }

  // ── Phone auth ──
  if (step === 1) {
    return (
      <SignupFrame title="휴대폰 인증" step={1} onBack={back} onClose={onCancel}>
        <div style={{ flex: 1, padding: '24px 4px' }}>
          <div style={{ fontSize: 21, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.025em', marginBottom: 8 }}>
            휴대폰 번호를 입력해주세요
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--c-text-sub)', marginBottom: 24, lineHeight: 1.55 }}>
            본인 확인용입니다. 알림과 문의 외에는 사용하지 않아요.
          </div>

          <div style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 6 }}>휴대폰 번호</div>
            <input value={phone} onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
              placeholder="01012345678" inputMode="numeric"
              style={{ width: '100%', height: 52, padding: '0 16px', borderRadius: 10, border: '1px solid var(--c-border)', fontSize: 18, fontWeight: 600, color: 'var(--c-text-primary)', outline: 'none', background: 'var(--c-bg-primary)', fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }} />
            {phone.length === 11 && !codeSent && (
              <Button kind="secondary" size="md" onClick={() => setCodeSent(true)} style={{ marginTop: 8 }}>인증번호 받기</Button>
            )}
          </div>

          {codeSent && (
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 6 }}>인증번호 (6자리)</div>
              <input value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="000000" inputMode="numeric" autoFocus
                style={{ width: '100%', height: 52, padding: '0 16px', borderRadius: 10, border: '1px solid var(--c-border)', fontSize: 22, fontWeight: 700, color: 'var(--c-text-primary)', outline: 'none', background: 'var(--c-bg-primary)', textAlign: 'center', fontVariantNumeric: 'tabular-nums', letterSpacing: '0.5em' }} />
              <div style={{ marginTop: 8, fontSize: 12, color: 'var(--c-text-tertiary)' }}>SMS로 인증번호를 발송했어요. 02:59 남음.</div>
            </div>
          )}
        </div>
        <Button kind="primary" full size="lg" disabled={code.length < 6} onClick={next}>인증 완료</Button>
      </SignupFrame>
    );
  }

  // ── Terms ──
  if (step === 2) {
    return (
      <SignupFrame title="약관 동의" step={2} onBack={back} onClose={onCancel}>
        <div style={{ flex: 1, padding: '24px 4px' }}>
          <div style={{ fontSize: 21, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.025em', marginBottom: 8 }}>
            약관에 동의해주세요
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--c-text-sub)', marginBottom: 24, lineHeight: 1.55 }}>
            돼지엄마는 학부모가 안전하게 정보를 나눌 수 있도록 엄격한 정책을 운영합니다.
          </div>

          {/* Master toggle */}
          <button onClick={() => {
            const all = !(terms.service && terms.privacy && terms.marketing);
            setTerms({ service: all, privacy: all, marketing: all });
          }} style={{
            width: '100%', padding: 16, borderRadius: 12, border: '1px solid var(--c-border)',
            background: 'var(--c-bg-primary)', display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, cursor: 'pointer',
          }}>
            <CheckSq on={terms.service && terms.privacy && terms.marketing} />
            <span style={{ flex: 1, textAlign: 'left', fontSize: 14.5, fontWeight: 700, color: 'var(--c-text-primary)' }}>전체 동의</span>
          </button>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {[
              { k: 'service', label: '서비스 이용약관 (필수)', detail: '회원가입·이용 정책', required: true },
              { k: 'privacy', label: '개인정보 처리방침 (필수)', detail: '본인인증·자녀 정보 등 7일 자동 파기', required: true },
              { k: 'marketing', label: '마케팅 정보 수신 (선택)', detail: '박람회·이벤트 알림', required: false },
            ].map((it) => (
              <button key={it.k} onClick={() => setTerms({ ...terms, [it.k]: !terms[it.k] })} style={{
                padding: 14, borderRadius: 10, border: 0, background: 'transparent', cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <CheckSq on={terms[it.k]} small />
                <span style={{ flex: 1, textAlign: 'left' }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: it.required ? 'var(--c-text-primary)' : 'var(--c-text-sub)' }}>
                    {it.label}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--c-text-tertiary)' }}>{it.detail}</div>
                </span>
                <span style={{ fontSize: 12, color: 'var(--c-text-tertiary)' }}>보기 ›</span>
              </button>
            ))}
          </div>
        </div>
        <Button kind="primary" full size="lg" disabled={!allTerms} onClick={next}>동의하고 계속</Button>
      </SignupFrame>
    );
  }

  // ── Child info ──
  if (step === 3) {
    const regions = ['강남구', '서초구', '송파구', '분당', '용산', '기타'];
    const grades = ['초등', '중1', '중2', '중3', '고1', '고2', '고3', '재수'];
    return (
      <SignupFrame title="자녀 정보" step={3} onBack={back} onClose={onCancel}>
        <div style={{ flex: 1, padding: '24px 4px' }}>
          <div style={{ fontSize: 21, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.025em', marginBottom: 8 }}>
            자녀의 학년·지역만 알려주세요
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--c-text-sub)', marginBottom: 24, lineHeight: 1.55, textWrap: 'pretty' }}>
            "강남구 고2 학부모"처럼 익명 닉네임으로만 표시됩니다. 자녀의 이름·주민번호는 절대 받지 않아요.
          </div>

          <div style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-text-primary)', marginBottom: 8 }}>거주 지역</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {regions.map((r) => (
                <button key={r} onClick={() => setRegion(r)} style={{
                  padding: '8px 14px', borderRadius: 18, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  border: '1px solid ' + (region === r ? 'var(--c-primary)' : 'var(--c-border)'),
                  background: region === r ? 'var(--c-primary)' : 'var(--c-bg-primary)',
                  color: region === r ? '#fff' : 'var(--c-text-sub)',
                }}>{r}</button>
              ))}
            </div>
          </div>

          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-text-primary)', marginBottom: 8 }}>자녀 학년</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {grades.map((g) => (
                <button key={g} onClick={() => setGrade(g)} style={{
                  padding: '8px 14px', borderRadius: 18, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  border: '1px solid ' + (grade === g ? 'var(--c-primary)' : 'var(--c-border)'),
                  background: grade === g ? 'var(--c-primary)' : 'var(--c-bg-primary)',
                  color: grade === g ? '#fff' : 'var(--c-text-sub)',
                }}>{g}</button>
              ))}
            </div>
          </div>

          {region && grade && (
            <div style={{ marginTop: 24, padding: 14, borderRadius: 10, background: 'rgba(44,91,255,.06)', border: '1px solid rgba(44,91,255,.18)' }}>
              <div style={{ fontSize: 12, color: 'var(--c-text-sub)', marginBottom: 4 }}>이렇게 노출됩니다</div>
              <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--c-primary)' }}>{region} {grade} 학부모</div>
            </div>
          )}
        </div>
        <Button kind="primary" full size="lg" disabled={!region || !grade} onClick={next}>다음</Button>
      </SignupFrame>
    );
  }

  // ── Verification optional ──
  if (step === 4) {
    return (
      <SignupFrame title="검증 (선택)" step={4} onBack={back} onClose={onCancel}>
        <div style={{ flex: 1, padding: '24px 4px' }}>
          <div style={{ fontSize: 21, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.025em', marginBottom: 8 }}>
            지금 검증하면 ✓ 검증 학부모 뱃지를 받아요
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--c-text-sub)', marginBottom: 20, lineHeight: 1.55, textWrap: 'pretty' }}>
            자녀 재학증명서를 제출하면 평가·솔직 후기 작성 권한이 열립니다. 자료는 운영팀 2명만 열람 후 7일 내 자동 파기.
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
            <button onClick={() => setVerifyChoice('now')} style={{
              padding: 16, borderRadius: 12, border: `2px solid ${verifyChoice === 'now' ? 'var(--c-primary)' : 'var(--c-border)'}`,
              background: verifyChoice === 'now' ? 'rgba(44,91,255,.04)' : 'var(--c-bg-primary)',
              cursor: 'pointer', textAlign: 'left',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <Icon name="shield" size={18} color="var(--c-verified)" stroke={2.4} />
                <span style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--c-text-primary)' }}>지금 검증</span>
                <Badge kind="verified" emphasis="strong" size="xs" />
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--c-text-sub)', lineHeight: 1.55, textWrap: 'pretty' }}>
                재학증명서 업로드 → 24~48시간 내 검수 완료 → 평가 작성 권한 활성
              </div>
            </button>

            <button onClick={() => setVerifyChoice('later')} style={{
              padding: 16, borderRadius: 12, border: `2px solid ${verifyChoice === 'later' ? 'var(--c-primary)' : 'var(--c-border)'}`,
              background: verifyChoice === 'later' ? 'rgba(44,91,255,.04)' : 'var(--c-bg-primary)',
              cursor: 'pointer', textAlign: 'left',
            }}>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--c-text-primary)', marginBottom: 6 }}>일단 둘러보기</div>
              <div style={{ fontSize: 12.5, color: 'var(--c-text-sub)', lineHeight: 1.55 }}>
                나중에 마이페이지 → 검증 받기에서 진행 가능. 단 평가 작성·솔직 후기는 검증 후 가능.
              </div>
            </button>
          </div>

          {verifyChoice === 'now' && (
            <div style={{
              padding: 16, borderRadius: 12, background: 'linear-gradient(135deg, rgba(44,91,255,.04), rgba(0,200,150,.03))',
              border: '1px solid rgba(44,91,255,.18)', marginBottom: 12,
            }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-primary)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="lock" size={14} stroke={2.4} /> 보안 안내
              </div>
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, lineHeight: 1.65, color: 'var(--c-text-primary)' }}>
                <li>운영팀 2명만 KMS 암호화 버킷에서 열람</li>
                <li>검증 완료 후 7일 내 자동 파기 (S3 lifecycle)</li>
                <li>평가 본문에 절대 노출되지 않음</li>
              </ul>
              <button style={{
                marginTop: 12, width: '100%', height: 44, borderRadius: 10, border: '2px dashed var(--c-border)',
                background: 'var(--c-bg-primary)', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, color: 'var(--c-text-sub)', fontSize: 13, fontWeight: 600,
              }}>
                <Icon name="upload" size={16} /> 재학증명서 사진 또는 PDF
              </button>
            </div>
          )}
        </div>
        <Button kind="primary" full size="lg" disabled={!verifyChoice} onClick={next}>가입 완료</Button>
      </SignupFrame>
    );
  }

  // ── Done ──
  return (
    <div style={{ background: 'var(--c-bg-primary)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '40px 24px' }}>
        <div style={{ width: 96, height: 96, borderRadius: 48, background: 'rgba(0,184,82,.12)', display: 'grid', placeItems: 'center', marginBottom: 24 }}>
          <Icon name="check" size={48} stroke={2.4} color="var(--c-success)" />
        </div>
        <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.025em', marginBottom: 10, textAlign: 'center' }}>
          {region} {grade} 학부모님,<br />환영합니다!
        </div>
        <div style={{ fontSize: 14.5, lineHeight: 1.6, color: 'var(--c-text-sub)', maxWidth: 300, textWrap: 'pretty', textAlign: 'center', marginBottom: 32 }}>
          {verifyChoice === 'now' ? '재학증명서 검수가 진행 중입니다. 24~48시간 내 결과를 알림으로 보내드릴게요.' : '둘러보시다가 평가를 작성하시려면 검증을 진행해주세요.'}
        </div>
        <div style={{ width: '100%', maxWidth: 320, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Button kind="primary" full size="lg" onClick={onComplete}>홈으로 가기</Button>
          {verifyChoice !== 'now' && (
            <Button kind="ghost" full onClick={onComplete}>나중에 검증할게요</Button>
          )}
        </div>
      </div>
    </div>
  );
}

function SignupFrame({ title, step, onBack, onClose, children }) {
  return (
    <div style={{ background: 'var(--c-bg-primary)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ height: 52, display: 'flex', alignItems: 'center', padding: '0 8px' }}>
        <button onClick={onBack} style={{ width: 36, height: 36, display: 'grid', placeItems: 'center', border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--c-text-primary)' }}>
          <Icon name="chevL" size={22} />
        </button>
        <div style={{ flex: 1, fontSize: 15, fontWeight: 600, color: 'var(--c-text-sub)', textAlign: 'center' }}>{title}</div>
        <button onClick={onClose} style={{ width: 36, height: 36, display: 'grid', placeItems: 'center', border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--c-text-tertiary)' }}>
          <Icon name="close" size={20} />
        </button>
      </div>
      <div style={{ padding: '0 16px 8px' }}>
        <div style={{ display: 'flex', gap: 4 }}>
          {[1, 2, 3, 4].map((n) => (
            <div key={n} style={{ flex: 1, height: 3, borderRadius: 2, background: n <= step ? 'var(--c-primary)' : 'var(--c-border)', transition: 'background .25s' }} />
          ))}
        </div>
      </div>
      <div style={{ flex: 1, padding: '0 16px 16px', display: 'flex', flexDirection: 'column' }}>
        {children}
      </div>
    </div>
  );
}

function CheckSq({ on, small }) {
  const sz = small ? 20 : 24;
  return (
    <div style={{
      width: sz, height: sz, borderRadius: 5, flexShrink: 0,
      background: on ? 'var(--c-primary)' : 'transparent',
      border: `2px solid ${on ? 'var(--c-primary)' : 'var(--c-border)'}`,
      display: 'grid', placeItems: 'center',
    }}>
      {on && <Icon name="check" size={sz * 0.6} color="#fff" stroke={3} />}
    </div>
  );
}

Object.assign(window, { NotificationScreen, SearchScreen, SignupFlowScreen });
