<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Report Agent — Canifa AI</title>
<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useRef, useEffect, useCallback } = React;
const ChartJS = Chart;

ChartJS.register(
ChartJS.CategoryScale, ChartJS.LinearScale, ChartJS.BarElement,
ChartJS.LineElement, ChartJS.PointElement, ChartJS.ArcElement,
ChartJS.Filler, ChartJS.Tooltip, ChartJS.Legend
)

const PAL = ["#2563EB","#059669","#D97706","#DC2626","#7C3AED","#0891B2","#EA580C","#DB2777"]
const rgba = (hex, a) => {
const [r,g,b] = [hex.slice(1,3),hex.slice(3,5),hex.slice(5,7)].map(v=>parseInt(v,16))
return `rgba(${r},${g},${b},${a})`
}

const SUGGESTIONS = [
"Báo cáo hiệu suất chatbot AI Canifa tháng 3/2026",
"Phân tích chi phí sử dụng LLM 30 ngày qua",
"Báo cáo chất lượng trả lời chatbot (scores & feedback)",
"Phân tích sản phẩm bán chạy nhất trên StarRocks",
]

// ─── CHARTS ──────────────────────────────────────────────────────────────────
const chartBase = (extra={}) => ({
responsive: true, maintainAspectRatio: false,
animation: { duration: 500, easing: "easeInOutQuart" },
plugins: {
legend: { display: false },
tooltip: { backgroundColor: "#1E293B", titleColor: "#94A3B8", bodyColor: "#F8FAFC", padding: 11, cornerRadius: 8,
titleFont:{size:10}, bodyFont:{size:12,weight:"600"} }
},
scales: {
x: { grid:{display:false}, border:{display:false}, ticks:{color:"#94A3B8",font:{size:10}} },
y: { grid:{color:"rgba(0,0,0,.05)"}, border:{display:false}, ticks:{color:"#94A3B8",font:{size:10}} }
},
...extra
})

function useChart(ref, build, deps) {
const ch = useRef(null)
useEffect(() => {
if (!ref.current) return
ch.current?.destroy()
ch.current = build(ref.current)
return () => ch.current?.destroy()
}, deps)
}

function InlineChart({ chart }) {
const ref = useRef(null)
const { type, labels=[], datasets=[], segments=[] } = chart

useChart(ref, (el) => {
if (type === "donut") {
return new ChartJS(el, {
type: "doughnut",
data: { labels: segments.map(s=>s.name), datasets: [{ data: segments.map(s=>s.value), backgroundColor: PAL, borderWidth:
0, hoverOffset: 4 }] },
options: { responsive:true, maintainAspectRatio:false, cutout:"68%", animation:{duration:500}, plugins:{ legend:{
display:true, position:"right", labels:{font:{size:11},color:"#475569",boxWidth:10,padding:10} }, tooltip:{
backgroundColor:"#1E293B",titleColor:"#94A3B8",bodyColor:"#F8FAFC",padding:10,cornerRadius:8 } } }
})
}
if (type === "hbar") {
return new ChartJS(el, {
type: "bar",
data: { labels, datasets: datasets.map((d,i)=>({ data:d.values,
backgroundColor:labels.map((_,j)=>rgba(PAL[j%PAL.length],.75)),
hoverBackgroundColor:labels.map((_,j)=>PAL[j%PAL.length]), borderRadius:4, borderSkipped:false })) },
options: { ...chartBase(), indexAxis:"y", scales:{ x:{
grid:{color:"rgba(0,0,0,.05)"},border:{display:false},ticks:{color:"#94A3B8",font:{size:10}} }, y:{
grid:{display:false},border:{display:false},ticks:{color:"#334155",font:{size:11,weight:"500"}} } } }
})
}
if (type === "area") {
const ctx = el.getContext("2d")
return new ChartJS(el, {
type: "line",
data: { labels, datasets: datasets.map((d,i) => {
const c = PAL[i%PAL.length], g = ctx.createLinearGradient(0,0,0,260)
g.addColorStop(0,rgba(c,.15)); g.addColorStop(1,rgba(c,0))
return { label:d.label, data:d.values, borderColor:c, backgroundColor:g, fill:true, borderWidth:2, tension:0.4,
pointRadius:3, pointBackgroundColor:c, pointBorderWidth:0 }
}) },
options: { ...chartBase(), plugins:{ ...chartBase().plugins, legend:{ display:datasets.length>1, position:"top",
labels:{font:{size:10},color:"#64748B",boxWidth:9,padding:10} } } }
})
}
if (type === "line") {
return new ChartJS(el, {
type: "line",
data: { labels, datasets: datasets.map((d,i)=>({ label:d.label, data:d.values, borderColor:PAL[i%PAL.length],
backgroundColor:"transparent", borderWidth:2.5, tension:0.4, pointRadius:3, pointBackgroundColor:PAL[i%PAL.length],
pointBorderWidth:0 })) },
options: { ...chartBase(), plugins:{ ...chartBase().plugins, legend:{ display:datasets.length>1, position:"top",
labels:{font:{size:10},color:"#64748B",boxWidth:9,padding:10} } } }
})
}
// bar default
return new ChartJS(el, {
type: "bar",
data: { labels, datasets: datasets.map((d,i)=>({ label:d.label, data:d.values,
backgroundColor:rgba(PAL[i%PAL.length],.75), hoverBackgroundColor:PAL[i%PAL.length], borderRadius:5, borderSkipped:false
})) },
options: { ...chartBase(), plugins:{ ...chartBase().plugins, legend:{ display:datasets.length>1, position:"top",
labels:{font:{size:10},color:"#64748B",boxWidth:9,padding:10} } } }
})
}, [JSON.stringify(chart)])

const h = type==="hbar" ? Math.max(180, (labels.length||4)*38) : 260

return (
<div style={{ margin:"20px 0" }}>
    <p style={{
        fontSize:12,fontWeight:600,color:"#64748B",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:10 }}>
        {chart.title}
    </p>
    <div style={{ height:h, background:"#FAFBFC", borderRadius:10, padding:"16px", border:"1px solid #E8ECF0" }}>
        <canvas ref={ref} />
    </div>
    {chart.caption && (
    <p style={{ fontSize:12,color:"#94A3B8",marginTop:8,fontStyle:"italic",lineHeight:1.5 }}>
        Hình: {chart.caption}
    </p>
    )}
</div>
)
}

function InlineTable({ table }) {
const { columns=[], rows=[] } = table
return (
<div style={{ margin:"20px 0" }}>
    {table.title && <p style={{
        fontSize:12,fontWeight:600,color:"#64748B",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:10 }}>
        {table.title}</p>}
    <div style={{ overflowX:"auto", border:"1px solid #E8ECF0", borderRadius:10 }}>
        <table style={{ width:"100%", borderCollapse:"collapse", fontSize:13 }}>
            <thead>
                <tr style={{ background:"#F8FAFC" }}>
                    {columns.map((c,i) => <th key={i} style={{ textAlign:"left",padding:"10px 16px",color:"#475569",fontWeight:600,fontSize:11,borderBottom:"1px solid #E8ECF0",whiteSpace:"nowrap" }}>{c}</th>)}
                </tr>
            </thead>
            <tbody>
                {rows.map((row,i) => (
                <tr key={i} style={{ borderBottom:i<rows.length-1?"1px solid #F1F5F9":"none" }} onMouseEnter={e=>
                    e.currentTarget.style.background="#F8FAFC"}
                    onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                    {row.map((cell,j) => <td key={j} style={{ padding:"10px 16px",color:j===0?"#0F172A":"#475569",fontWeight:j===0?600:400 }}>{cell}</td>)}
                </tr>
                ))}
            </tbody>
        </table>
    </div>
    {table.caption && <p style={{ fontSize:12,color:"#94A3B8",marginTop:8,fontStyle:"italic" }}>Bảng: {table.caption}
    </p>}
</div>
)
}

