// 돼지엄마 — Consultant list, AI assistant chat

// ───────── CONSULTANT LIST ─────────
function ConsultantScreen({ onConsult, t }) {
  const [cat, setCat] = useState('admit');
  const [sort, setSort] = useState('rating');
  const cats = [
    { id: 'admit', label: '입시 전략' },
    { id: 'career', label: '글로벌 커리어' },
    { id: 'essay', label: '에세이 첨삭' },
  ];
  const sorts = [
    { id: 'rating', label: '평점순' },
    { id: 'price', label: '가격낮은순' },
    { id: 'rec', label: '추천순' },
  ];
  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%' }}>
      <TopBar title="검증된 컨설턴트" />

      {/* Trust banner */}
      <div style={{ padding: '12px 16px 0' }}>
        <div style={{
          padding: 12, borderRadius: 10, background: 'rgba(0,200,150,.08)',
          border: '1px solid rgba(0,200,150,.20)',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <Icon name="shield" size={20} color="var(--c-verified)" stroke={2.2} />
          <div style={{ flex: 1, fontSize: 12.5, lineHeight: 1.5, color: 'var(--c-text-primary)' }}>
            <b>학력·경력·재직 증명서 검증 완료</b>한 컨설턴트만 활동합니다
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ padding: '14px 16px 0', display: 'flex', gap: 6 }}>
        {cats.map((c) => (
          <button key={c.id} onClick={() => setCat(c.id)} style={{
            padding: '8px 14px', borderRadius: 18, fontSize: 13, fontWeight: 600, cursor: 'pointer',
            border: '1px solid ' + (cat === c.id ? 'var(--c-primary)' : 'var(--c-border)'),
            background: cat === c.id ? 'var(--c-primary)' : 'var(--c-bg-primary)',
            color: cat === c.id ? '#fff' : 'var(--c-text-sub)',
          }}>{c.label}</button>
        ))}
      </div>

      {/* Sort row */}
      <div style={{ padding: '14px 16px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 12, color: 'var(--c-text-sub)' }}>전체 <span style={{ fontWeight: 700, color: 'var(--c-text-primary)' }}>{D.consultants.length}</span>명</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{
            padding: '6px 10px', border: '1px solid var(--c-border)', borderRadius: 16,
            background: 'var(--c-bg-primary)', cursor: 'pointer',
            fontSize: 12, color: 'var(--c-text-sub)', display: 'flex', alignItems: 'center', gap: 4,
          }}><Icon name="filter" size={14} /> 필터</button>
          <select value={sort} onChange={(e) => setSort(e.target.value)} style={{
            padding: '6px 10px', border: '1px solid var(--c-border)', borderRadius: 16,
            background: 'var(--c-bg-primary)', fontSize: 12, color: 'var(--c-text-sub)',
          }}>
            {sorts.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
        </div>
      </div>

      {/* Cards */}
      <div style={{ padding: '8px 16px 100px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {D.consultants.map((c) => (
          <Card key={c.id} padding={16} onClick={() => onConsult && onConsult(c.id)}>
            <div style={{ display: 'flex', gap: 14, marginBottom: 12 }}>
              <Avatar initial={c.avatar} bg={c.avatarBg} size={64} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--c-text-primary)', marginBottom: 4, letterSpacing: '-0.02em' }}>
                  {c.name}{!c.photo && <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--c-text-tertiary)', marginLeft: 6 }}>(익명 멘토)</span>}
                </div>
                <div style={{ fontSize: 13, color: 'var(--c-text-sub)', marginBottom: 8, textWrap: 'pretty' }}>{c.tagline}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {c.tags.map((tg, i) => (
                    <Badge key={i} kind="expert" label={tg} emphasis={t.badgeEmphasis === 'minimal' ? 'medium' : t.badgeEmphasis} size="xs" />
                  ))}
                </div>
              </div>
            </div>

            {/* Rating */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 12, fontSize: 13 }}>
              <span style={{ color: '#FFB700', fontSize: 15 }}>★</span>
              <b style={{ color: 'var(--c-text-primary)' }}>{c.rating}</b>
              <span style={{ color: 'var(--c-text-sub)' }}>({c.reviews}명 후기)</span>
            </div>

            {/* Prices */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: 12, background: 'var(--c-bg-secondary)', borderRadius: 10 }}>
              {c.prices.map((p, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                  <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: 'var(--c-bg-primary)', color: 'var(--c-text-sub)', minWidth: 36, textAlign: 'center' }}>{p.dur}</span>
                  <span style={{ flex: 1, color: 'var(--c-text-primary)', fontWeight: 500 }}>{p.label}</span>
                  <b style={{ color: 'var(--c-text-primary)', fontVariantNumeric: 'tabular-nums', fontSize: 14 }}>{(p.price / 10000).toLocaleString()}만원</b>
                </div>
              ))}
            </div>

            <div style={{ marginTop: 12 }}>
              <Button kind="primary" full size="md">상담 예약</Button>
            </div>
          </Card>
        ))}

        <div style={{ height: 40, display: 'grid', placeItems: 'center', color: 'var(--c-text-tertiary)', fontSize: 12 }}>
          더 많은 컨설턴트 불러오는 중...
        </div>
      </div>
    </div>
  );
}

