// chat.jsx — AI 어시스턴트(채팅). 자연어로 문서 생성·심사·점검을 실제 실행.

const { Icon, Pill, Button } = window.RAlly;

const SUGGEST = [
  '이 트랙 심사해줘',
  '요건 충족됐어?',
  '위험관리계획서 다시 써줘',
  '뭘 만들 수 있어?',
  'GMP 갱신심사가 뭐야?',
];

const Chat = ({ go }) => {
  const trackId = (typeof window !== 'undefined' && window.__RALLY_TRACK) || 1;
  const [msgs, setMsgs] = React.useState([
    { role: 'bot', text: '안녕하세요! RAlly 어시스턴트예요. 문서 생성·가상 심사·요건 점검을 자연어로 시켜보세요.\n예: "이 트랙 심사해줘", "위험관리계획서 다시 써줘", "별표1이 뭐야?"', actions: [] },
  ]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const endRef = React.useRef(null);

  React.useEffect(() => { if (endRef.current) endRef.current.scrollIntoView({ behavior: 'smooth' }); }, [msgs, busy]);

  const send = (text) => {
    const q = (text != null ? text : input).trim();
    if (!q || busy) return;
    setMsgs((m) => [...m, { role: 'me', text: q }]);
    setInput(''); setBusy(true);
    fetch('/api/chat', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: q, track_id: trackId }),
    }).then((r) => r.json()).then((d) => {
      setMsgs((m) => [...m, { role: 'bot', text: d.reply || '...', actions: d.actions || [] }]);
      setBusy(false);
    }).catch(() => {
      setMsgs((m) => [...m, { role: 'bot', text: '연결에 문제가 있어요. 다시 시도해 주세요.', actions: [] }]);
      setBusy(false);
    });
  };
  const doAction = (a) => {
    if (a.track_id) window.__RALLY_TRACK = a.track_id;
    if (a.doc_id) window.__RALLY_DOC = a.doc_id;
    if (a.screen) go(a.screen);
  };

  return (
    <div className="page" style={{ maxWidth: 820, margin: '0 auto', display: 'flex', flexDirection: 'column', height: 'calc(100vh - 120px)' }}>
      <div className="page__head" style={{ marginBottom: 12 }}>
        <div>
          <div className="row" style={{ gap: 8, marginBottom: 6 }}>
            <Pill variant="coral">AI 어시스턴트</Pill>
            <Pill>자연어로 실행</Pill>
          </div>
          <div className="page__title" style={{ fontSize: 22 }}>무엇을 도와드릴까요?</div>
        </div>
      </div>

      {/* 대화 스레드 */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '4px 2px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {msgs.map((m, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: m.role === 'me' ? 'flex-end' : 'flex-start' }}>
            <div style={{ maxWidth: '82%', display: 'flex', gap: 10, flexDirection: m.role === 'me' ? 'row-reverse' : 'row' }}>
              {m.role === 'bot' && (
                <div style={{ width: 30, height: 30, flexShrink: 0, borderRadius: 999, background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', padding: 5 }}><img src="logo_white.svg" alt="RAlly" style={{ width: '100%', height: '100%', objectFit: 'contain' }} /></div>
              )}
              <div>
                <div style={{
                  padding: '11px 14px', borderRadius: 14, fontSize: 14, lineHeight: 1.6, whiteSpace: 'pre-wrap',
                  background: m.role === 'me' ? 'var(--navy)' : 'var(--surface)',
                  color: m.role === 'me' ? '#F0EFE8' : 'var(--ink)',
                  border: m.role === 'me' ? 'none' : '1px solid var(--line)',
                  borderTopLeftRadius: m.role === 'bot' ? 4 : 14, borderTopRightRadius: m.role === 'me' ? 4 : 14,
                }}>{m.text}</div>
                {m.actions && m.actions.length > 0 && (
                  <div className="row" style={{ gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                    {m.actions.map((a, j) => (
                      <Button key={j} variant="soft" size="sm" iconRight="arrow_right" onClick={() => doAction(a)}>{a.label}</Button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
        {busy && (
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ width: 30, height: 30, borderRadius: 999, background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', padding: 5 }}><img src="logo_white.svg" alt="RAlly" style={{ width: '100%', height: '100%', objectFit: 'contain' }} /></div>
            <div className="muted" style={{ padding: '11px 14px', fontSize: 13 }}>처리 중…</div>
          </div>
        )}
        <div ref={endRef} />
      </div>

      {/* 추천 + 입력 */}
      {msgs.length <= 1 && (
        <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
          {SUGGEST.map((s) => (
            <span key={s} onClick={() => send(s)} style={{ cursor: 'pointer', fontSize: 12.5, padding: '6px 11px', borderRadius: 999, border: '1px solid var(--line)', color: 'var(--ink-2)' }}
              onMouseEnter={(e) => (e.currentTarget.style.borderColor = 'var(--coral)')}
              onMouseLeave={(e) => (e.currentTarget.style.borderColor = 'var(--line)')}>{s}</span>
          ))}
        </div>
      )}
      <div className="row" style={{ gap: 8, paddingTop: 8 }}>
        <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
          placeholder="문서 생성·심사·질문을 입력하세요…" disabled={busy}
          style={{ flex: 1, fontFamily: 'inherit', fontSize: 14, padding: '12px 14px', border: '1px solid var(--line)', borderRadius: 10, outline: 'none' }} />
        <Button variant="primary" onClick={() => send()} disabled={busy || !input.trim()}>보내기</Button>
      </div>
      <div className="muted" style={{ fontSize: 11, marginTop: 6, textAlign: 'center' }}>
        실제 백엔드를 호출해 동작합니다. 생성·재작성 문서는 제출 전 RA 검토가 필요합니다.
      </div>
    </div>
  );
};

window.RAlly.Chat = Chat;