function Callout({ type, text }) {
const styles = {
info: { bg:"#EFF6FF", border:"#BFDBFE", icon:"ℹ", iconBg:"#DBEAFE", iconColor:"#1D4ED8", textColor:"#1E40AF" },
warning: { bg:"#FFFBEB", border:"#FDE68A", icon:"!", iconBg:"#FEF3C7", iconColor:"#D97706", textColor:"#92400E" },
success: { bg:"#F0FDF4", border:"#BBF7D0", icon:"✓", iconBg:"#DCFCE7", iconColor:"#15803D", textColor:"#14532D" },
}
const s = styles[type]||styles.info
return (
<div style={{ background:s.bg, border:`1px solid ${s.border}`, borderRadius:10, padding:"14px 16px", margin:"20px 0",
    display:"flex", gap:12, alignItems:"flex-start" }}>
    <div style={{
        width:22,height:22,borderRadius:"50%",background:s.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:11,fontWeight:700,color:s.iconColor
        }}>{s.icon}</div>
    <p style={{ fontSize:13,color:s.textColor,lineHeight:1.6,margin:0 }}>{text}</p>
</div>
)
}

// ─── REPORT DOCUMENT ─────────────────────────────────────────────────────────
function ReportDoc({ report, onExport }) {
const now = new Date().toLocaleDateString("vi-VN", { year:"numeric", month:"long", day:"numeric" })
const TREND = { up:"↑", down:"↓", neutral:"→" }
const TREND_COLOR = { up:"#059669", down:"#DC2626", neutral:"#64748B" }

return (
<div style={{ maxWidth:780, margin:"0 auto", padding:"32px 24px 60px", fontFamily:"'Georgia',serif" }}>

    {/* ── Cover ── */}
    <div style={{ borderBottom:"3px solid #0F172A", paddingBottom:32, marginBottom:40 }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:28 }}>
            <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                <div style={{
                    width:36,height:36,borderRadius:9,background:"linear-gradient(135deg,#1E40AF,#4338CA)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,color:"white"
                    }}>✦</div>
                <div>
                    <p style={{
                        fontSize:11,fontWeight:700,color:"#6366F1",textTransform:"uppercase",letterSpacing:"0.08em",margin:0
                        }}>ReportAI Agent</p>
                    <p style={{ fontSize:10,color:"#94A3B8",margin:0 }}>{report.organization||"Phòng Phân tích"}</p>
                </div>
            </div>
            <div style={{ textAlign:"right" }}>
                <p style={{ fontSize:10,color:"#94A3B8",margin:"0 0 2px" }}>Ngày xuất bản</p>
                <p style={{ fontSize:12,fontWeight:600,color:"#374151",margin:0 }}>{now}</p>
            </div>
        </div>

        <div style={{ background:"linear-gradient(135deg,#F8FAFF,#EEF2FF)", borderRadius:14, padding:"28px 28px 24px",
            border:"1px solid #E0E7FF" }}>
            <div style={{
                display:"inline-flex",alignItems:"center",gap:7,background:"#E0E7FF",borderRadius:100,padding:"4px 12px",marginBottom:14 }}>
                <div style={{ width:6,height:6,borderRadius:"50%",background:"#4338CA" }} />
                <span style={{
                    fontSize:10,fontWeight:700,color:"#3730A3",textTransform:"uppercase",letterSpacing:"0.07em" }}>Báo
                    cáo phân tích — Dữ liệu thật</span>
            </div>
            <h1 style={{ fontSize:28,fontWeight:700,color:"#0F172A",lineHeight:1.25,margin:"0 0 10px",letterSpacing:"-0.02em",fontFamily:"'Georgia',serif" }}>{report.title}</h1>
            <p style={{ fontSize:15,color:"#475569",margin:"0 0 20px",lineHeight:1.5,fontFamily:"system-ui,sans-serif"
                }}>{report.subtitle}</p>
            <div style={{ display:"flex", gap:20, flexWrap:"wrap" }}>
                {[["Kỳ báo cáo",report.period],["Người lập",report.prepared_by]].map(([k,v])=>v&&(
                <div key={k}>
                    <p style={{ fontSize:10,color:"#94A3B8",margin:"0 0 2px",textTransform:"uppercase",letterSpacing:"0.06em",fontFamily:"system-ui" }}>{k}</p>
                    <p style={{ fontSize:12.5,fontWeight:600,color:"#374151",margin:0,fontFamily:"system-ui" }}>{v}</p>
                </div>
                ))}
            </div>
        </div>
    </div>

    {/* ── Highlights row ── */}
    {report.highlights?.length>0 && (
    <div style={{ display:"flex", gap:12, flexWrap:"wrap", marginBottom:36 }}>
        {report.highlights.map((h,i) => (
        <div key={i} style={{ flex:"1 1 120px",background:"#fff",borderRadius:10,padding:"14px 16px",border:"1px solid #E8ECF0",borderTop:`3px solid ${PAL[i%PAL.length]}` }}>
            <p style={{
                fontSize:9.5,fontWeight:700,color:"#94A3B8",textTransform:"uppercase",letterSpacing:"0.08em",margin:"0 0 6px",fontFamily:"system-ui" }}>{h.label}</p>
            <p style={{ fontSize:22,fontWeight:800,color:"#0F172A",margin:"0 0 4px",letterSpacing:"-0.03em",fontFamily:"system-ui" }}>{h.value}</p>
            <span style={{ fontSize:11,color:TREND_COLOR[h.trend]||"#64748B",fontFamily:"system-ui",fontWeight:600
                }}>{TREND[h.trend]} {h.trend==="up"?"Tăng":h.trend==="down"?"Giảm":"Ổn định"}</span>
        </div>
        ))}
    </div>
    )}

    {/* ── Executive Summary ── */}
    <div style={{ background:"#F8FAFF", borderLeft:"4px solid #4338CA", borderRadius:"0 10px 10px 0", padding:"20px 24px", marginBottom:36 }}>
        <p style={{
            fontSize:10,fontWeight:700,color:"#4338CA",textTransform:"uppercase",letterSpacing:"0.08em",margin:"0 0 10px",fontFamily:"system-ui" }}>Tóm tắt điều hành</p>
        <p style={{ fontSize:14,color:"#1E293B",lineHeight:1.8,margin:0 }}>{report.executive_summary}</p>
    </div>

    {/* ── Table of Contents ── */}
    <div style={{ marginBottom:36, padding:"16px 20px", background:"#FAFBFC", borderRadius:10, border:"1px solid #E8ECF0" }}>
        <p style={{
            fontSize:10,fontWeight:700,color:"#64748B",textTransform:"uppercase",letterSpacing:"0.08em",margin:"0 0 12px",fontFamily:"system-ui" }}>Mục lục</p>
        <div style={{ display:"flex", flexDirection:"column", gap:6 }}>
            {report.sections?.map((s,i) => (
            <div key={i} style={{ display:"flex", alignItems:"center", gap:10 }}>
                <span style={{ fontSize:12,fontWeight:600,color:"#4338CA",fontFamily:"system-ui",width:20
                    }}>{s.number}.</span>
                <span style={{ fontSize:13,color:"#334155",flex:1 }}>{s.title}</span>
                <div style={{ flex:1,borderBottom:"1px dotted #CBD5E1",margin:"0 8px" }} />
                <span style={{ fontSize:12,color:"#94A3B8",fontFamily:"system-ui" }}>{i+1+3}</span>
            </div>
            ))}
        </div>
    </div>

    {/* ── Sections ── */}
    {report.sections?.map((section, si) => (
    <div key={section.id||si} style={{ marginBottom:48 }}>
        <div style={{ display:"flex", alignItems:"center", gap:14, marginBottom:18, paddingBottom:12, borderBottom:"1px solid #E8ECF0" }}>
            <div style={{
                width:36,height:36,borderRadius:10,background:`linear-gradient(135deg,${PAL[si%PAL.length]},${PAL[(si+1)%PAL.length]})`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:800,color:"white",flexShrink:0,fontFamily:"system-ui"
                }}>
                {section.number}
            </div>
            <h2 style={{ fontSize:20,fontWeight:700,color:"#0F172A",margin:0,letterSpacing:"-0.01em" }}>{section.title}
            </h2>
        </div>

        {section.paragraphs?.map((p, pi) => (
        <p key={pi} style={{ fontSize:14,color:"#1E293B",lineHeight:1.85,marginBottom:14,textAlign:"justify" }}>{p}</p>
        ))}

        {section.callout &&
        <Callout type={section.callout.type} text={section.callout.text} />}

        {section.chart &&
        <InlineChart chart={section.chart} />}

        {section.table &&
        <InlineTable table={section.table} />}
    </div>
    ))}

    {/* ── Conclusion ── */}
    {report.conclusion && (
    <div style={{ marginBottom:36 }}>
        <h2 style={{ fontSize:18,fontWeight:700,color:"#0F172A",marginBottom:14,paddingBottom:10,borderBottom:"1px solid #E8ECF0" }}>Kết luận</h2>
        <p style={{ fontSize:14,color:"#1E293B",lineHeight:1.85 }}>{report.conclusion}</p>
    </div>
    )}

    {/* ── Recommendations ── */}
    {report.recommendations?.length>0 && (
    <div style={{ background:"#F0FDF4", border:"1px solid #BBF7D0", borderRadius:14, padding:"22px 24px",
        marginBottom:36 }}>
        <p style={{
            fontSize:10,fontWeight:700,color:"#15803D",textTransform:"uppercase",letterSpacing:"0.08em",margin:"0 0 14px",fontFamily:"system-ui" }}>✓ Khuyến nghị</p>
        <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
            {report.recommendations.map((r,i) => (
            <div key={i} style={{ display:"flex", gap:12, alignItems:"flex-start" }}>
                <div style={{
                    width:22,height:22,borderRadius:"50%",background:"#DCFCE7",display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,color:"#15803D",flexShrink:0,marginTop:1,fontFamily:"system-ui"
                    }}>{i+1}</div>
                <p style={{ fontSize:13.5,color:"#14532D",lineHeight:1.65,margin:0 }}>{r}</p>
            </div>
            ))}
        </div>
    </div>
    )}

    {/* ── Footer ── */}
    <div style={{ borderTop:"1px solid #E8ECF0", paddingTop:20, display:"flex", justifyContent:"space-between",
        alignItems:"center" }}>
        <p style={{ fontSize:11,color:"#94A3B8",fontFamily:"system-ui",margin:0 }}>Generated by ReportAI Agent · Powered by
            Canifa AI Platform</p>
        <button onClick={onExport} style={{ background:"#0F172A",color:"white",border:"none",borderRadius:8,padding:"8px 18px",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"system-ui",display:"flex",alignItems:"center",gap:7
            }}>
            🖨 In / Lưu PDF
        </button>
    </div>
</div>
)
}

