// หน้าหลัก — รายการหลักสูตร (คลิกเข้าไปดูรายชื่อผู้เข้าอบรมของแต่ละหลักสูตร)
const CourseListScreen = ({ user, onOpenCourse, onNewCourse, onEditCourse, onOpenSummary, onDashboard, onOpenSatisfaction, onLogout, onDataChange }) => {
  const [courses, setCourses] = React.useState(window.TRN_DATA.COURSES || []);
  const [search, setSearch]   = React.useState("");
  const [deleteTarget, setDeleteTarget] = React.useState(null);
  const { push } = useToast();

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

  const filtered = React.useMemo(() => courses.filter(c => {
    if (!search) return true;
    const q = search.toLowerCase();
    return c.course_name?.toLowerCase().includes(q) || c.trainer?.toLowerCase().includes(q);
  }), [courses, search]);

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await window.TRN_API.deleteCourse(deleteTarget.id);
      push("ลบหลักสูตรเรียบร้อย", { kind:"success" });
      setCourses(p => p.filter(c => c.id !== deleteTarget.id));
      onDataChange?.();
    } catch(e) { push(e.message || "ลบไม่สำเร็จ", { kind:"error" }); }
    finally { setDeleteTarget(null); }
  };

  return (
    <div style={{ minHeight:"100vh", paddingBottom:60 }}>
      <GlowBlob color="rgba(0,212,168,0.3)" x={-80} y={-60} size={500} opacity={0.22} />
      <GlowBlob color="rgba(124,92,255,0.25)" x="65vw" y="25vh" size={400} opacity={0.16} />

      {/* Topbar */}
      <div style={{ padding:"16px 28px", display:"flex", alignItems:"center", justifyContent:"space-between", borderBottom:"1px solid var(--border)", backdropFilter:"blur(10px)", position:"sticky", top:0, zIndex:100, background:"var(--bg-1)" }}>
        <div className="row gap-12">
          <a href="https://myempinfo.pages.dev" className="btn btn-ghost btn-icon" title="กลับหน้าหลัก (Landing)"><Icon name="chevron-l" size={16} /></a>
          <div style={{ width:36, height:36, borderRadius:10, background:"linear-gradient(135deg,#00d4a8,#7c5cff)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:13, color:"#fff", fontWeight:700 }}>TF</div>
          <div><div style={{ fontWeight:600, fontSize:14 }}>Training Follow-Up</div><div className="faint" style={{ fontSize:11 }}>ระบบติดตามผลการฝึกอบรม</div></div>
        </div>
        <div className="row gap-10">
          {user?.canEdit && (
            <button className="btn btn-primary btn-sm shine" onClick={onNewCourse}><Icon name="user-plus" size={14} /> เพิ่มหลักสูตร</button>
          )}
          <button className="btn btn-ghost btn-sm" onClick={onDashboard}><Icon name="briefcase" size={14} /> แดชบอร์ด</button>
          {onOpenSatisfaction && (
            <button className="btn btn-ghost btn-sm" onClick={onOpenSatisfaction}><Icon name="chart-pie" size={14} /> ความพึงพอใจ</button>
          )}
          <button className="btn btn-ghost btn-sm" title="ตั้งค่าธีม" onClick={() => window.postMessage({ type: '__activate_edit_mode' }, '*')}><Icon name="sliders" size={14} /></button>
          <div className="row gap-8" style={{ padding:"5px 10px", borderRadius:8, background:"var(--surface)", border:"1px solid var(--border)" }}>
            <div style={{ width:26, height:26, borderRadius:"50%", background:"linear-gradient(135deg,#00d4a855,#7c5cff55)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, fontWeight:600 }}>
              {user?.email?.[0]?.toUpperCase() || "U"}
            </div>
            <div style={{ fontSize:12, fontWeight:500 }}>{user?.name || user?.email}</div>
            <button className="btn btn-ghost btn-sm" onClick={onLogout} style={{ padding:"3px 6px" }}><Icon name="logout" size={13} /></button>
          </div>
        </div>
      </div>

      <div style={{ padding:"24px 28px 0", maxWidth:1200, margin:"0 auto" }}>
        <div className="row" style={{ justifyContent:"space-between", marginBottom:18 }}>
          <div>
            <div style={{ fontWeight:700, fontSize:20 }}>หลักสูตรการอบรม</div>
            <div className="faint" style={{ fontSize:13, marginTop:2 }}>{filtered.length} หลักสูตร — คลิกเพื่อดู/บันทึกผู้เข้าอบรม</div>
          </div>
          <div style={{ position:"relative", width:280 }}>
            <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:36 }} placeholder="ค้นหาหลักสูตร, วิทยากร…" value={search} onChange={e=>setSearch(e.target.value)} />
          </div>
        </div>

        {filtered.length === 0 ? (
          <div className="glass" style={{ borderRadius:14, padding:"60px 0", textAlign:"center" }}>
            <div className="faint" style={{ fontSize:14, marginBottom:14 }}>ยังไม่มีหลักสูตร</div>
            {user?.canEdit && <button className="btn btn-primary shine" onClick={onNewCourse}><Icon name="user-plus" size={14} /> สร้างหลักสูตรแรก</button>}
          </div>
        ) : (
          <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(330px, 1fr))", gap:16 }}>
            {filtered.map(c => (
              <div key={c.id} className="glass" onClick={() => onOpenCourse(c.id)}
                style={{ borderRadius:14, padding:"18px 20px", cursor:"pointer", position:"relative", transition:"transform .12s, box-shadow .12s" }}
                onMouseEnter={e=>{ e.currentTarget.style.transform="translateY(-2px)"; e.currentTarget.style.boxShadow="0 8px 24px rgba(0,0,0,0.08)"; }}
                onMouseLeave={e=>{ e.currentTarget.style.transform=""; e.currentTarget.style.boxShadow=""; }}>
                <div className="row" style={{ justifyContent:"space-between", alignItems:"flex-start", gap:8 }}>
                  <div style={{ fontWeight:600, fontSize:15, lineHeight:1.4, flex:1 }}>{c.course_name}</div>
                  {user?.canDelete && (
                    <button className="btn btn-ghost btn-sm" style={{ color:"var(--pink)", padding:"3px 6px", flexShrink:0 }}
                      onClick={e=>{ e.stopPropagation(); setDeleteTarget(c); }}><Icon name="trash" size={13} /></button>
                  )}
                </div>
                <div className="faint" style={{ fontSize:12, marginTop:8, display:"flex", flexDirection:"column", gap:4 }}>
                  <div><Icon name="hourglass" size={12} /> อบรม {fmtThaiDate(c.course_date)}</div>
                  <div><Icon name="check" size={12} /> ติดตามผล {fmtThaiDate(c.follow_up_date)}</div>
                  {c.trainer && <div><Icon name="users" size={12} /> {c.trainer}</div>}
                </div>
                <div style={{ marginTop:14, paddingTop:12, borderTop:"1px solid var(--border)", display:"flex", alignItems:"center", justifyContent:"space-between", gap:8 }}>
                  <div style={{ fontSize:13 }}>
                    <span style={{ fontWeight:700, fontSize:18, color:"var(--teal)" }}>{c.people || 0}</span>
                    <span className="faint" style={{ fontSize:12, marginLeft:5 }}>คน</span>
                  </div>
                  <div className="row gap-6">
                    {c.completed > 0 && <span className="chip chip-teal" style={{ fontSize:10 }}>เสร็จ {c.completed}</span>}
                    {(c.self_done > 0 || c.sup_done > 0) && <span className="chip chip-yellow" style={{ fontSize:10 }}>รอ {(c.self_done||0)+(c.sup_done||0)}</span>}
                    {c.draft > 0 && <span className="chip" style={{ fontSize:10 }}>ร่าง {c.draft}</span>}
                  </div>
                </div>
                {(c.people || 0) > 0 && onOpenSummary && (
                  <button className="btn btn-ghost btn-sm" style={{ width:"100%", marginTop:10, justifyContent:"center" }}
                    onClick={e => { e.stopPropagation(); onOpenSummary(c); }}>
                    <Icon name="trend" size={13} /> สรุปผลคะแนน
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <ConfirmDialog open={!!deleteTarget} title="ลบหลักสูตร"
        message={`ลบหลักสูตร "${deleteTarget?.course_name}" และผู้เข้าอบรมทั้งหมดในหลักสูตรนี้? (${deleteTarget?.people||0} คน)`}
        onConfirm={handleDelete} onCancel={() => setDeleteTarget(null)} danger />
    </div>
  );
};
window.CourseListScreen = CourseListScreen;