// ───────── AI ASSISTANT CHAT ─────────
function AIChatScreen({ t, onProfile }) {
  const [messages, setMessages] = useState([
    { id: 1, kind: 'system' },
    { id: 2, kind: 'user', text: '고2 자녀, 내신 2.8, SAT 1450, 미국 학부 어디 가능할까요?' },
    { id: 3, kind: 'ai' },
  ]);
  const [input, setInput] = useState('');
  const scrollRef = useRef(null);

  const send = () => {
    if (!input.trim()) return;
    const id = Date.now();
    setMessages((m) => [...m, { id, kind: 'user', text: input }, { id: id + 1, kind: 'ai-loading' }]);
    setInput('');
    setTimeout(() => {
      setMessages((m) => m.map((x) => x.id === id + 1 ? { ...x, kind: 'ai', text: '추가 질문 감사합니다. 자녀분의 상황을 더 정확히 보려면 GPA 추세, AP/IB 이수 과목, 관심 전공을 알려주세요.' } : x));
    }, 900);
  };

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <TopBar title="AI 학부모 비서" showSearch={false} showBell={false} />

      {/* Safety strip */}
      <div style={{ padding: '8px 16px', background: 'var(--c-bg-secondary)', borderBottom: '1px solid var(--c-border)', display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--c-text-sub)' }}>
        <Icon name="info" size={13} /> Claude AI 기반 상담입니다. 중요한 결정은 검증된 컨설턴트와 함께
      </div>

      <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {messages.map((m) => {
          if (m.kind === 'system') return <SystemCard key={m.id} onProfile={onProfile} />;
          if (m.kind === 'user') return <UserBubble key={m.id} text={m.text} />;
          if (m.kind === 'ai') return m.text ? <AIBubble key={m.id} text={m.text} /> : <AIRecommendCard key={m.id} t={t} />;
          if (m.kind === 'ai-loading') return <AIBubble key={m.id} loading />;
          return null;
        })}
      </div>

      {/* Usage + input */}
      <div style={{ borderTop: '1px solid var(--c-border)', background: 'var(--c-bg-primary)' }}>
        <div style={{ padding: '6px 16px', display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--c-text-tertiary)' }}>
          <Icon name="sparkle" size={12} color="var(--c-primary)" />
          무료 잔여 상담 <b style={{ color: 'var(--c-primary)' }}>3</b> / 5회
        </div>
        <div style={{ padding: '6px 12px 12px', display: 'flex', gap: 8, alignItems: 'flex-end' }}>
          <button style={{ width: 40, height: 40, borderRadius: 20, border: '1px solid var(--c-border)', background: 'var(--c-bg-primary)', cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--c-text-sub)', flexShrink: 0 }}>
            <Icon name="mic" size={18} />
          </button>
          <textarea value={input} onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder="자녀 입시·진로에 대해 질문해주세요"
            rows={1}
            style={{ flex: 1, minHeight: 40, maxHeight: 100, padding: '10px 14px', borderRadius: 20, border: '1px solid var(--c-border)', background: 'var(--c-bg-secondary)', fontSize: 14, lineHeight: 1.4, color: 'var(--c-text-primary)', outline: 'none', resize: 'none', fontFamily: 'inherit' }} />
          <button onClick={send} disabled={!input.trim()} style={{
            width: 40, height: 40, borderRadius: 20, border: 0, cursor: input.trim() ? 'pointer' : 'default',
            background: input.trim() ? 'var(--c-primary)' : 'var(--c-border)', color: '#fff',
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <Icon name="send" size={18} stroke={2.2} />
          </button>
        </div>
      </div>
    </div>
  );
}

function SystemCard({ onProfile }) {
  return (
    <Card padding={20} style={{ background: 'linear-gradient(135deg, rgba(44,91,255,.06), rgba(0,200,150,.04))', border: '1px solid rgba(44,91,255,.18)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--c-primary)', display: 'grid', placeItems: 'center' }}>
          <Icon name="sparkle" size={18} color="#fff" stroke={2.4} />
        </div>
        <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--c-text-primary)' }}>안녕하세요, 학부모님</div>
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--c-text-primary)', marginBottom: 14, textWrap: 'pretty' }}>
        자녀의 진학·진로에 대해 무엇이든 물어보세요. 1,200건의 합격 데이터와 검증된 학부모 후기를 바탕으로 답변합니다.
      </div>
      <Button kind="tertiary" size="sm" onClick={onProfile} leading={<Icon name="plus" size={14} stroke={2.4} />}>자녀 정보 입력하기</Button>
    </Card>
  );
}

function UserBubble({ text }) {
  return (
    <div style={{ alignSelf: 'flex-end', maxWidth: '82%' }}>
      <div style={{
        padding: '12px 14px', background: 'var(--c-primary)', color: '#fff',
        borderRadius: '16px 16px 4px 16px', fontSize: 14.5, lineHeight: 1.5, textWrap: 'pretty',
      }}>{text}</div>
    </div>
  );
}

function AIBubble({ text, loading }) {
  return (
    <div style={{ alignSelf: 'flex-start', maxWidth: '88%', display: 'flex', gap: 8 }}>
      <div style={{ width: 28, height: 28, borderRadius: 14, background: 'var(--c-primary)', display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>
        <Icon name="sparkle" size={14} color="#fff" stroke={2.4} />
      </div>
      <div style={{
        padding: '12px 14px', background: 'var(--c-bg-primary)',
        borderRadius: '4px 16px 16px 16px', fontSize: 14.5, lineHeight: 1.6, textWrap: 'pretty',
        color: 'var(--c-text-primary)', boxShadow: 'var(--card-shadow)',
      }}>
        {loading ? <Dots /> : text}
      </div>
    </div>
  );
}

function Dots() {
  return (
    <div style={{ display: 'inline-flex', gap: 4 }}>
      {[0, 1, 2].map((i) => (
        <span key={i} style={{
          width: 7, height: 7, borderRadius: 4, background: 'var(--c-text-tertiary)',
          animation: `aiDot 1.2s ${i * 0.18}s infinite`,
        }} />
      ))}
    </div>
  );
}

function AIRecommendCard({ t }) {
  return (
    <div style={{ alignSelf: 'flex-start', maxWidth: '92%', display: 'flex', gap: 8 }}>
      <div style={{ width: 28, height: 28, borderRadius: 14, background: 'var(--c-primary)', display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>
        <Icon name="sparkle" size={14} color="#fff" stroke={2.4} />
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Card padding={16} style={{ borderRadius: '4px 16px 16px 16px' }}>
          <div style={{ fontSize: 14.5, lineHeight: 1.65, color: 'var(--c-text-primary)', textWrap: 'pretty' }}>
            자녀분의 스펙(내신 2.8 / SAT 1450)으로는 다음과 같은 대학들이 가능 범위입니다:
          </div>

          <Tier label="Reach" color="var(--c-danger)" items={['Boston University', 'UC Davis']} />
          <Tier label="Match" color="var(--c-secondary)" items={['Penn State', 'Indiana University Bloomington']} />
          <Tier label="Safety" color="var(--c-success)" items={['Arizona State University']} />

          <div style={{ marginTop: 14, padding: 12, background: 'var(--c-bg-secondary)', borderRadius: 10 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-text-primary)', marginBottom: 6 }}>📌 보강하면 좋을 영역</div>
            <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.65, color: 'var(--c-text-sub)' }}>
              <li>비교과 활동 — 지원 전공 관련 1~2개 더</li>
              <li>에세이 — Common App 메인은 8월 안에 초안</li>
            </ul>
          </div>
        </Card>

        <Card padding={14} style={{ borderRadius: 14 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 10, letterSpacing: '0.02em' }}>📚 관련 합격기 추천</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { t: '내신 3.0 → Boston U 합격기', a: '강남구 고3 학부모' },
              { t: 'SAT 1450으로 가는 길', a: '서초구 고2 학부모' },
            ].map((r, i) => (
              <div key={i} style={{ padding: '10px 12px', background: 'var(--c-bg-secondary)', borderRadius: 8, cursor: 'pointer' }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--c-text-primary)', marginBottom: 2, textWrap: 'pretty' }}>{r.t}</div>
                <div style={{ fontSize: 11.5, color: 'var(--c-text-sub)' }}>{r.a} · 검증 ✓</div>
              </div>
            ))}
          </div>
        </Card>

        <Card padding={14} style={{ borderRadius: 14, background: 'linear-gradient(135deg, rgba(44,91,255,.04), rgba(255,107,53,.04))' }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 10, letterSpacing: '0.02em' }}>💼 더 깊은 상담이 필요하다면</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <Avatar initial="김" bg="#2C5BFF" size={44} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--c-text-primary)' }}>김민서 컨설턴트</div>
              <div style={{ fontSize: 11.5, color: 'var(--c-text-sub)', marginTop: 2 }}>Harvard MBA · 前 입학사정관 · ★ 4.9</div>
            </div>
          </div>
          <Button kind="primary" full size="sm">상담 예약하기 (60분 10만원~)</Button>
        </Card>
      </div>
    </div>
  );
}

function Tier({ label, color, items }) {
  return (
    <div style={{ marginTop: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
        <span style={{ width: 6, height: 6, borderRadius: 3, background: color }} />
        <span style={{ fontSize: 11.5, fontWeight: 800, color, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</span>
      </div>
      <div style={{ paddingLeft: 12, fontSize: 13.5, lineHeight: 1.65, color: 'var(--c-text-primary)' }}>
        {items.join(' · ')}
      </div>
    </div>
  );
}

Object.assign(window, { ConsultantScreen, AIChatScreen });
