const DashboardScreen = ({ onNewEval, onViewAll, onLogout, user }) => {
  const stats  = window.TRN_STATS;
  const recent = stats?.recent || [];
  const qs     = window.EVAL_QUESTIONS;

  const statCards = [
    { label:"แบบประเมินทั้งหมด", value: stats?.total ?? "—",                        color:"var(--teal)",   icon:"briefcase" },
    { label:"เสร็จสมบูรณ์",       value: stats?.statusMap?.completed ?? 0,            color:"var(--teal)",   icon:"check" },
    { label:"รอผู้บังคับบัญชา",  value: stats?.statusMap?.self_done ?? 0,            color:"var(--yellow)", icon:"hourglass" },
    { label:"ยังไม่ได้ประเมิน",  value: stats?.statusMap?.draft ?? 0,                color:"var(--pink)",   icon:"users" },
  ];

  const avg = stats?.avgScores || {};
  const selfAvgs = qs.map((q,i) => avg[`s${i+1}`] || 0);
  const supAvgs  = qs.map((q,i) => avg[`p${i+1}`] || 0);

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

      {/* Topbar */}
      <div style={{ padding:"18px 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-bar, rgba(15,15,25,0.85))" }}>
        <div className="row gap-12">
          <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={onNewEval}>
              <Icon name="user-plus" size={14} /> เพิ่มแบบประเมิน
            </button>
          )}
          <button className="btn btn-ghost btn-sm" onClick={onViewAll}><Icon name="briefcase" 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:"28px 28px 0", maxWidth:1400, margin:"0 auto" }}>
        {/* Stat cards */}
        <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:14, marginBottom:24 }}>
          {statCards.map((c,i) => (
            <div key={i} className="glass" style={{ padding:"20px 20px 16px", borderRadius:14, position:"relative", overflow:"hidden" }}>
              <div style={{ position:"absolute", right:14, top:14, opacity:0.12 }}><Icon name={c.icon} size={38} color={c.color} /></div>
              <div className="faint" style={{ fontSize:11.5, marginBottom:5 }}>{c.label}</div>
              <div style={{ fontSize:32, fontWeight:700, color:c.color, lineHeight:1 }}>{c.value}</div>
            </div>
          ))}
        </div>

        <div style={{ display:"grid", gridTemplateColumns:"1fr 340px", gap:18, marginBottom:18 }}>
          {/* Avg scores table */}
          <div className="glass" style={{ borderRadius:14, padding:"20px 22px" }}>
            <div style={{ fontWeight:600, fontSize:14, marginBottom:16 }}>คะแนนเฉลี่ยรายด้าน (เต็ม 5)</div>
            {selfAvgs.every(v => v === 0) ? (
              <div className="faint" style={{ fontSize:13, textAlign:"center", padding:"24px 0" }}>ยังไม่มีข้อมูลการประเมิน</div>
            ) : (
              <div className="col gap-10">
                {qs.map((q, i) => (
                  <div key={q.key} style={{ display:"grid", gridTemplateColumns:"160px 1fr 80px 1fr", alignItems:"center", gap:10 }}>
                    <div style={{ fontSize:12.5 }}>{q.label}</div>
                    <ScoreBar score={selfAvgs[i]} />
                    <div className="faint" style={{ fontSize:11, textAlign:"center" }}>ตนเอง</div>
                    <ScoreBar score={supAvgs[i]} />
                  </div>
                ))}
                <div className="faint" style={{ fontSize:11, marginTop:6, textAlign:"right" }}>
                  <span style={{ marginRight:16 }}>■ ประเมินตนเอง</span>
                  <span>■ ผู้บังคับบัญชา</span>
                </div>
              </div>
            )}
          </div>

          {/* By dept */}
          <div className="col gap-16">
            <div className="glass" style={{ borderRadius:14, padding:"18px 20px", flex:1 }}>
              <div style={{ fontWeight:600, fontSize:14, marginBottom:14 }}>แยกตามแผนก</div>
              {(stats?.byDept || []).length === 0 ? (
                <div className="faint" style={{ fontSize:13 }}>ยังไม่มีข้อมูล</div>
              ) : (
                <div className="col gap-10">
                  {(stats?.byDept || []).map((d,i) => {
                    const colors = ["var(--teal)","var(--purple)","var(--yellow)","var(--pink)","var(--blue)"];
                    const c = colors[i % colors.length];
                    const max = stats.byDept[0].c;
                    return (
                      <div key={d.dept}>
                        <div style={{ display:"flex", justifyContent:"space-between", marginBottom:4 }}>
                          <div style={{ fontSize:12.5 }}>{d.dept || "ไม่ระบุ"}</div>
                          <div style={{ fontSize:12, color:c, fontWeight:600 }}>{d.c}</div>
                        </div>
                        <div style={{ height:5, borderRadius:3, background:"var(--surface)", overflow:"hidden" }}>
                          <div style={{ width:`${(d.c/max)*100}%`, height:"100%", background:c, borderRadius:3 }} />
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Recent + Activity */}
        <div style={{ display:"grid", gridTemplateColumns:"1fr 320px", gap:18 }}>
          <div className="glass" style={{ borderRadius:14, padding:"20px 22px" }}>
            <div className="row" style={{ justifyContent:"space-between", marginBottom:14 }}>
              <div style={{ fontWeight:600, fontSize:14 }}>แบบประเมินล่าสุด</div>
              <button className="btn btn-ghost btn-sm" onClick={onViewAll} style={{ fontSize:12 }}>ดูทั้งหมด →</button>
            </div>
            {recent.length === 0 ? (
              <div className="faint" style={{ fontSize:13, textAlign:"center", padding:"24px 0" }}>ยังไม่มีข้อมูล</div>
            ) : (
              <table style={{ width:"100%", borderCollapse:"collapse" }}>
                <thead>
                  <tr style={{ borderBottom:"1px solid var(--border)" }}>
                    {["ผู้เข้าอบรม","หลักสูตร","แผนก","วันที่อบรม","สถานะ"].map(h => (
                      <th key={h} style={{ padding:"8px 12px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"left" }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {recent.map((r, i) => (
                    <tr key={r.id} style={{ borderBottom: i<recent.length-1?"1px solid var(--border)":"none" }}
                        onClick={() => onViewAll()} style={{ cursor:"pointer" }}
                        onMouseEnter={e=>e.currentTarget.style.background="var(--surface)"}
                        onMouseLeave={e=>e.currentTarget.style.background=""}>
                      <td style={{ padding:"10px 12px", fontSize:13, fontWeight:500 }}>{r.trainee_name}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, color:"var(--text-muted)", maxWidth:180, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{r.course_name}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, color:"var(--text-muted)" }}>{r.dept || "—"}</td>
                      <td style={{ padding:"10px 12px", fontSize:12, color:"var(--text-muted)", whiteSpace:"nowrap" }}>{fmtThaiDate(r.course_date)}</td>
                      <td style={{ padding:"10px 12px" }}><StatusChip status={r.status} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          <div className="glass" style={{ borderRadius:14, padding:"18px 20px" }}>
            <div style={{ fontWeight:600, fontSize:14, marginBottom:14 }}>ความเคลื่อนไหว</div>
            {(stats?.activity || []).length === 0 ? (
              <div className="faint" style={{ fontSize:13 }}>ยังไม่มีกิจกรรม</div>
            ) : (
              <div className="col gap-0">
                {(stats?.activity || []).map((a,i) => (
                  <div key={a.id} style={{ display:"flex", gap:8, padding:"9px 0", borderBottom:i<(stats.activity.length-1)?"1px solid var(--border)":"none" }}>
                    <div style={{ width:6, height:6, borderRadius:"50%", background:"var(--teal)", marginTop:5, flexShrink:0 }} />
                    <div>
                      <div style={{ fontSize:12.5, lineHeight:1.5 }}>{a.detail}</div>
                      <div className="faint" style={{ fontSize:11, marginTop:1 }}>{relativeTime(a.created_at)}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
window.DashboardScreen = DashboardScreen;