// ─── AGENT STEP CARD (shows tool calls in sidebar) ───────────────────────────
function AgentStep({ step }) {
const ICONS = {
  thinking: "🧠",
  plan_ready: "📋",
  tool_call: "🔧",
  tool_result: "📊",
  section_ready: "📄",
  report_complete: "✅",
  reflect: "🔍",
  error: "❌",
  done: "🏁",
}
const icon = ICONS[step.type] || "•"

if (step.type === "tool_call") {
  return (
    <div style={{ padding:"7px 10px",background:"rgba(99,102,241,.12)",borderRadius:8,fontSize:11.5,color:"#C7D2FE",lineHeight:1.5 }}>
      {icon} Gọi <b style={{color:"#A5B4FC"}}>{step.tool}</b>
      {step.params && Object.keys(step.params).length > 0 && (
        <div style={{ fontSize:10,color:"#818CF8",marginTop:3,fontFamily:"monospace",wordBreak:"break-all" }}>
          {JSON.stringify(step.params).slice(0, 120)}
        </div>
      )}
    </div>
  )
}

if (step.type === "tool_result") {
  return (
    <div style={{ padding:"7px 10px",background:step.success?"rgba(16,185,129,.12)":"rgba(239,68,68,.12)",borderRadius:8,fontSize:11.5,color:step.success?"#6EE7B7":"#FCA5A5",lineHeight:1.5 }}>
      {step.success ? "✅" : "❌"} {step.tool}
      {step.preview?.row_count != null && <span style={{color:"#A7F3D0"}}> — {step.preview.row_count} rows</span>}
      {step.preview?.summary?.total_traces != null && <span style={{color:"#A7F3D0"}}> — {step.preview.summary.total_traces} traces</span>}
      {step.preview?.error && <div style={{color:"#FCA5A5",fontSize:10,marginTop:2}}>{step.preview.error.slice(0,100)}</div>}
    </div>
  )
}

if (step.type === "plan_ready") {
  return (
    <div style={{ padding:"7px 10px",background:"rgba(99,102,241,.08)",borderRadius:8,fontSize:11.5,color:"#C7D2FE",lineHeight:1.5 }}>
      📋 Kế hoạch: <b>{step.tools_count} tools</b>{step.cycle ? ` · vòng ${step.cycle}` : ""}
      {step.thinking && <div style={{fontSize:10,color:"#A5B4FC",marginTop:3,fontStyle:"italic"}}>{step.thinking.slice(0,150)}</div>}
    </div>
  )
}

if (step.type === "reflect") {
  return (
    <div style={{ padding:"7px 10px",background:step.data_sufficient?"rgba(16,185,129,.12)":"rgba(245,158,11,.12)",borderRadius:8,fontSize:11.5,color:step.data_sufficient?"#6EE7B7":"#FCD34D",lineHeight:1.5 }}>
      {step.data_sufficient ? "✅" : "🔍"} Đánh giá vòng {step.cycle}: {step.data_sufficient ? <b>Dữ liệu đủ!</b> : <b>Cần thêm dữ liệu</b>}
      {step.thinking && <div style={{fontSize:10,color:step.data_sufficient?"#A7F3D0":"#FDE68A",marginTop:3,fontStyle:"italic"}}>{step.thinking.slice(0,150)}</div>}
      {step.missing?.length > 0 && <div style={{fontSize:10,color:"#FCA5A5",marginTop:2}}>Thiếu: {step.missing.join(", ").slice(0,100)}</div>}
      {step.quality_issues?.length > 0 && <div style={{fontSize:10,color:"#FDBA74",marginTop:2}}>⚠️ {step.quality_issues.join(", ").slice(0,100)}</div>}
    </div>
  )
}

const text = step.step || step.message || (step.type === "done" ? "Hoàn thành!" : step.type)
return (
  <div style={{ padding:"6px 10px",background:"rgba(255,255,255,.05)",borderRadius:8,fontSize:11.5,color:"#D1D5DB",lineHeight:1.5 }}>
    {icon} {text} 
  </div>
)
}

