// ===== Employee list screen + Profile drawer + forms =====

const EmployeeListScreen = ({ onBack, onOpenProfile, onAddEmployee, onResign, initialFilter }) => {
  const { DEPARTMENTS, EMPLOYEES } = window.MEI_DATA;
  const [query, setQuery] = React.useState("");
  const [deptFilter, setDeptFilter] = React.useState(initialFilter?.deptId || "all");
  const [statusFilter, setStatusFilter] = React.useState("active");
  const [genderFilter, setGenderFilter] = React.useState("all");
  const [ageRange, setAgeRange] = React.useState("all");
  const [selected, setSelected] = React.useState(new Set());
  const [sortBy, setSortBy] = React.useState("name");
  const [showFilters, setShowFilters] = React.useState(true);
  const toast = useToast();

  const filtered = React.useMemo(() => {
    let out = EMPLOYEES.filter(e => {
      if (statusFilter !== "all" && e.status !== statusFilter) return false;
      if (deptFilter !== "all" && e.deptId !== deptFilter) return false;
      if (genderFilter !== "all" && e.gender !== genderFilter) return false;
      if (ageRange === "<30" && e.age >= 30) return false;
      if (ageRange === "30-40" && (e.age < 30 || e.age > 40)) return false;
      if (ageRange === ">40" && e.age <= 40) return false;
      if (query) {
        const q = query.toLowerCase();
        const hay = (e.fullName + " " + e.position + " " + e.deptName + " " + e.code + " " + e.email).toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
    if (sortBy === "name") out.sort((a, b) => a.firstName.localeCompare(b.firstName, "th"));
    if (sortBy === "tenure") out.sort((a, b) => new Date(a.startDate) - new Date(b.startDate));
    if (sortBy === "salary") out.sort((a, b) => b.salary - a.salary);
    if (sortBy === "age") out.sort((a, b) => b.age - a.age);
    return out;
  }, [query, deptFilter, statusFilter, genderFilter, ageRange, sortBy]);

  const toggleOne = (id) => {
    const ns = new Set(selected);
    ns.has(id) ? ns.delete(id) : ns.add(id);
    setSelected(ns);
  };
  const toggleAll = () => {
    if (selected.size === filtered.length) setSelected(new Set());
    else setSelected(new Set(filtered.map(e => e.id)));
  };

  const doExport = (kind) => {
    toast.push(`กำลังเตรียมไฟล์ ${kind.toUpperCase()} (${filtered.length} รายการ)…`, { kind: "info" });
    setTimeout(() => {
      toast.push(`ดาวน์โหลดไฟล์ employees-${new Date().toISOString().slice(0,10)}.${kind} เรียบร้อย`, { kind: "success" });
    }, 1200);
  };

  return (
    <div className="page-enter">
      {/* HEADER */}
      <header style={{
        position: "sticky", top: 0, zIndex: 50,
        padding: "18px 32px",
        backdropFilter: "blur(12px)",
        background: "linear-gradient(to bottom, var(--bg-0) 60%, transparent)",
      }}>
        <div className="row gap-16">
          <button className="btn btn-ghost btn-sm" onClick={onBack}>
            <Icon name="chevron-l" size={14} /> Dashboard
          </button>
          <div className="col">
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.2 }}>รายชื่อพนักงาน</div>
            <div className="faint" style={{ fontSize: 12 }}>
              พบ {filtered.length} จาก {EMPLOYEES.length} รายการ
              {selected.size > 0 && <> · เลือกแล้ว <span style={{ color: "var(--teal)" }}>{selected.size}</span></>}
            </div>
          </div>

          <div className="spacer" />

          <div style={{ position: "relative", width: 340 }}>
            <Icon name="search" size={16} color="var(--text-faint)"
              style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)" }} />
            <input className="input" placeholder="ค้นหา ชื่อ, ตำแหน่ง, รหัสพนักงาน, อีเมล…"
              value={query} onChange={(e) => setQuery(e.target.value)}
              style={{ paddingLeft: 40 }} />
          </div>

          <button className="btn btn-ghost btn-sm" onClick={() => setShowFilters(v => !v)}>
            <Icon name="filter" size={14} /> ตัวกรอง
          </button>

          <button className="btn btn-sm" onClick={onAddEmployee}
            style={{ background: "rgba(0,212,168,0.12)", borderColor: "rgba(0,212,168,0.3)", color: "var(--teal)" }}>
            <Icon name="user-plus" size={14} /> เพิ่มพนักงาน
          </button>
        </div>

        {showFilters && (
          <div className="row gap-8" style={{ marginTop: 14, flexWrap: "wrap" }}>
            <FilterChip label="ทั้งหมด" active={deptFilter === "all"} onClick={() => setDeptFilter("all")}
              count={EMPLOYEES.filter(e => statusFilter === "all" || e.status === statusFilter).length} />
            {DEPARTMENTS.map(d => (
              <FilterChip key={d.id} label={d.name} active={deptFilter === d.id} color={d.color}
                onClick={() => setDeptFilter(d.id)}
                count={EMPLOYEES.filter(e => e.deptId === d.id && (statusFilter === "all" || e.status === statusFilter)).length} />
            ))}
            <div style={{ width: 1, height: 22, background: "var(--border)", margin: "0 4px" }} />
            <FilterChip label="Active" active={statusFilter === "active"} onClick={() => setStatusFilter("active")} />
            <FilterChip label="ลาออก" active={statusFilter === "resigned"} onClick={() => setStatusFilter("resigned")} />
            <FilterChip label="ทุกสถานะ" active={statusFilter === "all"} onClick={() => setStatusFilter("all")} />
            <div style={{ width: 1, height: 22, background: "var(--border)", margin: "0 4px" }} />
            <FilterChip label="ชาย" active={genderFilter === "ชาย"} onClick={() => setGenderFilter(g => g === "ชาย" ? "all" : "ชาย")} />
            <FilterChip label="หญิง" active={genderFilter === "หญิง"} onClick={() => setGenderFilter(g => g === "หญิง" ? "all" : "หญิง")} />
            <div style={{ width: 1, height: 22, background: "var(--border)", margin: "0 4px" }} />
            <FilterChip label="< 30 ปี" active={ageRange === "<30"} onClick={() => setAgeRange(a => a === "<30" ? "all" : "<30")} />
            <FilterChip label="30-40 ปี" active={ageRange === "30-40"} onClick={() => setAgeRange(a => a === "30-40" ? "all" : "30-40")} />
            <FilterChip label="40+ ปี" active={ageRange === ">40"} onClick={() => setAgeRange(a => a === ">40" ? "all" : ">40")} />
          </div>
        )}
      </header>

      {/* BULK ACTION BAR */}
      {selected.size > 0 && (
        <div className="glass" style={{
          position: "sticky", top: 132, zIndex: 40,
          margin: "0 32px",
          padding: "10px 18px",
          display: "flex", alignItems: "center", gap: 12,
          background: "rgba(0,212,168,0.08)",
          borderColor: "rgba(0,212,168,0.3)",
        }}>
          <span style={{ fontSize: 13, fontWeight: 500 }}>
            <span style={{ color: "var(--teal)" }}>{selected.size}</span> รายการถูกเลือก
          </span>
          <div className="spacer" />
          <button className="btn btn-ghost btn-sm">
            <Icon name="edit" size={13} /> แก้ไขฝ่าย
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => doExport("xlsx")}>
            <Icon name="excel" size={13} color="#1cd6a8" /> Excel
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => doExport("pdf")}>
            <Icon name="pdf" size={13} color="#ff8a4c" /> PDF
          </button>
          <button className="btn btn-ghost btn-sm">
            <Icon name="user-minus" size={13} color="var(--pink)" /> บันทึกการลาออก
          </button>
          <button className="btn btn-ghost btn-icon btn-sm" onClick={() => setSelected(new Set())}>
            <Icon name="close" size={14} />
          </button>
        </div>
      )}

      {/* MAIN TABLE */}
      <div style={{ padding: "8px 32px 40px" }}>
        <div className="glass" style={{ overflow: "hidden" }}>
          <div className="row" style={{ padding: "12px 18px", borderBottom: "1px solid var(--border)" }}>
            <div className="row gap-10">
              <button className="tab-pill"
                style={{
                  padding: "5px 12px", fontSize: 12,
                  background: sortBy === "name" ? "rgba(124,92,255,0.18)" : "transparent",
                  color: sortBy === "name" ? "#a48cff" : "var(--text-dim)",
                  borderColor: sortBy === "name" ? "rgba(124,92,255,0.3)" : "var(--border)"
                }}
                onClick={() => setSortBy("name")}>เรียงตามชื่อ</button>
              <button className="tab-pill" style={{
                padding: "5px 12px", fontSize: 12,
                background: sortBy === "tenure" ? "rgba(124,92,255,0.18)" : "transparent",
                color: sortBy === "tenure" ? "#a48cff" : "var(--text-dim)",
                borderColor: sortBy === "tenure" ? "rgba(124,92,255,0.3)" : "var(--border)"
              }} onClick={() => setSortBy("tenure")}>เรียงตามอายุงาน</button>
              <button className="tab-pill" style={{
                padding: "5px 12px", fontSize: 12,
                background: sortBy === "age" ? "rgba(124,92,255,0.18)" : "transparent",
                color: sortBy === "age" ? "#a48cff" : "var(--text-dim)",
                borderColor: sortBy === "age" ? "rgba(124,92,255,0.3)" : "var(--border)"
              }} onClick={() => setSortBy("age")}>เรียงตามอายุ</button>
            </div>
            <div className="spacer" />
            <div className="row gap-8">
              <button className="btn btn-ghost btn-sm" onClick={() => doExport("xlsx")}>
                <Icon name="excel" size={14} color="#1cd6a8" /> Export Excel
              </button>
              <button className="btn btn-ghost btn-sm" onClick={() => doExport("pdf")}>
                <Icon name="pdf" size={14} color="#ff8a4c" /> Export PDF
              </button>
            </div>
          </div>

          <div style={{ maxHeight: "calc(100vh - 280px)", overflowY: "auto" }}>
            <table className="table">
              <thead>
                <tr>
                  <th style={{ width: 40 }}>
                    <CheckBox checked={selected.size === filtered.length && filtered.length > 0} onChange={toggleAll} />
                  </th>
                  <th>พนักงาน</th>
                  <th>ฝ่าย / ตำแหน่ง</th>
                  <th>อายุ</th>
                  <th>อายุงาน</th>
                  <th>วันเริ่มงาน</th>
                  <th>สถานะ</th>
                  <th style={{ width: 60, textAlign: "right" }}></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((e, i) => {
                  const dept = DEPARTMENTS.find(d => d.id === e.deptId);
                  const isSel = selected.has(e.id);
                  return (
                    <tr key={e.id} className={isSel ? "selected" : ""}
                      onClick={() => onOpenProfile(e)}
                      style={{ animationDelay: `${Math.min(i, 20) * 0.02}s` }}>
                      <td onClick={(ev) => ev.stopPropagation()}>
                        <CheckBox checked={isSel} onChange={() => toggleOne(e.id)} />
                      </td>
                      <td>
                        <div className="row gap-10">
                          <Avatar person={e} size={36} />
                          <div className="col">
                            <div style={{ fontSize: 13.5, fontWeight: 500 }}>{e.fullName}</div>
                            <div className="faint" style={{ fontSize: 11.5 }}>
                              {e.code} · {e.gender} · {e.nickname}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td>
                        <DeptPill dept={dept} small />
                        <div className="faint" style={{ fontSize: 11.5, marginTop: 3 }}>{e.position}</div>
                      </td>
                      <td className="num-display" style={{ fontSize: 13.5 }}>{e.age}</td>
                      <td>
                        <div style={{ fontSize: 13 }}>{fmtTenure(e.startDate, e.endDate)}</div>
                      </td>
                      <td>
                        <div style={{ fontSize: 12.5 }}>{fmtThaiDate(e.startDate)}</div>
                      </td>
                      <td><StatusPill status={e.status} /></td>
                      <td style={{ textAlign: "right" }} onClick={(ev) => ev.stopPropagation()}>
                        <button className="btn btn-ghost btn-icon btn-sm">
                          <Icon name="more" size={14} />
                        </button>
                      </td>
                    </tr>
                  );
                })}
                {filtered.length === 0 && (
                  <tr><td colSpan="8" style={{ textAlign: "center", padding: "60px 20px" }}>
                    <div className="faint" style={{ fontSize: 14 }}>ไม่พบพนักงานตามเงื่อนไขที่กำหนด</div>
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

const FilterChip = ({ label, active, onClick, count, color }) => (
  <button onClick={onClick} style={{
    padding: "6px 12px",
    borderRadius: 999,
    fontSize: 12.5,
    border: "1px solid",
    borderColor: active ? (color || "var(--teal)") : "var(--border)",
    background: active ? `${color || "#00d4a8"}1f` : "transparent",
    color: active ? (color || "var(--teal)") : "var(--text-dim)",
    cursor: "pointer",
    fontFamily: "var(--font)",
    display: "inline-flex", alignItems: "center", gap: 6,
    transition: "all .15s",
  }}>
    {color && active && <span className="dot" style={{ background: color }} />}
    {label}
    {count != null && (
      <span className="num-display" style={{ opacity: 0.7, fontSize: 11 }}>{count}</span>
    )}
  </button>
);

window.EmployeeListScreen = EmployeeListScreen;
