// สรุปผลการติดตามผลการฝึกอบรม — รายหลักสูตร
// จัดกลุ่มหัวข้อ + ถ่วงน้ำหนัก (SCORE_GROUPS) เทียบเป้าหมาย (SCORE_TARGET_PERCENT)
// สลับดูได้ 3 มุมมอง: ประเมินตนเอง / ผู้บังคับบัญชา / เฉลี่ยรวม

const GROUP_COLORS = { individual:"var(--teal)", team:"var(--purple)", overall:"var(--yellow)" };
const SOURCE_TABS = [
  { key:"combined", label:"เฉลี่ยรวม" },
  { key:"self",     label:"ประเมินตนเอง" },
  { key:"sup",      label:"ผู้บังคับบัญชา" },
];

const pct0 = v => v == null ? "—" : `${v.toFixed(0)}%`;
const num2 = v => v == null ? "—" : v.toFixed(2);

// แท่งแนวนอน (ใช้กับตารางรายข้อ + กราฟหัวข้อ)
const PctBar = ({ pct, color }) => (
  <div style={{ display:"flex", alignItems:"center", gap:8 }}>
    <div style={{ flex:1, height:8, borderRadius:4, background:"var(--surface)", overflow:"hidden" }}>
      {pct != null && <div style={{ width:`${pct}%`, height:"100%", background:color, borderRadius:4, transition:"width .4s" }} />}
    </div>
    <span style={{ fontSize:12, fontWeight:600, color:pct!=null?color:"var(--text-faint)", minWidth:38, textAlign:"right" }}>{pct0(pct)}</span>
  </div>
);