// ─── GUIDE ────────────────────────────────────────────────────────────────────
function Guide() {
const S = (props) => <div style={{marginBottom:40,...props.style}}>{props.children}</div>
const Label = ({children}) => <div style={{display:"inline-flex",alignItems:"center",gap:8,fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.1em",color:"#6366F1",marginBottom:12}}><span style={{width:8,height:8,borderRadius:"50%",background:"#6366F1"}}/>{children}</div>
const Card = ({icon,bg,border,title,desc,sub}) => <div style={{background:"#fff",border:`1.5px solid ${border||'#E2E8F0'}`,borderRadius:14,padding:20}}><div style={{width:40,height:40,borderRadius:10,background:bg,border:`1px solid ${border}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,marginBottom:12}}>{icon}</div><h3 style={{fontSize:14,fontWeight:700,color:"#0F172A",marginBottom:6}}>{title}</h3><p style={{fontSize:12.5,color:"#64748B",lineHeight:1.6}}>{desc}</p>{sub&&<p style={{marginTop:8,fontSize:11,color:"#94A3B8"}}>{sub}</p>}</div>
const FlowStep = ({icon,bg,border,title,desc,tags}) => <div style={{display:"flex",gap:16,alignItems:"flex-start",marginBottom:8}}><div style={{width:44,height:44,borderRadius:12,background:bg,border:`1.5px solid ${border}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,flexShrink:0}}>{icon}</div><div style={{flex:1,paddingBottom:20}}><h3 style={{fontSize:14,fontWeight:700,color:"#0F172A",marginBottom:4}}>{title}</h3><p style={{fontSize:12.5,color:"#64748B",lineHeight:1.6}}>{desc}</p>{tags&&<div style={{display:"flex",gap:6,marginTop:6,flexWrap:"wrap"}}>{tags.map((t,i)=><span key={i} style={{fontSize:10,fontWeight:700,padding:"3px 8px",borderRadius:6,background:t.bg,color:t.color,textTransform:"uppercase",letterSpacing:"0.03em"}}>{t.text}</span>)}</div>}</div></div>

const schemaRows = [
  ["trace_id","VARCHAR","ID unique của trace"],
  ["session_id","VARCHAR","ID phiên hội thoại"],
  ["customer_id","VARCHAR","Mã khách hàng"],
  ["device_id","VARCHAR","ID thiết bị user"],
  ["model_name","VARCHAR","Model LLM (gpt-5.2-codex, gemini-3.1-flash-lite...)"],
  ["trace_latency","DECIMAL","Tổng latency trace (giây)"],
  ["user_latency","DECIMAL","Latency user cảm nhận (giây)"],
  ["input_cost","DECIMAL","Chi phí input tokens (USD)"],
  ["output_cost","DECIMAL","Chi phí output tokens (USD)"],
  ["total_cost","DECIMAL","Tổng chi phí (USD)"],
  ["total_obs","BIGINT","Tổng observations"],
  ["total_obs_error","BIGINT","Observations bị lỗi"],
  ["nb_generation_error","BIGINT","Số lỗi generation"],
  ["is_guest","TINYINT","1=khách vãng lai, 0=đã login"],
  ["traced_at","DATETIME","Thời điểm trace xảy ra"],
]
const typeColor = {VARCHAR:"#4338CA",DECIMAL:"#059669",BIGINT:"#D97706",DATETIME:"#E11D48",TINYINT:"#0284C7"}
const typeBg = {VARCHAR:"#EEF2FF",DECIMAL:"#ECFDF5",BIGINT:"#FEF3C7",DATETIME:"#FFF1F2",TINYINT:"#F0F9FF"}

return (
<div style={{maxWidth:880,margin:"0 auto",padding:"40px 28px 80px",fontFamily:"'Inter',system-ui,sans-serif"}}>
  {/* Hero */}
  <div style={{background:"linear-gradient(135deg,#0F172A,#1E293B 50%,#312E81)",borderRadius:20,padding:"48px 36px 40px",textAlign:"center",color:"white",marginBottom:40,position:"relative",overflow:"hidden"}}>
    <div style={{position:"absolute",inset:0,background:"radial-gradient(circle at 30% 20%, rgba(99,102,241,.2) 0%, transparent 50%), radial-gradient(circle at 70% 80%, rgba(59,130,246,.15) 0%, transparent 50%)"}} />
    <div style={{position:"relative"}}>
      <div style={{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",background:"rgba(99,102,241,.2)",border:"1px solid rgba(99,102,241,.3)",borderRadius:100,fontSize:12,fontWeight:600,color:"#A5B4FC",marginBottom:18}}>📋 Documentation · v2.0</div>
      <h1 style={{fontSize:28,fontWeight:800,letterSpacing:"-0.03em",marginBottom:10}}>AI Report Agent</h1>
      <p style={{fontSize:14,color:"#94A3B8",maxWidth:550,margin:"0 auto",lineHeight:1.7}}>Hướng dẫn chi tiết về luồng hoạt động, kiến trúc ReAct Reflect Loop, và các công cụ mà Agent sử dụng.</p>
    </div>
  </div>

  {/* Overview */}
  <S><Label>Tổng quan</Label>
    <h2 style={{fontSize:20,fontWeight:800,color:"#0F172A",letterSpacing:"-0.02em",marginBottom:14}}>Agent hoạt động như thế nào?</h2>
    <p style={{fontSize:13.5,color:"#475569",lineHeight:1.7,marginBottom:14}}>AI Report Agent sử dụng kiến trúc <b>ReAct (Reasoning + Acting)</b> với cơ chế <b>Reflect Loop</b>. Thay vì chạy cứng một pipeline, Agent tự suy nghĩ, query dữ liệu, đánh giá xem đã đủ chưa, và tự quyết định khi nào dừng lại để viết báo cáo.</p>
    <div style={{padding:"14px 18px",background:"#EEF2FF",border:"1px solid #E0E7FF",borderRadius:12,fontSize:13,color:"#3730A3",display:"flex",gap:12,alignItems:"flex-start"}}>
      <span style={{fontSize:18,flexShrink:0}}>💡</span>
      <div><b>Tại sao dùng Reflect Loop?</b><br/>Pipeline truyền thống (Planner → Tools → Writer) sẽ quyết định tất cả tools từ đầu. Nếu 1 tool lỗi hoặc data thiếu, không có cơ chế bổ sung. Reflect Loop cho phép Agent tự đánh giá và query thêm khi cần.</div>
    </div>
  </S>

  {/* Flow */}
  <S><Label>Luồng hoạt động</Label>
    <h2 style={{fontSize:20,fontWeight:800,color:"#0F172A",letterSpacing:"-0.02em",marginBottom:14}}>ReAct Reflect Loop — Chi tiết</h2>
    <div style={{background:"#fff",border:"1.5px solid #E2E8F0",borderRadius:16,padding:"24px 28px",marginBottom:24}}>
      <pre style={{fontFamily:"'Inter',system-ui",fontSize:12.5,color:"#475569",lineHeight:2.1,whiteSpace:"pre-wrap"}}>{`  📝  User nhập yêu cầu báo cáo
         ↓
  🧠  THINK — Agent phân tích, chọn tools + viết SQL
         ↓
  🔧  ACT — Execute tools song song (asyncio.gather)
         ↓
  👁️  OBSERVE — Thu thập kết quả từ các tools
         ↓
  🔍  REFLECT — LLM tự đánh giá:
      │   • Dữ liệu đã đủ chưa?
      │   • Chất lượng data có ổn không?
      │   • Còn thiếu góc nhìn nào?
      │
      ├── ❌ Chưa đủ → Quay lại THINK (max 3 vòng)
      └── ✅ Đủ rồi → Tiếp tục xuống
         ↓
  ✍️  WRITE — LLM viết báo cáo hoàn chỉnh từ data thật
         ↓
  📄  Stream sections lên frontend
         ↓
  🏁  DONE!`}</pre>
    </div>
    <FlowStep icon="🧠" bg="linear-gradient(135deg,#EEF2FF,#E0E7FF)" border="#C7D2FE" title="Phase 1: THINK — Phân tích & Lên kế hoạch" desc="Agent nhận yêu cầu từ user, phân tích cần data gì, tạo SQL queries phù hợp. Chọn 2-4 tools đa dạng cho batch đầu." tags={[{text:"LLM Call #1",bg:"#EEF2FF",color:"#4338CA"}]} />
    <FlowStep icon="🔧" bg="linear-gradient(135deg,#FEF3C7,#FDE68A)" border="#FCD34D" title="Phase 2: ACT — Execute Tools Song Song" desc="Tất cả tools trong batch được execute đồng thời bằng asyncio.gather(). Nhanh gấp 3-4x so với tuần tự." tags={[{text:"Parallel I/O",bg:"#ECFDF5",color:"#059669"}]} />
    <FlowStep icon="🔍" bg="linear-gradient(135deg,#FFF7ED,#FFEDD5)" border="#FDBA74" title="Phase 3: REFLECT — Tự đánh giá dữ liệu" desc="LLM xem lại toàn bộ data đã thu thập. Nếu thiếu → tạo thêm queries. Nếu đủ → chuyển sang viết." tags={[{text:"LLM Call #2",bg:"#FEF3C7",color:"#D97706"},{text:"Max 3 vòng",bg:"#FFF1F2",color:"#E11D48"}]} />
    <FlowStep icon="✍️" bg="linear-gradient(135deg,#ECFDF5,#D1FAE5)" border="#6EE7B7" title="Phase 4: WRITE — Viết báo cáo hoàn chỉnh" desc="LLM nhận toàn bộ data thật → viết báo cáo JSON: executive summary, highlights, 4-6 sections (chart/table), conclusion, recommendations." tags={[{text:"LLM Call #3",bg:"#ECFDF5",color:"#059669"}]} />
  </S>

  {/* Tools */}
  <S><Label>Công cụ dữ liệu</Label>
    <h2 style={{fontSize:20,fontWeight:800,color:"#0F172A",letterSpacing:"-0.02em",marginBottom:14}}>4 Tools Agent sử dụng</h2>
    <p style={{fontSize:13.5,color:"#475569",marginBottom:16}}>Agent có quyền truy cập 4 tools để thu thập dữ liệu. Mỗi tool chỉ được phép <b>SELECT</b> (read-only).</p>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
      <Card icon="📊" bg="#EEF2FF" border="#E0E7FF" title="sql_langfuse" desc="Query bảng analytic.chatbot_rsa_trace_event_detail — traces, latency, costs, models, errors." sub="👉 Hiệu suất chatbot, chi phí LLM, user analytics" />
      <Card icon="🏷️" bg="#FEF3C7" border="#FDE68A" title="sql_starrocks" desc="Query bảng sản phẩm — tên, giá, số lượng bán, màu, chất liệu, mùa." sub="👉 Phân tích sản phẩm, doanh thu, thống kê catalog" />
      <Card icon="💬" bg="#ECFDF5" border="#A7F3D0" title="sql_postgres" desc="Query chat histories — tin nhắn user, bot, timestamp, identity." sub="👉 Phân tích hội thoại, volume chat, engagement" />
      <Card icon="🧮" bg="#FFF1F2" border="#FECDD3" title="calculator" desc="Tính toán math: cộng, trừ, nhân, chia, phần trăm. Chỉ nhận digits + operators." sub="👉 Tỉ lệ tăng trưởng, % thay đổi, trung bình" />
    </div>
  </S>

  {/* Schema */}
  <S><Label>Schema</Label>
    <h2 style={{fontSize:20,fontWeight:800,color:"#0F172A",letterSpacing:"-0.02em",marginBottom:14}}>Bảng Langfuse trên StarRocks</h2>
    <p style={{fontSize:13.5,color:"#475569",marginBottom:14}}>Bảng <code style={{background:"#F1F5F9",padding:"2px 6px",borderRadius:4,fontSize:11,color:"#6366F1"}}>analytic.chatbot_rsa_trace_event_detail</code> — chứa toàn bộ traces từ Langfuse.</p>
    <table style={{width:"100%",borderCollapse:"collapse",fontSize:12.5}}>
      <thead><tr style={{background:"#F8FAFC"}}><th style={{textAlign:"left",padding:"8px 12px",fontWeight:700,color:"#475569",borderBottom:"2px solid #E2E8F0"}}>Cột</th><th style={{textAlign:"left",padding:"8px 12px",fontWeight:700,color:"#475569",borderBottom:"2px solid #E2E8F0"}}>Kiểu</th><th style={{textAlign:"left",padding:"8px 12px",fontWeight:700,color:"#475569",borderBottom:"2px solid #E2E8F0"}}>Mô tả</th></tr></thead>
      <tbody>{schemaRows.map(([col,type,desc],i) => <tr key={i}><td style={{padding:"8px 12px",borderBottom:"1px solid #F1F5F9",color:"#334155"}}><code style={{background:"#F1F5F9",padding:"2px 6px",borderRadius:4,fontSize:11}}>{col}</code></td><td style={{padding:"8px 12px",borderBottom:"1px solid #F1F5F9"}}><span style={{fontSize:10,fontWeight:600,padding:"2px 8px",borderRadius:4,fontFamily:"monospace",background:typeBg[type],color:typeColor[type]}}>{type}</span></td><td style={{padding:"8px 12px",borderBottom:"1px solid #F1F5F9",color:"#334155"}}>{desc}</td></tr>)}</tbody>
    </table>
  </S>

  {/* Tech */}
  <S><Label>Tech Stack</Label>
    <h2 style={{fontSize:20,fontWeight:800,color:"#0F172A",letterSpacing:"-0.02em",marginBottom:14}}>Kiến trúc kỹ thuật</h2>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
      <Card icon="🖥️" bg="#F8FAFC" border="#E2E8F0" title="Frontend" desc="React 18 (UMD) + Babel + Chart.js 4. SSE streaming qua fetch() + ReadableStream." />
      <Card icon="⚡" bg="#F8FAFC" border="#E2E8F0" title="Backend" desc="FastAPI + StreamingResponse (SSE). Async tools via asyncio.gather(). POST /api/report-agent" />
      <Card icon="🤖" bg="#F8FAFC" border="#E2E8F0" title="LLM" desc="Codex GPT-5.3. 2-3 LLM calls/report: Think + Reflect + Write. Custom system prompts." />
      <Card icon="🗄️" bg="#F8FAFC" border="#E2E8F0" title="Databases" desc="StarRocks (products + Langfuse) + PostgreSQL (chat). Read-only, SQL injection protected." />
    </div>
  </S>
</div>
)
}

// ─── EMPTY ────────────────────────────────────────────────────────────────────
function Empty({ onSuggest, onShowGuide }) {
return (
<div style={{
    flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:24,padding:40,background:"#FAFBFD"
    }}>
    <div style={{ width:72,height:72,borderRadius:22,background:"linear-gradient(135deg,#EEF2FF,#F5F3FF)",border:"1px solid #E0E7FF",display:"flex",alignItems:"center",justifyContent:"center",fontSize:32 }}>📋</div>
    <div style={{ textAlign:"center",maxWidth:460 }}>
        <p style={{
            fontSize:20,fontWeight:800,color:"#0F172A",letterSpacing:"-0.02em",marginBottom:8,fontFamily:"'Georgia',serif"
            }}>AI Report Agent</p>
        <p style={{ fontSize:13.5,color:"#64748B",lineHeight:1.6,fontFamily:"system-ui" }}>
            Mô tả chủ đề báo cáo — Agent sẽ tự query dữ liệu thật<br />từ Langfuse, StarRocks, Postgres rồi viết báo
            cáo hoàn chỉnh
        </p>
    </div>
    <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,width:"100%",maxWidth:540 }}>
        {SUGGESTIONS.map((s,i) => (
        <button key={i} onClick={()=>onSuggest(s)} style={{ background:"#fff",border:"1.5px solid #E2E8F0",borderRadius:11,padding:"13px 15px",fontSize:12.5,color:"#475569",cursor:"pointer",textAlign:"left",lineHeight:1.5,fontFamily:"system-ui",transition:"all .15s" }} onMouseEnter={e=>{e.currentTarget.style.borderColor="#C7D2FE";e.currentTarget.style.color="#4338CA";e.currentTarget.style.background="#FAFBFF"}} onMouseLeave={e=>{e.currentTarget.style.borderColor="#E2E8F0";e.currentTarget.style.color="#475569";e.currentTarget.style.background="#fff"}}>
            {s}
        </button>
        ))}
    </div>
    <button onClick={onShowGuide} style={{marginTop:8,display:"inline-flex",alignItems:"center",gap:6,padding:"10px 20px",background:"#F8FAFC",border:"1.5px solid #E2E8F0",borderRadius:10,fontSize:12.5,fontWeight:600,color:"#6366F1",cursor:"pointer",transition:"all .15s"}} onMouseEnter={e=>{e.currentTarget.style.background="#EEF2FF";e.currentTarget.style.borderColor="#C7D2FE"}} onMouseLeave={e=>{e.currentTarget.style.background="#F8FAFC";e.currentTarget.style.borderColor="#E2E8F0"}}>
      📖 Xem hướng dẫn Agent hoạt động
    </button>
</div>
)
}

// ─── MAIN ─────────────────────────────────────────────────────────────────────
const SMIN=52, SDEF=340, SMAX=500

function ReportAI() {
const [messages, setMessages] = useState([{role:"assistant",content:"👋 Xin chào!\n\nTôi là AI Report Agent — tạo báo cáo từ dữ liệu thật:\n\n• 📊 Query Langfuse: traces, scores, costs\n• 🗄️ Query StarRocks: sản phẩm, doanh thu\n• 💬 Query Postgres: lịch sử chat\n• 📈 Tạo biểu đồ + bảng số liệu\n\nChọn gợi ý bên phải hoặc nhập chủ đề →"}])
const [steps, setSteps] = useState([])  // Agent steps for sidebar
const [input, setInput] = useState("")
const [loading, setLoading] = useState(false)
const [report, setReport] = useState(null)
const [showGuide, setShowGuide] = useState(false)
const [sideW, setSideW] = useState(SDEF)
const [collapsed, setCollapsed] = useState(false)
const bottomRef = useRef(null)
const dragging = useRef(false), dragX = useRef(0), startW = useRef(0)
const abortRef = useRef(null)

useEffect(() => { bottomRef.current?.scrollIntoView({behavior:"smooth"}) }, [messages, steps, loading])

const onMouseDown = useCallback(e => {
if (collapsed) return
dragging.current=true; dragX.current=e.clientX; startW.current=sideW; e.preventDefault()
}, [collapsed, sideW])

useEffect(() => {
const mv = e => { if(!dragging.current) return; setSideW(Math.max(SMIN+1, Math.min(SMAX,
startW.current+(e.clientX-dragX.current)))) }
const up = () => { dragging.current=false }
window.addEventListener("mousemove",mv); window.addEventListener("mouseup",up)
return () => { window.removeEventListener("mousemove",mv); window.removeEventListener("mouseup",up) }
}, [])

// ─── SSE STREAMING ──────────────────────────────────────────────────────────
const send = async (text) => {
const msg = text||input
if (!msg.trim()||loading) return
setInput(""); setLoading(true); setReport(null); setSteps([])
if (collapsed) setCollapsed(false)

const uMsgs = [...messages,{role:"user",content:msg}]; setMessages(uMsgs)

try {
  const abort = new AbortController()
  abortRef.current = abort

  const res = await fetch("/api/report-agent", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ question: msg }),
    signal: abort.signal,
  })

  if (!res.ok) {
    throw new Error(`Server error: ${res.status}`)
  }

  const reader = res.body.getReader()
  const decoder = new TextDecoder()
  let buffer = ""

  while (true) {
    const { done, value } = await reader.read()
    if (done) break

    buffer += decoder.decode(value, { stream: true })
    const lines = buffer.split("\n")
    buffer = lines.pop() || ""

    for (const line of lines) {
      if (!line.startsWith("data: ")) continue
      const jsonStr = line.slice(6).trim()
      if (!jsonStr) continue

      try {
        const evt = JSON.parse(jsonStr)

        // Add to steps sidebar
        if (["thinking","plan_ready","tool_call","tool_result","reflect"].includes(evt.type)) {
          setSteps(prev => [...prev, evt])
        }

        // Progressive section rendering
        if (evt.type === "section_ready") {
          setReport(prev => {
            if (!prev) return { sections: [evt.section] }
            return { ...prev, sections: [...(prev.sections||[]), evt.section] }
          })
          setSteps(prev => [...prev, { type: "section_ready", step: `📄 Section ${evt.index + 1}: ${evt.section?.title || ""}` }])
        }

        // Full report
        if (evt.type === "report_complete") {
          setReport(evt.report)
          const rpt = evt.report
          const numSec = rpt.sections?.length||0
          const numChart = rpt.sections?.filter(s=>s.chart).length||0
          const numTable = rpt.sections?.filter(s=>s.table).length||0
          setMessages(prev => [...prev, {
            role:"assistant",
            content:`✅ Báo cáo **"${rpt.title}"** hoàn thành!\n\n${numSec} chương · ${numChart} biểu đồ · ${numTable} bảng\n\nDữ liệu thật từ Langfuse + DB.`
          }])
        }

        if (evt.type === "error") {
          setMessages(prev => [...prev, {role:"assistant", content:`❌ Lỗi: ${evt.message}`}])
          setSteps(prev => [...prev, evt])
        }

        if (evt.type === "done") {
          setSteps(prev => [...prev, { type: "done" }])
        }
      } catch (parseErr) {
        console.warn("SSE parse error:", parseErr, jsonStr)
      }
    }
  }
} catch(e) {
  if (e.name !== "AbortError") {
    setMessages(prev => [...prev, {role:"assistant", content:`❌ Lỗi: ${e.message}`}])
  }
}
setLoading(false)
abortRef.current = null
}

