import { useEffect, useRef, useState } from 'react' import type { ChatMetadata } from '../lib/api' import { SCENARIO_QUADRANTS, type DemoCase } from '../content/cases' import type { NegoState } from '../App' export interface Msg { role: 'bot' | 'user' text: string step?: string meta?: ChatMetadata | null } // 내부 스텝 ID → 관람자용 라벨 (엔진 내부명 노출 방지) const STEP_LABELS: Record = { wild_card_1pct: '1% 추가 제안', wild_card_budget: '재원부족 제안', 가격협상_확인_버짓: '가격협상 확인', } const stepLabel = (s: string) => STEP_LABELS[s] ?? s // 봇 스크립트가 한 덩어리 문단일 때 가독성을 위해 2문장씩 끊는다 (표시 전용). // 서버가 이미 넣어둔 줄바꿈은 유지하고, 긴 줄만 종결어미("~다."/"~요.") 경계에서 나눈다. function paragraphize(text: string): string { return text .split('\n') .map((line) => { if (line.length < 90) return line const sentences = line.split(/(?<=[다요]\.)\s+/) if (sentences.length < 3) return line const chunks: string[] = [] for (let i = 0; i < sentences.length; i += 2) chunks.push(sentences.slice(i, i + 2).join(' ')) return chunks.join('\n\n') }) .join('\n') } export function ChatPanel({ messages, nego, busy, started, error, demoCase, cases, finalPrice, onAnswer, onOffer, onRestart, onSelect, }: { messages: Msg[] nego: NegoState busy: boolean started: boolean error: string | null demoCase: DemoCase | null cases: DemoCase[] finalPrice: number | null onAnswer: (label: string) => void onOffer: (v: number) => void onRestart: () => void onSelect: (c: DemoCase) => void }) { const [priceInput, setPriceInput] = useState('') const scroller = useRef(null) useEffect(() => { scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: 'smooth' }) }, [messages, busy]) useEffect(() => setPriceInput(''), [nego.step]) const submitPrice = () => { const v = Number(priceInput.replaceAll(',', '')) if (!Number.isFinite(v) || v <= 0) return onOffer(Math.round(v)) } const savedPct = finalPrice != null && demoCase != null ? Math.round(((demoCase.item_price - finalPrice) / demoCase.item_price) * 1000) / 10 : null return (
{started && demoCase && (
{demoCase.item_name} {!nego.done && ( )}
)}
{!started && (

어떤 시나리오로 협상해 볼까요?

구매 엔진은 상품의 매출 규모와 경쟁 강도에 따라 가격 전략을 다르게 씁니다. 시나리오를 선택하면 해당 조건의 품목으로 협상이 시작됩니다.

{/* 사분면 다이어그램 — Y축: 매출 규모(위=높음), X축: 경쟁 강도(오른쪽=높음) */}
매출 높음 매출 낮음
{[['B', 'A'], ['C', 'D']].flat().map((letter) => { const q = SCENARIO_QUADRANTS.find((x) => x.letter === letter) const c = q && cases.find((x) => x.scenario === q.scenario) if (!q || !c) return null return ( ) })}
경쟁 낮음 경쟁 높음

챗봇은 구매 담당자(MD) 역할이고, 당신은 공급사로서 가격 제안에 응답합니다.

)}
    {messages.map((m, i) => (
  1. {m.role === 'bot' && m.step && (
    {stepLabel(m.step)} {m.meta?.card_id && ( {m.meta.card_id} )}
    )}
    {m.role === 'bot' ? paragraphize(m.text) : m.text}
  2. ))} {busy && (
  3. 담당자가 검토하고 있어요
  4. )}
{error && (
{error} — 엔진 연결을 확인한 뒤 다시 시도해 주세요.
)}
{started && (
{nego.done ? (
{/* 큰 숫자는 좌측 최종 합의가 패널이 담당 — 여기서는 사건만 알린다 */} {finalPrice != null ? (

협상 완료 최종 합의가 {finalPrice.toLocaleString()}원 · −{savedPct}%

) : ( 협상이 종료되었습니다 )}
) : nego.mode === 'price' ? (
{ e.preventDefault(); submitPrice() }}> setPriceInput(e.target.value)} disabled={busy} className="input num min-w-0 flex-1 bg-base-200 text-[15px] focus:outline-primary" />
) : nego.options.length > 0 ? (
{nego.options.map((opt) => ( ))}
) : (

응답을 기다리는 중…

)}
)}
) }