const CourseSummaryScreen = ({ courseId, user, onBack, onEditCourse }) => {
  const [data, setData] = React.useState(null); // { course, evals }
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);
  const [source, setSource] = React.useState("combined");

  const load = React.useCallback(() => {
    setLoading(true);
    window.TRN_API.getCourse(courseId)
      .then(d => { setData(d); setErr(null); })
      .catch(e => setErr(e.message || "โหลดไม่สำเร็จ"))
      .finally(() => setLoading(false));
  }, [courseId]);

  React.useEffect(() => { load(); }, [load]);

  const course = data?.course;
  const evals  = data?.evals || [];
  const summary = React.useMemo(() => evals.length ? window.computeCourseSummary(evals) : null, [evals]);
  const view = summary?.[source];
  const target = window.SCORE_TARGET_PERCENT;

  return (
    <div style={{ minHeight:"100vh", paddingBottom:60 }}>
      <GlowBlob color="rgba(124,92,255,0.2)" x={-60} y={0} size={400} opacity={0.16} />

      {/* Topbar */}
      <div style={{ padding:"12px 26px", display:"flex", alignItems:"center", gap:12, borderBottom:"1px solid var(--border)", backdropFilter:"blur(10px)", position:"sticky", top:0, zIndex:100, background:"var(--bg-1)" }}>
        <button className="btn btn-ghost btn-sm" onClick={onBack}><Icon name="chevron-l" size={15} /> กลับ</button>
        <div style={{ fontWeight:600, fontSize:14, flex:1, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>
          สรุปผลการติดตามผลการฝึกอบรม <span className="faint" style={{ fontWeight:400 }}>· {course?.course_name || ""}</span>
        </div>
      </div>

      {loading ? (
        <div style={{ padding:60, textAlign:"center" }}><LoadingSplash /></div>
      ) : err ? (
        <div style={{ padding:60, textAlign:"center" }}><ErrorSplash message={err} onRetry={load} /></div>
      ) : evals.length === 0 ? (
        <div style={{ padding:60, textAlign:"center" }}>
          <div className="faint" style={{ fontSize:14 }}>ยังไม่มีผู้เข้าอบรมในหลักสูตรนี้ — ยังสรุปผลไม่ได้</div>
        </div>
      ) : (
        <div style={{ padding:"22px 26px", maxWidth:1200, margin:"0 auto" }}>

          {/* Toggle มุมมอง */}
          <div className="row" style={{ justifyContent:"space-between", marginBottom:18, flexWrap:"wrap", gap:10 }}>
            <div>
              <div style={{ fontWeight:700, fontSize:19 }}>{course.course_name}</div>
              <div className="faint" style={{ fontSize:12.5, marginTop:2 }}>{evals.length} คน · น้ำหนัก 60/20/20 · เป้าหมาย {target}%</div>
            </div>
            <div style={{ display:"flex", background:"var(--surface)", borderRadius:10, padding:4, gap:4 }}>
              {SOURCE_TABS.map(t => (
                <button key={t.key} type="button" onClick={() => setSource(t.key)}
                  className="btn btn-sm" style={{
                    background: source===t.key ? "var(--bg-1)" : "transparent",
                    boxShadow: source===t.key ? "0 1px 4px rgba(0,0,0,0.12)" : "none",
                    color: source===t.key ? "var(--text)" : "var(--text-muted)",
                    fontWeight: source===t.key ? 600 : 500,
                  }}>{t.label}</button>
              ))}
            </div>
          </div>

          {!view?.hasData ? (
            <div className="glass" style={{ borderRadius:14, padding:"50px 0", textAlign:"center" }}>
              <div className="faint" style={{ fontSize:14 }}>ยังไม่มีข้อมูลการประเมิน ({SOURCE_TABS.find(t=>t.key===source)?.label})</div>
            </div>
          ) : (
            <>
              {/* Overall Score gauge */}
              <div className="glass" style={{ borderRadius:14, padding:"20px 22px", marginBottom:18 }}>
                <div style={{ fontWeight:600, fontSize:14, marginBottom:14 }}>Overall Score <span className="faint" style={{ fontWeight:400, fontSize:12 }}>(เปอร์เซ็นต์เทียบเป้าหมาย)</span></div>
                <div style={{ display:"flex", alignItems:"center", gap:20, flexWrap:"wrap" }}>
                  <div style={{ fontSize:46, fontWeight:800, color: view.overallPct >= target ? "var(--teal)" : "var(--pink)", lineHeight:1, minWidth:110 }}>
                    {num2(view.overallPct)}<span style={{ fontSize:20, fontWeight:600 }}>%</span>
                  </div>
                  <div style={{ flex:1, minWidth:260, position:"relative", paddingTop:18 }}>
                    <div style={{ position:"relative", height:22, borderRadius:11, background:"var(--surface)", overflow:"hidden" }}>
                      <div style={{
                        position:"absolute", inset:0, width:`${Math.min(100, view.overallPct)}%`, borderRadius:11,
                        background: view.overallPct >= target
                          ? "linear-gradient(90deg, var(--purple), var(--teal))"
                          : "linear-gradient(90deg, var(--purple), var(--pink))",
                        transition:"width .5s",
                      }} />
                      <div style={{ position:"absolute", left:`${target}%`, top:-6, bottom:-6, width:2, background:"var(--yellow)" }} />
                    </div>
                    <div style={{ position:"absolute", left:`${target}%`, top:-2, transform:"translateX(-50%)", fontSize:10.5, fontWeight:700, color:"var(--yellow)", whiteSpace:"nowrap" }}>
                      เป้าหมาย {target}%
                    </div>
                    <div className="faint" style={{ display:"flex", justifyContent:"space-between", fontSize:10.5, marginTop:5 }}>
                      <span>0%</span><span>50%</span><span>100%</span>
                    </div>
                  </div>
                </div>
              </div>

              <div style={{ display:"grid", gridTemplateColumns:"1.3fr 1fr", gap:18, marginBottom:18 }}>
                {/* ตารางรายข้อ จัดกลุ่ม */}
                <div className="glass" style={{ borderRadius:14, padding:"20px 22px" }}>
                  <div style={{ fontWeight:600, fontSize:14, marginBottom:14 }}>สรุปคะแนนรายหัวข้อ</div>
                  <div style={{ display:"grid", gridTemplateColumns:"1.6fr 60px 1fr 50px 60px", gap:8, paddingBottom:6, marginBottom:8, borderBottom:"1px solid var(--border)" }}>
                    {["หัวข้อประเมิน","AVR","%","น.น.","Point"].map((h,i) => (
                      <div key={h} className="faint" style={{ fontSize:10.5, textAlign:i===0?"left":"right" }}>{h}</div>
                    ))}
                  </div>
                  <div className="col gap-0">
                    {view.groups.map(g => (
                      <div key={g.key}>
                        <div style={{ display:"grid", gridTemplateColumns:"1.6fr 60px 1fr 50px 60px", gap:8, alignItems:"center", padding:"7px 0", background:`color-mix(in srgb, ${GROUP_COLORS[g.key]} 8%, transparent)`, borderRadius:6 }}>
                          <div style={{ fontSize:12.5, fontWeight:700, color:GROUP_COLORS[g.key], display:"flex", alignItems:"center", gap:6, paddingLeft:6 }}>
                            <span style={{ width:8, height:8, borderRadius:2, background:GROUP_COLORS[g.key], flexShrink:0 }} /> {g.label}
                          </div>
                          <div style={{ fontSize:12, fontWeight:700, textAlign:"right" }}>{num2(g.avg)}</div>
                          <div style={{ textAlign:"right" }}><span style={{ fontSize:12, fontWeight:700, color:GROUP_COLORS[g.key] }}>{pct0(g.pct)}</span></div>
                          <div className="faint" style={{ fontSize:11.5, textAlign:"right" }}>{g.weight}</div>
                          <div style={{ fontSize:12, fontWeight:700, textAlign:"right", paddingRight:6 }}>{num2(g.point)}</div>
                        </div>
                        {g.items.map(it => (
                          <div key={it.key} style={{ display:"grid", gridTemplateColumns:"1.6fr 60px 1fr 50px 60px", gap:8, alignItems:"center", padding:"7px 0 7px 20px", borderBottom:"1px solid var(--border)" }}>
                            <div style={{ fontSize:12.5 }}>{it.label}</div>
                            <div className="faint" style={{ fontSize:12, textAlign:"right" }}>{num2(it.avg)}</div>
                            <div style={{ textAlign:"right" }}><span className="faint" style={{ fontSize:11.5 }}>{pct0(it.pct)}</span></div>
                            <div />
                            <div />
                          </div>
                        ))}
                      </div>
                    ))}
                  </div>
                  <div style={{ display:"grid", gridTemplateColumns:"1.6fr 60px 1fr 50px 60px", gap:8, paddingTop:10, marginTop:4, borderTop:"2px solid var(--border)" }}>
                    <div style={{ fontSize:13, fontWeight:700 }}>รวม</div>
                    <div />
                    <div />
                    <div className="faint" style={{ fontSize:12, textAlign:"right", fontWeight:700 }}>{view.groups.reduce((a,g)=>a+g.weight,0)}</div>
                    <div style={{ fontSize:13, fontWeight:800, textAlign:"right", color:"var(--purple)" }}>{num2(view.groups.reduce((a,g)=>a+(g.point||0),0))}</div>
                  </div>
                </div>

                {/* กราฟแยกตามกลุ่ม เทียบเป้าหมาย */}
                <div className="glass" style={{ borderRadius:14, padding:"20px 22px" }}>
                  <div style={{ fontWeight:600, fontSize:14, marginBottom:6 }}>เปอร์เซ็นต์เฉลี่ย แยกตามกลุ่ม</div>
                  <div className="faint" style={{ fontSize:11, marginBottom:16 }}>เส้นประสีเหลือง = เป้าหมาย {target}%</div>
                  <div style={{ position:"relative", height:200, display:"flex", alignItems:"flex-end", gap:20, padding:"0 8px" }}>
                    <div style={{ position:"absolute", left:0, right:0, bottom:`${target/100*200}px`, height:0, borderTop:"2px dashed var(--yellow)" }} />
                    {view.groups.map(g => (
                      <div key={g.key} style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"flex-end", height:"100%" }}>
                        <div style={{ fontSize:12, fontWeight:700, color:GROUP_COLORS[g.key], marginBottom:4 }}>{pct0(g.pct)}</div>
                        <div style={{
                          width:"70%", height:`${Math.min(100, g.pct||0)/100*180}px`,
                          background:GROUP_COLORS[g.key], borderRadius:"6px 6px 0 0", transition:"height .4s",
                        }} />
                      </div>
                    ))}
                  </div>
                  <div style={{ display:"flex", gap:20, padding:"10px 8px 0", borderTop:"1px solid var(--border)", marginTop:10 }}>
                    {view.groups.map(g => (
                      <div key={g.key} style={{ flex:1, textAlign:"center", fontSize:11, color:"var(--text-muted)" }}>{g.label}</div>
                    ))}
                  </div>
                </div>
              </div>

              <div style={{ display:"grid", gridTemplateColumns:"1.3fr 1fr", gap:18 }}>
                {/* กราฟรายหัวข้อ (แนวนอน) */}
                <div className="glass" style={{ borderRadius:14, padding:"20px 22px" }}>
                  <div style={{ fontWeight:600, fontSize:14, marginBottom:14 }}>คะแนนเฉลี่ย แยกตามหัวข้อ</div>
                  <div className="col gap-10">
                    {view.groups.flatMap(g => g.items.map(it => (
                      <div key={it.key} style={{ display:"grid", gridTemplateColumns:"140px 1fr", gap:10, alignItems:"center" }}>
                        <div style={{ fontSize:12, display:"flex", alignItems:"center", gap:6 }}>
                          <span style={{ width:7, height:7, borderRadius:2, background:GROUP_COLORS[g.key], flexShrink:0 }} />
                          <span style={{ overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{it.label}</span>
                        </div>
                        <PctBar pct={it.pct} color={GROUP_COLORS[g.key]} />
                      </div>
                    )))}
                  </div>
                </div>

                {/* Max vs Score ตามน้ำหนัก */}
                <div className="glass" style={{ borderRadius:14, padding:"20px 22px" }}>
                  <div style={{ fontWeight:600, fontSize:14, marginBottom:14 }}>คะแนนตามน้ำหนักเป้าหมาย</div>
                  <div className="col gap-16">
                    {view.groups.map(g => (
                      <div key={g.key}>
                        <div style={{ display:"flex", justifyContent:"space-between", fontSize:12, marginBottom:5 }}>
                          <span>{g.label}</span>
                          <span className="faint">{num2(g.point)} / {g.weight} <span style={{ fontWeight:700, color:GROUP_COLORS[g.key] }}>({pct0(g.pct)})</span></span>
                        </div>
                        <div style={{ height:9, borderRadius:5, background:"var(--surface)", overflow:"hidden", position:"relative" }}>
                          <div style={{ position:"absolute", inset:0, width:"100%", background:"var(--border)", opacity:0.5 }} />
                          <div style={{ position:"absolute", inset:0, width:`${g.weight ? (g.point/g.weight)*100 : 0}%`, background:GROUP_COLORS[g.key], borderRadius:5, transition:"width .4s" }} />
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="faint" style={{ fontSize:10.5, marginTop:14, textAlign:"right" }}>แถบเทา = คะแนนเต็มของกลุ่ม (Max = น้ำหนัก) · แถบสี = คะแนนที่ได้จริง</div>
                </div>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};
window.CourseSummaryScreen = CourseSummaryScreen;
