// Dashboard สรุปผลแบบสอบถามความพึงพอใจหลังอบรม 1 ชุด (1 หลักสูตร/รุ่นที่อัปโหลด)
// สูตรคำนวณตรงกับชีต "Sum" ในไฟล์ Excel ต้นฉบับ (ดู window.computeSatisfactionSummary ใน data.jsx)

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

const SatPctBar = ({ 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 ScoreGroupCard = ({ title, group, color }) => (
  <div className="glass" style={{ borderRadius: 14, padding: "20px 22px" }}>
    <div className="row" style={{ justifyContent: "space-between", marginBottom: 14 }}>
      <div style={{ fontWeight: 600, fontSize: 14 }}>{title}</div>
      <div style={{ fontSize: 13, fontWeight: 700, color }}>{pct0(group.overallPct)}</div>
    </div>
    <div className="col gap-10">
      {group.items.map(it => (
        <div key={it.key} style={{ display: "grid", gridTemplateColumns: "1fr 160px", gap: 12, alignItems: "center" }}>
          <div style={{ fontSize: 12.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={it.label}>{it.label}</div>
          <SatPctBar pct={it.pct} color={color} />
        </div>
      ))}
    </div>
  </div>
);

const DistBarGroup = ({ group }) => {
  const max = Math.max(...group.counts.map(c => c.count), 1);
  return (
    <div className="glass" style={{ borderRadius: 14, padding: "18px 20px" }}>
      <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 4 }}>{group.label}</div>
      <div className="faint" style={{ fontSize: 11, marginBottom: 12 }}>ตอบแล้ว {group.answered} คน</div>
      <div className="col gap-8">
        {group.counts.map(c => (
          <div key={c.label}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
              <div style={{ fontSize: 12, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "80%" }} title={c.label}>{c.label}</div>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text)" }}>{c.count}</div>
            </div>
            <div style={{ height: 6, borderRadius: 3, background: "var(--surface)", overflow: "hidden" }}>
              <div style={{ width: `${(c.count / max) * 100}%`, height: "100%", background: "var(--blue)", borderRadius: 3, transition: "width .4s" }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// คำตอบปลายเปิดที่ถือว่า "ไม่มีเนื้อหา" (ตอบขอไปที/ไม่มีความเห็น) — ไม่เอามาแสดงในสรุป
const BLANK_ANSWERS = new Set(["-", "–", "—", "ไม่มี", "ไม่มีค่ะ", "ไม่มีครับ", "n/a", "na", ""]);
const isMeaningfulAnswer = (v) => v != null && !BLANK_ANSWERS.has(String(v).trim().toLowerCase());

const TextAnswerList = ({ title, field, responses, color }) => {
  const items = responses
    .filter(r => isMeaningfulAnswer(r[field]))
    .map(r => ({ text: r[field].trim(), name: [r.first_name, r.last_name].filter(Boolean).join(" "), dept: r.dept }));
  return (
    <div className="glass" style={{ borderRadius: 14, padding: "18px 20px" }}>
      <div className="row" style={{ justifyContent: "space-between", marginBottom: 4 }}>
        <div style={{ fontWeight: 600, fontSize: 13.5 }}>{title}</div>
        <div style={{ fontSize: 11.5, fontWeight: 600, color }}>{items.length} คำตอบ</div>
      </div>
      <div className="faint" style={{ fontSize: 11, marginBottom: 12 }}>จากทั้งหมด {responses.length} คน (ไม่รวมคำตอบว่าง/"-")</div>
      {items.length === 0 ? (
        <div className="faint" style={{ fontSize: 12.5, padding: "10px 0" }}>ไม่มีคำตอบ</div>
      ) : (
        <div className="col gap-10" style={{ maxHeight: 360, overflowY: "auto" }}>
          {items.map((it, i) => (
            <div key={i} style={{ padding: "10px 12px", borderRadius: 10, background: "var(--surface)", borderLeft: `3px solid ${color}` }}>
              <div style={{ fontSize: 13, lineHeight: 1.5 }}>{it.text}</div>
              {(it.name || it.dept) && (
                <div className="faint" style={{ fontSize: 11, marginTop: 5 }}>
                  {it.name || "—"}{it.dept ? ` · ${it.dept}` : ""}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const SatisfactionDashboardScreen = ({ surveyId, onBack }) => {
  const [data, setData] = React.useState(null); // { survey, responses }
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);
  const { push } = useToast();

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

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

  const survey = data?.survey;
  const responses = data?.responses || [];
  const summary = React.useMemo(() => responses.length ? window.computeSatisfactionSummary(responses) : null, [responses]);

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

      <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 }}>· {survey?.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>
      ) : responses.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" }}>
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontWeight: 700, fontSize: 19 }}>{survey.course_name}</div>
            <div className="faint" style={{ fontSize: 12.5, marginTop: 2 }}>
              {summary.n} คนตอบแบบสอบถาม{survey.course_date ? ` · อบรมวันที่ ${fmtThaiDate(survey.course_date)}` : ""}
            </div>
          </div>

          {/* Overall Score gauge */}
          <div className="glass" style={{ borderRadius: 14, padding: "20px 22px", marginBottom: 18 }}>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 14 }}>ภาพรวมความพึงพอใจ <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: "var(--teal)", lineHeight: 1, minWidth: 110 }}>
                {summary.overallPct != null ? summary.overallPct.toFixed(2) : "—"}<span style={{ fontSize: 20, fontWeight: 600 }}>%</span>
              </div>
              <div style={{ flex: 1, minWidth: 260 }}>
                <div style={{ height: 22, borderRadius: 11, background: "var(--surface)", overflow: "hidden" }}>
                  <div style={{
                    width: `${Math.min(100, summary.overallPct || 0)}%`, height: "100%", borderRadius: 11,
                    background: "linear-gradient(90deg, var(--purple), var(--teal))", transition: "width .5s",
                  }} />
                </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: "1fr 1fr", gap: 18, marginBottom: 18 }}>
            <ScoreGroupCard title="หัวข้อประเมินด้านการจัดฝึกอบรม" group={summary.org} color="var(--teal)" />
            <ScoreGroupCard title="หัวข้อประเมินด้านวิทยากร" group={summary.trainer} color="var(--purple)" />
          </div>

          <div style={{ fontWeight: 600, fontSize: 14, margin: "22px 0 12px" }}>ผลลัพธ์การเรียนรู้ผู้เข้าอบรม</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
            {summary.distributions.map(g => <DistBarGroup key={g.key} group={g} />)}
          </div>

          <div style={{ fontWeight: 600, fontSize: 14, margin: "22px 0 12px" }}>ความคิดเห็นจากผู้เข้าอบรม</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <TextAnswerList title="สิ่งสำคัญที่สุดที่ได้เรียนรู้จากการอบรมครั้งนี้" field="key_learning" responses={responses} color="var(--teal)" />
            <TextAnswerList title="จะนำความรู้ที่ได้ไปใช้ในการทำงานอะไร" field="will_apply_to" responses={responses} color="var(--purple)" />
          </div>
        </div>
      )}
    </div>
  );
};
window.SatisfactionDashboardScreen = SatisfactionDashboardScreen;
