// AIPanel.jsx — 전역 AI 어시스턴트 (우측 사이드 패널). 화면 컨텍스트 기반 채팅.

// ---- 컨텍스트 스토어 ----
let _AICTX = { screen: 'IBK 리스크 인사이트', summary: '', facts: [], suggestions: [] };
function setAIContext(c){ _AICTX = { screen:'IBK 리스크 인사이트', summary:'', facts:[], suggestions:[], ...c }; window.dispatchEvent(new CustomEvent('aictx', { detail:_AICTX })); }
function getAIContext(){ return _AICTX; }
Object.assign(window, { setAIContext, getAIContext });

// ---- 스크립트형 폴백 응답 (LLM 미가용 시) ----
function fallbackAnswer(q, ctx){
  const f = (ctx.facts||[]).slice(0,4).map(x=>'· '+x).join('\n');
  const lead = ctx.summary ? ctx.summary+' ' : '';
  return `현재 보고 계신 **${ctx.screen}** 화면을 기준으로 말씀드릴게요.\n\n${lead}주요 수치는 다음과 같아요.\n${f}\n\n질문하신 내용은 이 데이터를 토대로 살펴봤을 때, 위험액 추이와 한도 소진율을 함께 모니터링하시는 것이 좋아요. 더 구체적으로 알고 싶은 항목을 골라주시면 자세히 설명드릴게요.`;
}

async function askAI(q, ctx, history){
  try {
    const res = await fetch('/api/ai', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ question: q, context: ctx, history: (history||[]).slice(-6) })
    });
    if (res.ok) {
      const data = await res.json();
      if (data.answer && data.answer.trim()) return data.answer.trim();
    }
  } catch(e){ /* fall through to fallback */ }
  await new Promise(r=>setTimeout(r, 650));
  return fallbackAnswer(q, ctx);
}

// 간단 마크다운(**굵게**, 줄바꿈) 렌더
function RichText({ text }){
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return <span>{parts.map((p,i)=> p.startsWith('**') && p.endsWith('**')
    ? <b key={i} style={{ color:T.c900 }}>{p.slice(2,-2)}</b>
    : <React.Fragment key={i}>{p}</React.Fragment>)}</span>;
}
function Bubble({ m }){
  const me = m.role==='user';
  return (
    <div style={{ display:'flex', justifyContent: me?'flex-end':'flex-start' }}>
      <div style={{ maxWidth:'90%', display:'flex', gap:9, flexDirection: me?'row-reverse':'row', alignItems:'flex-start' }}>
        {!me && <div style={{ width:26, height:26, borderRadius:8, flex:'none', background:'linear-gradient(135deg,#0A4FA3,#00A0E0)', display:'flex', alignItems:'center', justifyContent:'center', marginTop:1 }}><Icon name="sparkles" size={15} color="#fff" /></div>}
        <div style={{ background: me?T.blue:T.white, color: me?'#fff':T.c700, border: me?'none':'1px solid '+T.line,
          borderRadius:12, borderTopRightRadius: me?3:12, borderTopLeftRadius: me?12:3, padding:'10px 13px',
          fontFamily:T.font, fontWeight:500, fontSize:13, lineHeight:1.7, textAlign:'left', whiteSpace:'pre-wrap', wordBreak:'keep-all', boxShadow: me?'none':'0 1px 2px rgba(15,23,34,.05)' }}>
          {me ? m.text : <RichText text={m.text} />}
        </div>
      </div>
    </div>);
}