const handleExport = () => {
window.print()
}

const handleReset = () => {
if (abortRef.current) abortRef.current.abort()
setReport(null)
setSteps([])
setMessages(messages.slice(0,1))
setLoading(false)
}

const bot = <div
    style={{width:26,height:26,borderRadius:8,background:"linear-gradient(135deg,#1E40AF,#4338CA)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:11,color:"white",fontFamily:"system-ui"}}>
    ✦</div>

return (
<div style={{display:"flex",height:"100vh",fontFamily:"system-ui,sans-serif",background:"#F0F2F8"}}>
    <style>
        {
            ` @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Georgia&display=swap');

            * {
                box-sizing: border-box;
                margin: 0;
                padding: 0
            }

            ::-webkit-scrollbar {
                width: 5px
            }

            ::-webkit-scrollbar-thumb {
                background: rgba(0, 0, 0, .1);
                border-radius: 4px
            }

            .sb-scroll::-webkit-scrollbar-thumb {
                background: rgba(255, 255, 255, .1)
            }

            @keyframes pulse {
                0%,100% { opacity: .3 }
                50% { opacity: 1 }
            }

            @keyframes pop {
                from { opacity: 0; transform: translateY(5px) }
                to { opacity: 1; transform: translateY(0) }
            }

            @keyframes spin {
                to { transform: rotate(360deg) }
            }

            @keyframes fadeIn {
                from { opacity: 0 }
                to { opacity: 1 }
            }

            .msg-row { animation: pop .2s ease }
            textarea:focus, button:focus { outline: none }
            button { cursor: pointer }

            @media print {
                .no-print { display: none !important }
                body { background: white }
                .report-area { overflow: visible !important; height: auto !important }
            }
            `
        }
    </style>

    {/* ── Sidebar ── */}
    <div className="no-print"
        style={{width:collapsed?SMIN:sideW,flexShrink:0,background:"#111827",display:"flex",flexDirection:"column",transition:collapsed?"width .25s ease":"none",overflow:"hidden",borderRight:"1px solid rgba(255,255,255,.06)"}}>

        {/* header */}
        <div style={{height:54,display:"flex",alignItems:"center",padding:"0 13px",gap:10,borderBottom:"1px solid rgba(255,255,255,.06)",flexShrink:0}}>
            {collapsed ? (
            <button onClick={()=>setCollapsed(false)}
                style={{width:36,height:36,borderRadius:10,background:"linear-gradient(135deg,#1E40AF,#4338CA)",border:"none",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto",fontSize:14,color:"white"}}>✦</button>
            ) : (
            <React.Fragment>
                <div
                    style={{width:34,height:34,borderRadius:10,background:"linear-gradient(135deg,#1E40AF,#4338CA)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:14,color:"white"}}>
                    ✦</div>
                <div style={{flex:1,minWidth:0}}>
                    <p style={{fontSize:13,fontWeight:700,color:"#F9FAFB",letterSpacing:"-0.01em"}}>ReportAI Agent</p>
                    <div style={{display:"flex",alignItems:"center",gap:4,marginTop:1}}>
                        <div style={{width:5,height:5,borderRadius:"50%",background:loading?"#FBBF24":"#4ADE80",animation:"pulse 2.5s ease-in-out infinite"}} />
                        <span style={{fontSize:10,color:loading?"#FBBF24":"#4ADE80",fontWeight:500}}>{loading?"Working...":"Codex · Ready"}</span>
                    </div>
                </div>
                <button onClick={()=>setCollapsed(true)}
                    style={{background:"none",border:"none",fontSize:18,width:28,height:28,borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",color:"#4B5563"}}>‹</button>
            </React.Fragment>
            )}
        </div>

        {/* messages + agent steps */}
        {!collapsed && (
        <div className="sb-scroll" style={{flex:1,overflowY:"auto",padding:"14px 12px",display:"flex",flexDirection:"column",gap:8}}>
            {messages.map((m,i) => (
            <div key={`m${i}`} className="msg-row" style={{display:"flex",flexDirection:m.role==="user"
                ?"row-reverse":"row",gap:8,alignItems:"flex-end"}}>
                {m.role==="assistant"&&bot}
                <div style={{maxWidth:"83%",padding:"9px 13px",borderRadius:m.role==="user" ?"13px 13px 3px 13px":"13px 13px 13px 3px",background:m.role==="user"
                    ?"linear-gradient(135deg,#1E40AF,#4338CA)":"rgba(255,255,255,.07)",fontSize:12.5,lineHeight:1.6,color:m.role==="user"
                    ?"#fff":"#D1D5DB",whiteSpace:"pre-wrap"}}>
                    {m.content.replace(/\*\*(.*?)\*\*/g,"$1")}
                </div>
            </div>
            ))}

            {/* Agent steps */}
            {steps.length > 0 && (
            <div style={{display:"flex",flexDirection:"column",gap:5,marginTop:4}}>
                <p style={{fontSize:9,fontWeight:700,color:"#4B5563",textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:2}}>Agent Steps</p>
                {steps.map((s,i) => <AgentStep key={`s${i}`} step={s} />)}
            </div>
            )}

            {loading && (
            <div className="msg-row" style={{display:"flex",gap:8,alignItems:"flex-end"}}>
                {bot}
                <div style={{padding:"11px 14px",background:"rgba(255,255,255,.07)",borderRadius:"13px 13px 13px 3px",display:"flex",gap:5,alignItems:"center"}}>
                    {[0,1,2].map(i=>
                    <div key={i} style={{width:5,height:5,borderRadius:"50%",background:"#3B82F6",animation:`pulse 1.4s
                        ease-in-out ${i*.2}s infinite`}} />)}
                </div>
            </div>
            )}
            <div ref={bottomRef} />
        </div>
        )}

        {/* collapsed icons */}
        {collapsed && (
        <div style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:12,gap:8}}>
            {["📋","📊","💬"].map((ic,i) => <button key={i} onClick={()=>setCollapsed(false)}
                style={{width:34,height:34,borderRadius:8,background:"rgba(255,255,255,.05)",border:"none",fontSize:14}}>{ic}</button>)}
        </div>
        )}

        {/* input */}
        {!collapsed && (
        <div style={{padding:"11px 12px",borderTop:"1px solid rgba(255,255,255,.06)",flexShrink:0}}>
            <div style={{background:"rgba(255,255,255,.06)",borderRadius:12,padding:"8px 8px 8px 12px",border:"1px solid rgba(255,255,255,.09)",display:"flex",gap:8,alignItems:"flex-end"}}>
                <textarea value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>{if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send()}}}
                placeholder="Mô tả báo cáo cần tạo..." rows={2}
                style={{flex:1,background:"transparent",border:"none",color:"#F9FAFB",fontSize:12.5,lineHeight:1.5,resize:"none",fontFamily:"inherit"}}/>
              <button onClick={()=>send()} disabled={!input.trim()||loading}
                style={{width:32,height:32,borderRadius:8,background:input.trim()&&!loading?"linear-gradient(135deg,#1E40AF,#4338CA)":"rgba(255,255,255,.07)",border:"none",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"white",fontSize:16,opacity:input.trim()&&!loading?1:.35}}>↑</button>
            </div>
            <p style={{textAlign:"center",fontSize:9.5,color:"#1F2937",marginTop:5}}>Enter gửi · Shift+Enter xuống dòng</p>
          </div>
        )}
      </div>

      {/* drag handle */}
      {!collapsed && (
        <div className="no-print" onMouseDown={onMouseDown} style={{width:4,flexShrink:0,cursor:"col-resize",position:"relative",zIndex:10}}
          onMouseEnter={e=>e.currentTarget.children[0].style.opacity=1}
          onMouseLeave={e=>e.currentTarget.children[0].style.opacity=0}>
          <div style={{position:"absolute",inset:0,background:"rgba(37,99,235,.6)",borderRadius:2,opacity:0,transition:"opacity .15s"}}/>
        </div>
      )}

      {/* ── Report area ── */}
      <div className="report-area" style={{flex:1,overflowY:"auto",minWidth:0,background:"#F0F2F8"}}>
        {/* topbar */}
        <div className="no-print" style={{height:52,background:"#fff",borderBottom:"1px solid #E8ECF0",display:"flex",alignItems:"center",padding:"0 20px",gap:12,flexShrink:0,position:"sticky",top:0,zIndex:5}}>
          {collapsed && <button onClick={()=>setCollapsed(false)} style={{width:30,height:30,borderRadius:8,background:"#EEF2FF",border:"none",color:"#4338CA",fontSize:16,display:"flex",alignItems:"center",justifyContent:"center"}}>›</button>}
          <div style={{width:28,height:28,borderRadius:8,background:"#EEF2FF",display:"flex",alignItems:"center",justifyContent:"center",fontSize:13,flexShrink:0}}>📋</div>
          <div style={{minWidth:0,flex:1}}>
            <p style={{fontWeight:700,color:"#0F172A",fontSize:13.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{report?.title||"AI Report Agent"}</p>
            {report?.period && <p style={{fontSize:10.5,color:"#94A3B8",marginTop:1}}>Kỳ báo cáo: {report.period}</p>}
          </div>
          <div style={{display:"flex",gap:8,flexShrink:0}}>
            <button onClick={()=>setShowGuide(!showGuide)} style={{background:showGuide?"#EEF2FF":"#F8FAFC",border:`1px solid ${showGuide?"#C7D2FE":"#E2E8F0"}`,borderRadius:8,padding:"0 12px",height:28,display:"flex",alignItems:"center",gap:5,color:showGuide?"#4338CA":"#64748B",fontSize:11.5,fontWeight:600,cursor:"pointer"}}>
              📖 {showGuide?"Đóng":"Hướng dẫn"}
            </button>
            {report && (
            <>
              <span style={{fontSize:11,color:"#4338CA",background:"#EEF2FF",padding:"4px 12px",borderRadius:100,fontWeight:600,border:"1px solid #E0E7FF"}}>
                {report.sections?.length||0} chương · {report.sections?.filter(s=>s.chart).length||0} biểu đồ
              </span>
              <button onClick={handleExport} style={{background:"#0F172A",color:"white",border:"none",borderRadius:9,padding:"7px 14px",fontSize:12,fontWeight:600,display:"flex",alignItems:"center",gap:6}}>
                <span style={{fontSize:13}}>🖨</span> Lưu PDF
              </button>
              <button onClick={handleReset} style={{background:"#F8FAFC",border:"1px solid #E2E8F0",borderRadius:8,width:28,height:28,display:"flex",alignItems:"center",justifyContent:"center",color:"#64748B",fontSize:13}}>↺</button>
            </>
            )}
          </div>
        </div>

        {/* content */}
        {showGuide ? (
          <div style={{background:"#fff",minHeight:"calc(100vh - 52px)",overflowY:"auto",animation:"fadeIn .3s ease"}}>
            <Guide />
          </div>
        ) : loading && !report ? (
          <div style={{flex:1,display:"flex",alignItems:"center",justifyContent:"center",minHeight:"calc(100vh - 52px)"}}>
            <div style={{textAlign:"center"}}>
              <div style={{width:44,height:44,borderRadius:"50%",border:"3px solid #DBEAFE",borderTopColor:"#2563EB",animation:"spin .8s linear infinite",margin:"0 auto 16px"}}/>
              <p style={{fontSize:14,color:"#374151",fontWeight:600,fontFamily:"'Georgia',serif"}}>Agent đang xử lý...</p>
              <p style={{fontSize:12,color:"#94A3B8",marginTop:6}}>Query dữ liệu thật · Phân tích · Viết báo cáo</p>
            </div>
          </div>
        ) : !report ? (
          <div style={{display:"flex",flex:1,minHeight:"calc(100vh - 52px)"}}>
            <Empty onSuggest={send} onShowGuide={()=>setShowGuide(true)}/>
          </div>
        ) : (
          <div style={{background:"#fff",margin:"0",minHeight:"calc(100vh - 52px)",animation:"fadeIn .4s ease"}}>
            <ReportDoc report={report} onExport={handleExport}/>
          </div>
        )}
      </div>
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(ReportAI));
</script>
</body>
</html>
