// รายการแบบประเมินทั้งหมด + Detail drawer
const EvalListScreen = ({ onBack, onNewEval, onDataChange, user }) => {
  const [evals, setEvals]     = React.useState(window.TRN_DATA.EVALS || []);
  const [search, setSearch]   = React.useState("");
  const [filterStatus, setFilterStatus] = React.useState("");
  const [selected, setSelected]   = React.useState(null);
  const [deleteTarget, setDeleteTarget] = React.useState(null);
  const { push } = useToast();

  React.useEffect(() => { setEvals(window.TRN_DATA.EVALS || []); }, []);

  const filtered = React.useMemo(() => evals.filter(e => {
    if (filterStatus && e.status !== filterStatus) return false;
    if (search) {
      const q = search.toLowerCase();
      return e.trainee_name?.toLowerCase().includes(q) || e.course_name?.toLowerCase().includes(q) || e.dept?.toLowerCase().includes(q);
    }
    return true;
  }), [evals, search, filterStatus]);

  const openDetail = async row => {
    try { setSelected(await window.TRN_API.getEval(row.id)); }
    catch { setSelected(row); }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await window.TRN_API.deleteEval(deleteTarget.id);
      push("ลบแบบประเมินเรียบร้อย", { kind:"success" });
      setEvals(p => p.filter(e => e.id !== deleteTarget.id));
      if (selected?.id === deleteTarget.id) setSelected(null);
      onDataChange?.();
    } catch(e) { push(e.message || "ลบไม่สำเร็จ", { kind:"error" }); }
    finally { setDeleteTarget(null); }
  };

  const statusOpts = [
    { v:"", l:"ทั้งหมด" },
    { v:"draft", l:"ยังไม่ประเมิน" },
    { v:"self_done", l:"รอผู้บังคับบัญชา" },
    { v:"sup_done", l:"รอฝ่ายบุคคล" },
    { v:"completed", l:"เสร็จสมบูรณ์" },
  ];

  return (
    <div style={{ minHeight:"100vh" }}>
      <GlowBlob color="rgba(0,212,168,0.2)" x={-60} y={0} size={400} opacity={0.18} />

      {/* Topbar */}
      <div style={{ padding:"16px 26px", display:"flex", alignItems:"center", gap:12, borderBottom:"1px solid var(--border)", backdropFilter:"blur(10px)", position:"sticky", top:0, zIndex:100, background:"var(--bg-bar, rgba(15,15,25,0.85))" }}>
        <button className="btn btn-ghost btn-sm" onClick={onBack}><Icon name="chevron-l" size={15} /> กลับ</button>
        <div style={{ fontWeight:600, fontSize:14 }}>รายการแบบประเมินทั้งหมด</div>
        <div className="faint" style={{ fontSize:12 }}>({filtered.length} รายการ)</div>
        <div style={{ flex:1 }} />
        {user?.canEdit && (
          <button className="btn btn-primary btn-sm shine" onClick={onNewEval}><Icon name="user-plus" size={13} /> เพิ่มแบบประเมิน</button>
        )}
      </div>

      {/* Filters */}
      <div style={{ padding:"14px 26px", display:"flex", gap:10, alignItems:"center", borderBottom:"1px solid var(--border)" }}>
        <div style={{ position:"relative", flex:1, maxWidth:320 }}>
          <Icon name="search" size={14} color="var(--text-faint)" style={{ position:"absolute", left:11, top:"50%", transform:"translateY(-50%)" }} />
          <input className="input" style={{ paddingLeft:33, height:34 }} placeholder="ค้นหาชื่อ, หลักสูตร, แผนก…" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        {statusOpts.map(s => (
          <button key={s.v} className={`btn btn-sm ${filterStatus === s.v ? "btn-primary" : "btn-ghost"}`} onClick={() => setFilterStatus(s.v)}>{s.l}</button>
        ))}
      </div>

      <div style={{ padding:"18px 26px" }}>
        {filtered.length === 0 ? (
          <div className="faint" style={{ textAlign:"center", padding:"60px 0", fontSize:14 }}>ไม่พบข้อมูล</div>
        ) : (
          <div className="glass" style={{ borderRadius:14, overflow:"hidden" }}>
            <table style={{ width:"100%", borderCollapse:"collapse" }}>
              <thead>
                <tr style={{ borderBottom:"1px solid var(--border)" }}>
                  {["ผู้เข้าอบรม","ตำแหน่ง","หลักสูตร","แผนก","วันที่อบรม","ประเมินตนเอง","ผู้บังคับบัญชา","สถานะ",""].map(h => (
                    <th key={h} style={{ padding:"9px 12px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"left", whiteSpace:"nowrap" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((e, i) => {
                  const sa = selfAvg(e), pa = supAvg(e);
                  return (
                    <tr key={e.id} onClick={() => openDetail(e)}
                      style={{ borderBottom:i<filtered.length-1?"1px solid var(--border)":"none", cursor:"pointer" }}
                      onMouseEnter={ev=>ev.currentTarget.style.background="var(--surface)"}
                      onMouseLeave={ev=>ev.currentTarget.style.background=""}>
                      <td style={{ padding:"10px 12px", fontWeight:500, fontSize:13 }}>{e.trainee_name}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, color:"var(--text-muted)" }}>{e.trainee_position || "—"}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, maxWidth:200, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{e.course_name}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, color:"var(--text-muted)" }}>{e.dept || "—"}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, whiteSpace:"nowrap" }}>{fmtThaiDate(e.course_date)}</td>
                      <td style={{ padding:"10px 12px", textAlign:"center" }}>
                        {sa ? <span style={{ fontSize:12, fontWeight:600, color:"var(--teal)" }}>{sa}</span> : <span className="faint" style={{ fontSize:12 }}>—</span>}
                      </td>
                      <td style={{ padding:"10px 12px", textAlign:"center" }}>
                        {pa ? <span style={{ fontSize:12, fontWeight:600, color:"var(--purple)" }}>{pa}</span> : <span className="faint" style={{ fontSize:12 }}>—</span>}
                      </td>
                      <td style={{ padding:"10px 12px" }}><StatusChip status={e.status} /></td>
                      <td style={{ padding:"10px 12px" }}>
                        {user?.canDelete && (
                          <button className="btn btn-ghost btn-sm" style={{ color:"var(--pink)", padding:"3px 7px" }}
                            onClick={ev => { ev.stopPropagation(); setDeleteTarget(e); }}>
                            <Icon name="trash" size={13} />
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <Drawer open={!!selected} onClose={() => setSelected(null)} width={640}>
        {selected && <EvalDetail eval={selected} onClose={() => setSelected(null)} user={user}
          onUpdate={updated => { setSelected(updated); setEvals(p => p.map(e => e.id===updated.id ? updated : e)); onDataChange?.(); }} />}
      </Drawer>

      <ConfirmDialog open={!!deleteTarget} title="ลบแบบประเมิน"
        message={`ต้องการลบแบบประเมินของ "${deleteTarget?.trainee_name}" ใช่หรือไม่?`}
        onConfirm={handleDelete} onCancel={() => setDeleteTarget(null)} danger />
    </div>
  );
};

// ----- Detail drawer -----
const SCORE_LABELS = { 5:"มากสุด", 4:"มาก", 3:"กลาง", 2:"น้อย", 1:"น้อยสุด" };

const EvalDetail = ({ eval: ev, onClose, onUpdate, user }) => {
  const [saving, setSaving] = React.useState(false);
  const { push } = useToast();
  const qs = window.EVAL_QUESTIONS;

  const scoreColor = s => s >= 4 ? "var(--teal)" : s >= 3 ? "var(--yellow)" : "var(--pink)";

  const ScoreCell = ({ score }) => score
    ? <div style={{ textAlign:"center" }}><span style={{ fontWeight:600, color:scoreColor(score), fontSize:13 }}>{score}</span><div style={{ fontSize:10, color:"var(--text-muted)" }}>{SCORE_LABELS[score]}</div></div>
    : <div className="faint" style={{ textAlign:"center", fontSize:13 }}>—</div>;

  // HR sign-off
  const signHR = async () => {
    setSaving(true);
    try {
      const updated = await window.TRN_API.updateEval(ev.id, {
        hr_sig_date: new Date().toISOString().slice(0,10),
        hr_sig_name: user.name || user.email,
      });
      onUpdate(updated);
      push("ฝ่ายบุคคลรับรองแล้ว", { kind:"success" });
    } catch(e) { push(e.message, { kind:"error" }); }
    finally { setSaving(false); }
  };

  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column" }}>
      {/* Header */}
      <div style={{ padding:"18px 20px 14px", borderBottom:"1px solid var(--border)", display:"flex", justifyContent:"space-between", alignItems:"flex-start" }}>
        <div>
          <div style={{ fontWeight:700, fontSize:16 }}>{ev.trainee_name}</div>
          <div className="faint" style={{ fontSize:12 }}>{ev.trainee_position} {ev.dept ? `· ${ev.dept}` : ""}</div>
        </div>
        <div className="row gap-8">
          <StatusChip status={ev.status} />
          <button className="btn btn-ghost btn-sm" onClick={onClose} style={{ padding:"5px 7px" }}><Icon name="close" size={15} /></button>
        </div>
      </div>

      <div style={{ flex:1, overflowY:"auto", padding:"16px 20px" }}>
        {/* Course info */}
        <div className="glass" style={{ borderRadius:12, padding:"13px 15px", marginBottom:16 }}>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 }}>
            {[
              { l:"หลักสูตร", v:ev.course_name },
              { l:"วันที่อบรม", v:fmtThaiDate(ev.course_date) },
              { l:"วันที่ติดตามผล", v:fmtThaiDate(ev.follow_up_date) },
              { l:"แผนก", v:ev.dept || "—" },
            ].map(r => (
              <div key={r.l}><div style={{ fontSize:11, color:"var(--text-muted)", marginBottom:3 }}>{r.l}</div><div style={{ fontSize:13, fontWeight:500 }}>{r.v || "—"}</div></div>
            ))}
          </div>
        </div>

        {/* Score comparison table */}
        <div style={{ fontWeight:600, fontSize:13.5, marginBottom:10 }}>ผลการประเมินพฤติกรรม</div>
        <div className="glass" style={{ borderRadius:12, overflow:"hidden", marginBottom:16 }}>
          <table style={{ width:"100%", borderCollapse:"collapse" }}>
            <thead>
              <tr style={{ borderBottom:"1px solid var(--border)" }}>
                <th style={{ padding:"9px 13px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"left", width:30 }}>#</th>
                <th style={{ padding:"9px 13px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"left" }}>ด้านพฤติกรรม</th>
                <th style={{ padding:"9px 13px", fontSize:11, color:"var(--teal)", fontWeight:500, textAlign:"center", whiteSpace:"nowrap" }}>ประเมินตนเอง</th>
                <th style={{ padding:"9px 13px", fontSize:11, color:"var(--purple)", fontWeight:500, textAlign:"center", whiteSpace:"nowrap" }}>ผู้บังคับบัญชา</th>
              </tr>
            </thead>
            <tbody>
              {qs.map((q,i) => (
                <tr key={q.key} style={{ borderBottom:i<qs.length-1?"1px solid var(--border)":"none" }}>
                  <td style={{ padding:"9px 13px", fontSize:12, color:"var(--text-muted)" }}>{i+1}</td>
                  <td style={{ padding:"9px 13px", fontSize:13 }}>{q.label} <span className="faint" style={{ fontSize:11 }}>({q.en})</span></td>
                  <td style={{ padding:"9px 13px" }}><ScoreCell score={ev[`self_${q.key}`]} /></td>
                  <td style={{ padding:"9px 13px" }}><ScoreCell score={ev[`sup_${q.key}`]} /></td>
                </tr>
              ))}
              <tr style={{ borderTop:"2px solid var(--border)", background:"var(--surface)" }}>
                <td colSpan={2} style={{ padding:"9px 13px", fontSize:12, fontWeight:600 }}>คะแนนเฉลี่ย</td>
                <td style={{ padding:"9px 13px", textAlign:"center" }}>
                  {selfAvg(ev) ? <span style={{ fontWeight:700, color:"var(--teal)", fontSize:15 }}>{selfAvg(ev)}</span> : <span className="faint">—</span>}
                </td>
                <td style={{ padding:"9px 13px", textAlign:"center" }}>
                  {supAvg(ev)  ? <span style={{ fontWeight:700, color:"var(--purple)", fontSize:15 }}>{supAvg(ev)}</span>  : <span className="faint">—</span>}
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        {/* Descriptions */}
        {ev.self_description && (
          <div style={{ marginBottom:12 }}>
            <div style={{ fontSize:12, color:"var(--teal)", fontWeight:600, marginBottom:6 }}>อธิบาย (ประเมินตนเอง)</div>
            <div className="glass" style={{ borderRadius:10, padding:"11px 13px", fontSize:13, lineHeight:1.65 }}>{ev.self_description}</div>
          </div>
        )}
        {ev.sup_description && (
          <div style={{ marginBottom:12 }}>
            <div style={{ fontSize:12, color:"var(--purple)", fontWeight:600, marginBottom:6 }}>อธิบาย (ผู้บังคับบัญชา)</div>
            <div className="glass" style={{ borderRadius:10, padding:"11px 13px", fontSize:13, lineHeight:1.65 }}>{ev.sup_description}</div>
          </div>
        )}

        {/* Signatures */}
        <div style={{ marginTop:16, fontWeight:600, fontSize:13.5, marginBottom:10 }}>ลายเซ็น</div>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:10 }}>
          {[
            { role:"พนักงาน",            name:ev.self_sig_name,  date:ev.self_sig_date,  done:!!ev.self_submitted_at, color:"var(--teal)" },
            { role:"ผู้บังคับบัญชา",    name:ev.sup_sig_name,   date:ev.sup_sig_date,   done:!!ev.sup_submitted_at,  color:"var(--purple)" },
            { role:"ฝ่ายบุคคล",          name:ev.hr_sig_name,    date:ev.hr_sig_date,    done:!!ev.hr_sig_date,       color:"var(--yellow)" },
          ].map((s,i) => (
            <div key={i} className="glass" style={{ borderRadius:10, padding:"12px 13px", border:s.done?"1px solid rgba(0,212,168,0.35)":"1px solid var(--border)" }}>
              <div style={{ fontSize:11, color:"var(--text-muted)", marginBottom:5 }}>{s.role}</div>
              <div style={{ fontSize:13, fontWeight:600, marginBottom:2 }}>{s.name || "—"}</div>
              <div style={{ fontSize:11, color:"var(--text-muted)" }}>{s.date ? fmtThaiDate(s.date) : "—"}</div>
              {s.done && <div style={{ marginTop:6 }}><span className="chip chip-teal" style={{ fontSize:10 }}><Icon name="check" size={10} /> รับรองแล้ว</span></div>}
            </div>
          ))}
        </div>

        {/* HR sign-off button */}
        {user?.isHrOrAdmin && ev.status === "sup_done" && !ev.hr_sig_date && (
          <button className="btn btn-primary shine" style={{ width:"100%", height:42, justifyContent:"center", marginTop:16 }}
            onClick={signHR} disabled={saving}>
            {saving ? "กำลังบันทึก…" : <><Icon name="check" size={15} /> ฝ่ายบุคคลรับรอง</>}
          </button>
        )}
      </div>
    </div>
  );
};

window.EvalListScreen = EvalListScreen;