function AIPanel({ open, onClose }){
  const [ctx, setCtx] = React.useState(getAIContext());
  const [msgs, setMsgs] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);
  const inputRef = React.useRef(null);

  React.useEffect(()=>{ const h=e=>setCtx(e.detail); window.addEventListener('aictx',h); return ()=>window.removeEventListener('aictx',h); },[]);
  React.useEffect(()=>{ if(scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; },[msgs, busy]);
  React.useEffect(()=>{ if(open && inputRef.current) setTimeout(()=>inputRef.current.focus(),250); },[open]);

  const send = React.useCallback(async (text)=>{
    const q = (text||'').trim(); if(!q || busy) return;
    setInput('');
    const c = getAIContext();
    setMsgs(m=>[...m, { role:'user', text:q }]);
    setBusy(true);
    const hist = msgs;
    const ans = await askAI(q, c, hist);
    setMsgs(m=>[...m, { role:'ai', text:ans }]);
    setBusy(false);
  },[busy, msgs]);

  return (
    <aside style={{ position:'fixed', top:0, right:0, bottom:0, width:404, background:T.c50, borderLeft:'1px solid '+T.line,
      boxShadow:'-8px 0 28px rgba(15,23,34,.08)', zIndex:60, display:'flex', flexDirection:'column',
      transform: open?'translateX(0)':'translateX(100%)', transition:'transform .28s cubic-bezier(.4,0,.2,1)' }}>
      {/* header */}
      <div style={{ flex:'none', height:58, display:'flex', alignItems:'center', gap:11, padding:'0 16px', background:T.white, borderBottom:'1px solid '+T.line }}>
        <div style={{ width:32, height:32, borderRadius:9, background:'linear-gradient(135deg,#0A4FA3,#00A0E0)', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name="sparkles" size={18} color="#fff" /></div>
        <div style={{ lineHeight:1.2 }}>
          <div style={{ fontFamily:T.font, fontWeight:700, fontSize:14, color:T.c900, textAlign:'left' }}>AI 리스크 어시스턴트</div>
          <div style={{ fontFamily:T.font, fontWeight:500, fontSize:11, color:T.c500 }}>화면 내용 기반 분석</div>
        </div>
        <button onClick={onClose} style={{ marginLeft:'auto', border:'1px solid '+T.line, background:T.white, borderRadius:8, padding:7, cursor:'pointer', color:T.c500, display:'flex' }}><Icon name="x" size={17} /></button>
      </div>

      {/* context chip */}
      <div style={{ flex:'none', padding:'10px 16px', background:T.white, borderBottom:'1px solid '+T.line }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, background:T.blueSurface, border:'1px solid '+T.blueLine, borderRadius:9, padding:'8px 11px' }}>
          <Icon name="eye" size={15} color={T.blue} />
          <div style={{ minWidth:0, textAlign:'left' }}>
            <div style={{ fontFamily:T.font, fontWeight:700, fontSize:11.5, color:T.blue600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>분석 대상 · {ctx.screen}</div>
            {ctx.summary && <div style={{ fontFamily:T.font, fontWeight:500, fontSize:10.5, color:T.c500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{ctx.summary}</div>}
          </div>
        </div>
      </div>

      {/* messages */}
      <div ref={scrollRef} style={{ flex:1, overflowY:'auto', padding:'18px 16px', display:'flex', flexDirection:'column', gap:14 }}>
        {msgs.length===0 && (
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <Bubble m={{ role:'ai', text:`안녕하세요, **${ctx.screen}** 화면을 함께 보고 있어요.\n이 화면에 표시된 데이터에 대해 무엇이든 물어보세요. 위험액·한도·시나리오 분석을 도와드릴게요.` }} />
            <div>
              <div style={{ fontFamily:T.font, fontWeight:600, fontSize:11, color:T.c400, margin:'4px 0 9px', textAlign:'left', letterSpacing:'.02em' }}>추천 질문</div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {(ctx.suggestions||[]).map((s,i)=>(
                  <button key={i} onClick={()=>send(s)} style={{ textAlign:'left', border:'1px solid '+T.line, background:T.white, borderRadius:10, padding:'10px 12px', cursor:'pointer',
                    fontFamily:T.font, fontWeight:600, fontSize:12.5, color:T.c700, display:'flex', alignItems:'center', gap:9, boxShadow:'0 1px 2px rgba(15,23,34,.04)' }}
                    onMouseEnter={e=>{e.currentTarget.style.borderColor=T.blueLine; e.currentTarget.style.background=T.blueSurface;}}
                    onMouseLeave={e=>{e.currentTarget.style.borderColor=T.line; e.currentTarget.style.background=T.white;}}>
                    <Icon name="sparkles" size={14} color={T.blue} /><span style={{ flex:1 }}>{s}</span><Icon name="arrowRight" size={14} color={T.c300} /></button>
                ))}
              </div>
            </div>
          </div>
        )}
        {msgs.map((m,i)=><Bubble key={i} m={m} />)}
        {busy && (
          <div style={{ display:'flex', gap:9, alignItems:'center' }}>
            <div style={{ width:26, height:26, borderRadius:8, flex:'none', background:'linear-gradient(135deg,#0A4FA3,#00A0E0)', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name="sparkles" size={15} color="#fff" /></div>
            <div style={{ background:T.white, border:'1px solid '+T.line, borderRadius:12, borderTopLeftRadius:3, padding:'12px 14px', display:'flex', gap:5 }}>
              {[0,1,2].map(i=><span key={i} className="ai-dot" style={{ width:6, height:6, borderRadius:9, background:T.c400, animationDelay:i*0.16+'s' }} />)}
            </div>
          </div>
        )}
      </div>

      {/* quick chips when conversation started */}
      {msgs.length>0 && (ctx.suggestions||[]).length>0 && (
        <div style={{ flex:'none', padding:'0 14px 8px', display:'flex', gap:7, overflowX:'auto' }}>
          {ctx.suggestions.slice(0,3).map((s,i)=>(
            <button key={i} onClick={()=>send(s)} disabled={busy} style={{ flex:'none', border:'1px solid '+T.line, background:T.white, borderRadius:999, padding:'6px 11px', cursor:busy?'default':'pointer',
              fontFamily:T.font, fontWeight:600, fontSize:11.5, color:T.c600, whiteSpace:'nowrap', opacity:busy?.5:1 }}>{s.length>20?s.slice(0,19)+'…':s}</button>
          ))}
        </div>
      )}

      {/* input */}
      <div style={{ flex:'none', padding:'12px 14px 14px', background:T.white, borderTop:'1px solid '+T.line }}>
        <div style={{ display:'flex', alignItems:'flex-end', gap:8, background:T.c100, border:'1px solid '+T.c250, borderRadius:12, padding:'8px 8px 8px 13px' }}>
          <textarea ref={inputRef} value={input} rows={1} placeholder="이 화면에 대해 질문해 보세요…"
            onChange={e=>setInput(e.target.value)}
            onKeyDown={e=>{ if(e.key==='Enter' && !e.shiftKey){ e.preventDefault(); send(input); } }}
            style={{ flex:1, border:0, outline:'none', resize:'none', background:'transparent', fontFamily:T.font, fontWeight:500, fontSize:13, color:T.c800, lineHeight:1.5, maxHeight:96, paddingTop:3 }} />
          <button onClick={()=>send(input)} disabled={busy||!input.trim()} style={{ flex:'none', border:0, borderRadius:9, width:34, height:34, cursor:(busy||!input.trim())?'default':'pointer',
            background:(busy||!input.trim())?T.c250:T.blue, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', transition:'background .15s' }}><Icon name="arrowRight" size={17} stroke={2.2} /></button>
        </div>
        <div style={{ fontFamily:T.font, fontWeight:500, fontSize:10, color:T.c400, marginTop:7, textAlign:'center' }}>AI가 생성한 분석으로 참고용이며, 투자 판단의 근거가 아니에요.</div>
      </div>
    </aside>);
}
Object.assign(window, { AIPanel });
