// Chatbot — professional consultant tone
function MsecmChatbot({ accent }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { role: 'bot', text: '안녕하십니까. MSECM 컨설팅 어시스턴트입니다.\n교육 프로그램, DX 컨설팅, 자료실 등 무엇이든 문의해주십시오.' },
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  const suggestions = [
    'DX 교육 도입 절차가 궁금합니다',
    'AI 부트캠프 운영 사례를 보여주세요',
    '자료실에서 가장 인기 있는 eBook은?',
  ];

  async function send(text) {
    const q = (text ?? input).trim();
    if (!q || loading) return;
    setMessages(m => [...m, { role: 'user', text: q }]);
    setInput('');
    setLoading(true);
    // Vercel 등 외부 호스팅에선 window.claude API가 없음 — placeholder 안내로 폴백
    if (typeof window.claude?.complete !== 'function') {
      setTimeout(() => {
        setMessages(m => [...m, { role: 'bot', text: '문의 주셔서 감사합니다. 어시스턴트는 정식 오픈 준비 중입니다. 빠른 상담이 필요하시면 055-275-8855 또는 msecm@msecm.co.kr 로 연락해주십시오.' }]);
        setLoading(false);
      }, 800);
      return;
    }
    try {
      const system = `당신은 MSECM이라는 한국의 교육·디지털 전환 컨설팅 전문 기업의 공식 안내 어시스턴트입니다.
차분하고 전문적인 컨설턴트 톤으로, 격식 있는 '~합니다' 체로 한국어로만 답합니다.
한 번에 3~4문장 이내로 간결하게, 필요시 짧은 목록으로 답합니다.
MSECM은 ① 교육 컨설팅 ② DX 인재 양성 ③ 에듀테크 플랫폼(M.Lab) ④ 공공·정책 사업의 4개 사업 영역을 보유하며,
삼성·LG·SK·현대차·교육부·과기정통부 등을 주요 고객으로 합니다. 누적 프로젝트 420건 이상, 연 누적 교육생 24만 명 이상입니다.
답을 모르는 사실은 추정하지 말고, "별도 상담을 통해 안내드리겠습니다"라고 답합니다.`;
      const reply = await window.claude.complete({
        messages: [
          { role: 'user', content: `[SYSTEM]\n${system}\n\n[질문]\n${q}` }
        ]
      });
      setMessages(m => [...m, { role: 'bot', text: reply }]);
    } catch (e) {
      setMessages(m => [...m, { role: 'bot', text: '잠시 응답이 지연되고 있습니다. 다시 시도해주십시오.' }]);
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      {/* Launcher */}
      <button
        onClick={() => setOpen(o => !o)}
        aria-label="문의하기"
        style={{
          position: 'fixed', right: 24, bottom: 24, zIndex: 9990,
          width: 60, height: 60, borderRadius: '50%',
          background: accent, color: '#fff', border: 'none',
          boxShadow: '0 12px 40px rgba(30,64,175,.35), 0 0 0 4px rgba(255,255,255,.6)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'transform .25s cubic-bezier(.2,.8,.2,1)',
          transform: open ? 'rotate(180deg) scale(.92)' : 'scale(1)',
        }}>
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M6 18L18 6"/></svg>
        ) : (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
        )}
      </button>

      {/* Panel */}
      <div style={{
        position: 'fixed',
        ...(isMobile
          ? { left: 8, right: 8, bottom: 8, top: 8, width: 'auto', height: 'auto', borderRadius: 16 }
          : { right: 24, bottom: 100, width: 380, maxWidth: 'calc(100vw - 48px)', height: 540, maxHeight: 'calc(100vh - 140px)', borderRadius: 20 }),
        zIndex: 9991,
        background: 'rgba(255,255,255,.92)',
        backdropFilter: 'blur(40px) saturate(180%)', WebkitBackdropFilter: 'blur(40px) saturate(180%)',
        border: '0.5px solid rgba(0,0,0,.08)',
        boxShadow: '0 30px 80px rgba(10,23,41,.18), 0 0 0 .5px rgba(255,255,255,.4) inset',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        transform: open ? 'translateY(0) scale(1)' : 'translateY(20px) scale(.96)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transformOrigin: 'bottom right',
        transition: 'transform .35s cubic-bezier(.2,.8,.2,1), opacity .25s',
      }}>
        {/* Header */}
        <div style={{ padding: '18px 22px 14px', borderBottom: '0.5px solid rgba(0,0,0,.06)', display:'flex', alignItems:'center', gap:12 }}>
          <div style={{ width: 38, height: 38, borderRadius: '50%', background: '#fff', display:'flex', alignItems:'center', justifyContent:'center', overflow: 'hidden', flexShrink: 0, border: '0.5px solid rgba(10,23,41,.08)' }}>
            <img src="/assets/msecm-logo.avif" alt="MSECM" style={{ width: '78%', height: '78%', objectFit: 'contain' }} />
          </div>
          <div style={{ flex:1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#0a1729', letterSpacing: '-.01em' }}>MSECM 컨설팅 어시스턴트</div>
            <div style={{ fontSize: 11.5, color: 'rgba(10,23,41,.55)', display: 'flex', alignItems:'center', gap: 5, marginTop: 2 }}>
              <span style={{ width:6, height:6, borderRadius:'50%', background:'#22c55e', display:'inline-block' }}></span>
              지금 응답 가능
            </div>
          </div>
          {/* 닫기 버튼 — 모바일 풀스크린에선 필수, 데스크탑에서도 편의 제공 */}
          <button onClick={() => setOpen(false)} aria-label="대화 닫기" style={{
            width: 32, height: 32, borderRadius: 10, border: 'none',
            background: 'rgba(10,23,41,.04)', color: 'rgba(10,23,41,.6)',
            cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            padding: 0, flexShrink: 0,
            transition: 'background .2s, color .2s',
          }}
          onMouseOver={e => { e.currentTarget.style.background = 'rgba(10,23,41,.08)'; e.currentTarget.style.color = '#0a1729'; }}
          onMouseOut={e => { e.currentTarget.style.background = 'rgba(10,23,41,.04)'; e.currentTarget.style.color = 'rgba(10,23,41,.6)'; }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M6 18L18 6"/></svg>
          </button>
        </div>

        {/* Messages */}
        <div ref={scrollRef} style={{ flex:1, overflowY:'auto', padding: '18px 18px 8px', display:'flex', flexDirection:'column', gap: 10 }}>
          {messages.map((m, i) => (
            <div key={i} style={{
              alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
              maxWidth: '82%',
              padding: '10px 14px', borderRadius: 14,
              background: m.role === 'user' ? accent : 'rgba(10,23,41,.05)',
              color: m.role === 'user' ? '#fff' : '#0a1729',
              fontSize: 13.5, lineHeight: 1.55, whiteSpace: 'pre-wrap',
              borderBottomRightRadius: m.role === 'user' ? 4 : 14,
              borderBottomLeftRadius: m.role === 'bot' ? 4 : 14,
            }}>{m.text}</div>
          ))}
          {loading && (
            <div style={{ alignSelf:'flex-start', padding: '10px 14px', borderRadius: 14, background:'rgba(10,23,41,.05)', display:'flex', gap:4 }}>
              {[0,1,2].map(i => (
                <span key={i} style={{ width:6, height:6, borderRadius:'50%', background:'rgba(10,23,41,.4)', animation:`msecmDot 1.2s ${i*.15}s infinite ease-in-out` }}></span>
              ))}
            </div>
          )}
          {messages.length === 1 && !loading && (
            <div style={{ display:'flex', flexDirection:'column', gap:6, marginTop: 8 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.08em', color:'rgba(10,23,41,.4)', textTransform:'uppercase', marginBottom:2 }}>추천 질문</div>
              {suggestions.map(s => (
                <button key={s} onClick={() => send(s)} style={{
                  textAlign:'left', padding:'10px 12px', borderRadius:10, border:'0.5px solid rgba(10,23,41,.1)',
                  background:'rgba(255,255,255,.6)', fontSize: 12.5, color:'#0a1729', cursor:'pointer', fontFamily:'inherit',
                }}>{s}</button>
              ))}
            </div>
          )}
        </div>

        {/* Input */}
        <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{ padding: '12px 14px 14px', borderTop: '0.5px solid rgba(0,0,0,.06)', display:'flex', gap: 8 }}>
          <input
            value={input} onChange={e => setInput(e.target.value)}
            placeholder="무엇이든 문의해주십시오"
            style={{
              flex:1, height: 40, padding: '0 14px', borderRadius: 12,
              border:'0.5px solid rgba(10,23,41,.12)', fontSize: 13.5, fontFamily:'inherit',
              background: 'rgba(255,255,255,.7)', outline:'none', color:'#0a1729'
            }}
          />
          <button type="submit" disabled={!input.trim() || loading} style={{
            width: 40, height: 40, borderRadius: 12, border:'none',
            background: accent, color:'#fff', cursor:'pointer',
            opacity: (!input.trim() || loading) ? .35 : 1,
            display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
          </button>
        </form>
      </div>

      <style>{`@keyframes msecmDot{0%,80%,100%{transform:translateY(0);opacity:.4}40%{transform:translateY(-4px);opacity:1}}`}</style>
    </>
  );
}

window.MsecmChatbot = MsecmChatbot;
