// ===== Drill-down modal, Profile drawer, New/Resign forms =====

const DrilldownModal = ({ open, data, onClose, onOpenProfile }) => {
  const toast = useToast();
  if (!open || !data) return null;
  const { DEPARTMENTS } = window.MEI_DATA;
  const employees = data.employees || [];
  const accent = data.accent || "#00d4a8";

  const [query, setQuery] = React.useState("");
  React.useEffect(() => { setQuery(""); }, [data]);

  const filtered = employees.filter(e => {
    if (!query) return true;
    const q = query.toLowerCase();
    return (e.fullName + e.position + e.deptName + e.code).toLowerCase().includes(q);
  });

  const doExport = (kind) => {
    toast.push(`กำลังเตรียมไฟล์ ${kind.toUpperCase()} (${filtered.length} รายการ)…`, { kind: "info" });
    setTimeout(() => {
      toast.push(`ดาวน์โหลด ${data.title.replace(/\s/g, "_")}.${kind} เรียบร้อย`, { kind: "success" });
    }, 1100);
  };

  return (
    <Modal open={open} onClose={onClose}>
      {/* Header */}
      <div style={{
        padding: "20px 26px 14px",
        borderBottom: "1px solid var(--border)",
        position: "relative",
        background: `linear-gradient(135deg, ${accent}15, transparent 60%)`,
      }}>
        <div className="row gap-12">
          <div style={{
            width: 40, height: 40, borderRadius: 10,
            background: `${accent}25`, color: accent,
            display: "flex", alignItems: "center", justifyContent: "center",
            flexShrink: 0,
          }}>
            <Icon name="chart-bar" size={18} />
          </div>
          <div className="col gap-4" style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: -0.2 }}>{data.title}</div>
            <div className="faint" style={{ fontSize: 12.5 }}>
              {data.subtitle || `ที่มาของข้อมูลในกราฟ · พบ ${filtered.length} รายการ · แสดงเฉพาะตามตัวกรองที่ใช้บน Dashboard`}
            </div>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}>
            <Icon name="close" size={16} />
          </button>
        </div>

        <div className="row gap-8" style={{ marginTop: 14 }}>
          <div style={{ position: "relative", flex: 1, maxWidth: 360 }}>
            <Icon name="search" size={14} color="var(--text-faint)"
              style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)" }} />
            <input className="input" style={{ paddingLeft: 36, height: 36 }}
              placeholder="ค้นหาในผลลัพธ์…"
              value={query} onChange={(e) => setQuery(e.target.value)} />
          </div>
          <div className="spacer" />
          <span className="chip" style={{
            background: `${accent}1f`, borderColor: `${accent}44`, color: accent,
            padding: "4px 12px",
          }}>
            <Icon name="users" size={12} /> {filtered.length} คน
          </span>
          <button className="btn btn-sm" onClick={() => doExport("xlsx")}
            style={{ background: "rgba(28,214,168,0.14)", borderColor: "rgba(28,214,168,0.35)", color: "#1cd6a8" }}>
            <Icon name="excel" size={14} /> Export Excel
          </button>
          <button className="btn btn-sm" onClick={() => doExport("pdf")}
            style={{ background: "rgba(255,138,76,0.14)", borderColor: "rgba(255,138,76,0.35)", color: "#ff8a4c" }}>
            <Icon name="pdf" size={14} /> Export PDF
          </button>
        </div>
      </div>

      {/* Body table */}
      <div style={{ overflowY: "auto", flex: 1, maxHeight: "70vh" }}>
        <table className="table">
          <thead>
            <tr>
              <th>พนักงาน</th>
              <th>ฝ่าย</th>
              <th>ตำแหน่ง</th>
              <th>อายุ</th>
              <th>อายุงาน</th>
              <th>วันเริ่มงาน</th>
              {data.employees.some(e => e.endDate) && <th>วันสิ้นสุด</th>}
              <th>สถานะ</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((e) => {
              const dept = DEPARTMENTS.find(d => d.id === e.deptId);
              return (
                <tr key={e.id} onClick={() => onOpenProfile(e)}>
                  <td>
                    <div className="row gap-10">
                      <Avatar person={e} size={32} />
                      <div className="col">
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{e.fullName}</div>
                        <div className="faint" style={{ fontSize: 11 }}>{e.code} · {e.gender}</div>
                      </div>
                    </div>
                  </td>
                  <td><DeptPill dept={dept} small /></td>
                  <td><span style={{ fontSize: 12.5 }}>{e.position}</span></td>
                  <td className="num-display" style={{ fontSize: 13 }}>{e.age}</td>
                  <td><span style={{ fontSize: 12.5 }}>{fmtTenure(e.startDate, e.endDate)}</span></td>
                  <td><span style={{ fontSize: 12 }}>{fmtThaiDate(e.startDate)}</span></td>
                  {data.employees.some(x => x.endDate) && (
                    <td><span style={{ fontSize: 12 }}>{fmtThaiDate(e.endDate)}</span></td>
                  )}
                  <td><StatusPill status={e.status} /></td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan="8" style={{ textAlign: "center", padding: 40 }}>
                <div className="faint">ไม่พบข้อมูล</div>
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Footer */}
      <div style={{
        padding: "12px 26px",
        borderTop: "1px solid var(--border)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        background: "rgba(0,0,0,0.18)",
      }}>
        <div className="faint" style={{ fontSize: 12 }}>
          คลิกที่แถวเพื่อดูประวัติเต็มของพนักงาน
        </div>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>ปิด</button>
      </div>
    </Modal>
  );
};

// ===== Profile Drawer =====
const ProfileDrawer = ({ person, onClose, onEdit, onResign }) => {
  const toast = useToast();
  const [photoUrl, setPhotoUrl] = React.useState(null);
  const fileRef = React.useRef(null);
  if (!person) return null;
  const { DEPARTMENTS } = window.MEI_DATA;
  const dept = DEPARTMENTS.find(d => d.id === person.deptId);

  const onPhotoChange = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => { setPhotoUrl(r.result); toast.push("อัปโหลดรูปภาพเรียบร้อย", { kind: "success" }); };
    r.readAsDataURL(f);
  };

  return (
    <Drawer open={true} onClose={onClose} width={520}>
      {/* Header */}
      <div style={{
        padding: "20px 22px",
        borderBottom: "1px solid var(--border)",
        background: `linear-gradient(135deg, ${dept.color}28, transparent 70%)`,
        position: "relative",
      }}>
        <div className="row">
          <div className="row gap-8">
            <DeptPill dept={dept} />
            <StatusPill status={person.status} />
          </div>
          <div className="spacer" />
          <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}>
            <Icon name="close" size={14} />
          </button>
        </div>

        <div className="row gap-16" style={{ marginTop: 18 }}>
          <div style={{ position: "relative" }}>
            <Avatar person={person} size={76} photo={photoUrl} />
            <button onClick={() => fileRef.current.click()} style={{
              position: "absolute", bottom: -2, right: -2,
              width: 28, height: 28, borderRadius: "50%",
              background: "var(--bg-card-solid)",
              border: "1px solid var(--border-strong)",
              display: "flex", alignItems: "center", justifyContent: "center",
              cursor: "pointer", color: "var(--text)",
            }}>
              <Icon name="camera" size={13} />
            </button>
            <input ref={fileRef} type="file" accept="image/*" onChange={onPhotoChange} style={{ display: "none" }} />
          </div>
          <div className="col gap-4" style={{ flex: 1 }}>
            <div style={{ fontSize: 19, fontWeight: 600, letterSpacing: -0.2 }}>{person.fullName}</div>
            <div className="faint" style={{ fontSize: 13 }}>{person.position} · {person.deptName}</div>
            <div className="row gap-8" style={{ marginTop: 6 }}>
              <span className="chip" style={{ fontSize: 11 }}>{person.code}</span>
              <span className="chip" style={{ fontSize: 11 }}>ระดับ {person.level}</span>
              <span className="chip" style={{ fontSize: 11 }}>{person.gender} · อายุ {person.age}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: "20px 22px", overflowY: "auto", flex: 1 }}>
        {/* Quick stats */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 22 }}>
          <ProfileMini label="อายุงาน" value={fmtTenure(person.startDate, person.endDate)} color="#7c5cff" />
          <ProfileMini label="เงินเดือน" value={fmtMoney(person.salary)} suffix="฿" color="#00d4a8" />
          <ProfileMini label="วันเกิด" value={person.birthDate} color="#ffc94d" />
        </div>

        <ProfileSection title="ข้อมูลส่วนตัว" icon="user">
          <ProfileRow label="ชื่อ-นามสกุล" value={person.fullName} />
          <ProfileRow label="ชื่อเล่น" value={person.nickname} />
          <ProfileRow label="เพศ" value={person.gender} />
          <ProfileRow label="อายุ" value={`${person.age} ปี`} />
          <ProfileRow label="ที่อยู่" value={person.location} icon="pin" />
        </ProfileSection>

        <ProfileSection title="ติดต่อ" icon="mail">
          <ProfileRow label="อีเมล" value={person.email} icon="mail" copy />
          <ProfileRow label="เบอร์โทร" value={person.phone} icon="phone" copy />
        </ProfileSection>

        <ProfileSection title="ตำแหน่งงาน" icon="briefcase">
          <ProfileRow label="ฝ่าย" value={person.deptName} />
          <ProfileRow label="ตำแหน่ง" value={person.position} />
          <ProfileRow label="ระดับ" value={person.level} />
          <ProfileRow label="วันเริ่มงาน" value={fmtThaiDate(person.startDate)} />
          {person.endDate && <ProfileRow label="วันสิ้นสุดงาน" value={fmtThaiDate(person.endDate)} highlight="pink" />}
        </ProfileSection>

        <ProfileSection title="การศึกษา" icon="graduation">
          <ProfileRow label="วุฒิการศึกษา" value={person.education} />
          <ProfileRow label="สถาบัน" value={person.university} />
        </ProfileSection>
      </div>

      {/* Footer actions */}
      <div style={{
        padding: "14px 22px",
        borderTop: "1px solid var(--border)",
        background: "rgba(0,0,0,0.18)",
        display: "flex", gap: 8,
      }}>
        <button className="btn btn-ghost btn-sm" style={{ flex: 1, justifyContent: "center" }}
          onClick={() => toast.push("เปิดประวัติทั้งหมดของพนักงาน (Coming soon)", { kind: "info" })}>
          <Icon name="briefcase" size={14} /> ดูประวัติเต็ม
        </button>
        <button className="btn btn-primary btn-sm shine" style={{ flex: 1, justifyContent: "center" }}
          onClick={() => { onEdit && onEdit(person); }}>
          <Icon name="edit" size={14} /> แก้ไขข้อมูล
        </button>
        {person.status === "active" && (
          <button className="btn btn-sm"
            style={{ background: "rgba(255,93,143,0.14)", borderColor: "rgba(255,93,143,0.35)", color: "var(--pink)" }}
            onClick={() => { onResign && onResign(person); }}>
            <Icon name="user-minus" size={14} /> ลาออก
          </button>
        )}
      </div>
    </Drawer>
  );
};

const ProfileMini = ({ label, value, suffix, color }) => (
  <div style={{
    padding: "10px 12px",
    borderRadius: 10,
    background: "rgba(255,255,255,0.03)",
    border: "1px solid var(--border)",
  }}>
    <div className="faint" style={{ fontSize: 11 }}>{label}</div>
    <div className="num-display" style={{ fontSize: 15, color, marginTop: 4, fontWeight: 600 }}>
      {value} {suffix && <span style={{ fontSize: 11, opacity: 0.6 }}>{suffix}</span>}
    </div>
  </div>
);

const ProfileSection = ({ title, icon, children }) => (
  <div style={{ marginBottom: 20 }}>
    <div className="row gap-8" style={{ marginBottom: 10 }}>
      <Icon name={icon} size={13} color="var(--text-faint)" />
      <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-faint)", letterSpacing: 0.4, textTransform: "uppercase" }}>
        {title}
      </div>
      <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
    </div>
    <div className="col gap-2">{children}</div>
  </div>
);

const ProfileRow = ({ label, value, icon, copy, highlight }) => {
  const toast = useToast();
  return (
    <div className="row" style={{ padding: "8px 0", borderBottom: "1px dashed var(--border)" }}>
      <div className="faint" style={{ fontSize: 12.5, width: 110 }}>{label}</div>
      <div className="row gap-6" style={{ flex: 1 }}>
        {icon && <Icon name={icon} size={13} color="var(--text-faint)" />}
        <span style={{
          fontSize: 13,
          color: highlight === "pink" ? "var(--pink)" : "var(--text)",
        }}>{value}</span>
      </div>
      {copy && (
        <button className="btn btn-ghost btn-sm" style={{ padding: "3px 8px", fontSize: 11 }}
          onClick={() => { navigator.clipboard?.writeText(value); toast.push("คัดลอกแล้ว", { kind: "success" }); }}>
          คัดลอก
        </button>
      )}
    </div>
  );
};

// ===== New Employee Form =====
const NewEmployeeForm = ({ open, onClose, onDataChange }) => {
  const toast = useToast();
  const { DEPARTMENTS } = window.MEI_DATA;
  const [step, setStep] = React.useState(1);
  const [submitting, setSubmitting] = React.useState(false);
  const [form, setForm] = React.useState({
    firstName: "", lastName: "", nickname: "",
    gender: "ชาย", age: "", birth: "",
    email: "", phone: "", location: "กรุงเทพฯ",
    deptId: "technical", position: "", level: "Staff",
    startDate: "2026-05-14", salary: "",
    education: "ปริญญาตรี", university: "",
  });
  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    try {
      await window.MEI_API.createEmployee({
        firstName: form.firstName, lastName: form.lastName, nickname: form.nickname,
        gender: form.gender, age: Number(form.age) || 22, birthDate: form.birth,
        email: form.email, phone: form.phone, location: form.location,
        deptId: form.deptId, position: form.position, level: form.level,
        startDate: form.startDate, salary: Number(form.salary) || 0,
        education: form.education, university: form.university,
      });
      toast.push(`เพิ่ม ${form.firstName} ${form.lastName} เข้าระบบเรียบร้อย`, { kind: "success" });
      if (onDataChange) await onDataChange();
      setTimeout(onClose, 300);
    } catch (e) {
      toast.push(`บันทึกไม่สำเร็จ: ${e.message}`, { kind: "error" });
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  return (
    <Modal open={open} onClose={onClose} maxWidth={780}>
      <div style={{
        padding: "20px 26px 16px",
        borderBottom: "1px solid var(--border)",
        background: "linear-gradient(135deg, rgba(0,212,168,0.15), transparent 60%)",
      }}>
        <div className="row gap-12">
          <div style={{
            width: 40, height: 40, borderRadius: 10,
            background: "rgba(0,212,168,0.2)", color: "var(--teal)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <Icon name="user-plus" size={20} />
          </div>
          <div className="col gap-4" style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 600 }}>เพิ่มพนักงานใหม่</div>
            <div className="faint" style={{ fontSize: 12.5 }}>ขั้นตอน {step} จาก 3 — {step === 1 ? "ข้อมูลส่วนตัว" : step === 2 ? "ตำแหน่งงาน" : "การศึกษา & ยืนยัน"}</div>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}><Icon name="close" size={16} /></button>
        </div>

        <div className="row gap-4" style={{ marginTop: 14 }}>
          {[1,2,3].map(s => (
            <div key={s} style={{
              flex: 1, height: 3, borderRadius: 2,
              background: s <= step ? "linear-gradient(90deg, #00d4a8, #19b791)" : "rgba(255,255,255,0.08)",
              transition: "background .3s",
            }} />
          ))}
        </div>
      </div>

      <div style={{ padding: "22px 26px", overflowY: "auto", maxHeight: "60vh" }}>
        {step === 1 && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <FormField label="ชื่อจริง" value={form.firstName} onChange={(v) => upd("firstName", v)} placeholder="เช่น ธนพล" />
            <FormField label="นามสกุล" value={form.lastName} onChange={(v) => upd("lastName", v)} placeholder="เช่น ศรีสุข" />
            <FormField label="ชื่อเล่น" value={form.nickname} onChange={(v) => upd("nickname", v)} />
            <FormField label="เพศ" value={form.gender} onChange={(v) => upd("gender", v)} type="select" options={["ชาย", "หญิง"]} />
            <FormField label="อายุ" value={form.age} onChange={(v) => upd("age", v)} placeholder="ปี" />
            <FormField label="วันเกิด" value={form.birth} onChange={(v) => upd("birth", v)} placeholder="วัน/เดือน" />
            <FormField label="อีเมล" value={form.email} onChange={(v) => upd("email", v)} placeholder="name@company.co.th" />
            <FormField label="เบอร์โทร" value={form.phone} onChange={(v) => upd("phone", v)} placeholder="08X-XXX-XXXX" />
            <FormField label="ที่อยู่" value={form.location} onChange={(v) => upd("location", v)}
              type="select" options={["กรุงเทพฯ","นนทบุรี","ปทุมธานี","สมุทรปราการ","ชลบุรี","ระยอง"]} />

            <div style={{ gridColumn: "1 / -1" }}>
              <div className="field-label">รูปโปรไฟล์</div>
              <div className="row gap-12" style={{
                padding: "14px 16px",
                border: "1.5px dashed var(--border-strong)",
                borderRadius: 10,
                background: "rgba(0,0,0,0.15)",
                cursor: "pointer",
              }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 8,
                  background: "rgba(0,212,168,0.18)", color: "var(--teal)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <Icon name="camera" size={18} />
                </div>
                <div className="col">
                  <div style={{ fontSize: 13.5 }}>คลิกหรือลากไฟล์มาวางเพื่ออัปโหลด</div>
                  <div className="faint" style={{ fontSize: 11.5 }}>JPG, PNG · ขนาดสูงสุด 5MB</div>
                </div>
                <div className="spacer" />
                <button className="btn btn-ghost btn-sm">เลือกไฟล์</button>
              </div>
            </div>
          </div>
        )}

        {step === 2 && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <FormField label="ฝ่าย / แผนก" value={form.deptId} onChange={(v) => upd("deptId", v)}
              type="select" options={DEPARTMENTS.map(d => ({ value: d.id, label: d.name }))} />
            <FormField label="ตำแหน่ง" value={form.position} onChange={(v) => upd("position", v)} placeholder="เช่น Software Engineer" />
            <FormField label="ระดับ" value={form.level} onChange={(v) => upd("level", v)}
              type="select" options={["Staff","Officer","Senior","Manager"]} />
            <FormField label="วันเริ่มงาน" value={form.startDate} onChange={(v) => upd("startDate", v)} type="date" />
            <FormField label="เงินเดือน (บาท)" value={form.salary} onChange={(v) => upd("salary", v)} placeholder="35000" />
            <FormField label="ประเภทพนักงาน" value="ประจำ" onChange={() => {}} type="select" options={["ประจำ","สัญญาจ้าง","พาร์ทไทม์"]} />
          </div>
        )}

        {step === 3 && (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 22 }}>
              <FormField label="วุฒิการศึกษา" value={form.education} onChange={(v) => upd("education", v)}
                type="select" options={["ปวส.","ปริญญาตรี","ปริญญาโท","ปริญญาเอก"]} />
              <FormField label="สถาบัน" value={form.university} onChange={(v) => upd("university", v)} placeholder="เช่น จุฬาฯ" />
            </div>

            <div className="glass" style={{ padding: 18 }}>
              <div className="row gap-8" style={{ marginBottom: 12 }}>
                <Icon name="sparkle" size={14} color="var(--teal)" />
                <div style={{ fontSize: 13, fontWeight: 600 }}>สรุปข้อมูลก่อนบันทึก</div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px 18px", fontSize: 12.5 }}>
                <div className="row gap-8"><span className="faint" style={{ width: 90 }}>ชื่อ:</span> {form.firstName || "—"} {form.lastName}</div>
                <div className="row gap-8"><span className="faint" style={{ width: 90 }}>เพศ/อายุ:</span> {form.gender} · {form.age || "—"} ปี</div>
                <div className="row gap-8"><span className="faint" style={{ width: 90 }}>ฝ่าย:</span> {DEPARTMENTS.find(d => d.id === form.deptId)?.name}</div>
                <div className="row gap-8"><span className="faint" style={{ width: 90 }}>ตำแหน่ง:</span> {form.position || "—"}</div>
                <div className="row gap-8"><span className="faint" style={{ width: 90 }}>วันเริ่มงาน:</span> {form.startDate}</div>
                <div className="row gap-8"><span className="faint" style={{ width: 90 }}>เงินเดือน:</span> {form.salary || "—"} บาท</div>
              </div>
            </div>
          </div>
        )}
      </div>

      <div style={{
        padding: "14px 26px",
        borderTop: "1px solid var(--border)",
        display: "flex", justifyContent: "space-between",
        background: "rgba(0,0,0,0.18)",
      }}>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>ยกเลิก</button>
        <div className="row gap-8">
          {step > 1 && (
            <button className="btn btn-ghost btn-sm" onClick={() => setStep(step - 1)}>
              <Icon name="chevron-l" size={14} /> ก่อนหน้า
            </button>
          )}
          {step < 3 ? (
            <button className="btn btn-primary btn-sm shine" onClick={() => setStep(step + 1)}>
              ถัดไป <Icon name="chevron-r" size={14} />
            </button>
          ) : (
            <button className="btn btn-primary btn-sm shine" onClick={submit}>
              <Icon name="check" size={14} /> บันทึกเข้าระบบ
            </button>
          )}
        </div>
      </div>
    </Modal>
  );
};

const FormField = ({ label, value, onChange, placeholder, type = "text", options }) => {
  if (type === "select") {
    return (
      <div>
        <label className="field-label">{label}</label>
        <select className="select" value={value} onChange={(e) => onChange(e.target.value)}>
          {options.map((o, i) => {
            const v = typeof o === "string" ? o : o.value;
            const l = typeof o === "string" ? o : o.label;
            return <option key={i} value={v}>{l}</option>;
          })}
        </select>
      </div>
    );
  }
  return (
    <div>
      <label className="field-label">{label}</label>
      <input className="input" type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />
    </div>
  );
};

// ===== Resign Form =====
const ResignForm = ({ person, onClose, onDataChange }) => {
  const toast = useToast();
  const [date, setDate] = React.useState("2026-05-31");
  const [reason, setReason] = React.useState("voluntary");
  const [note, setNote] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  if (!person) return null;

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    try {
      await window.MEI_API.resignEmployee(person.id);
      toast.push(`บันทึกการลาออกของ ${person.fullName} เรียบร้อย`, { kind: "success" });
      if (onDataChange) await onDataChange();
      setTimeout(onClose, 200);
    } catch (e) {
      toast.push(`บันทึกไม่สำเร็จ: ${e.message}`, { kind: "error" });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal open={true} onClose={onClose} maxWidth={520}>
      <div style={{ padding: "20px 26px", borderBottom: "1px solid var(--border)", background: "linear-gradient(135deg, rgba(255,93,143,0.15), transparent 60%)" }}>
        <div className="row gap-12">
          <div style={{ width: 40, height: 40, borderRadius: 10, background: "rgba(255,93,143,0.2)", color: "var(--pink)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="user-minus" size={20} />
          </div>
          <div className="col gap-4" style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 600 }}>บันทึกการลาออก</div>
            <div className="faint" style={{ fontSize: 12.5 }}>กรุณายืนยันรายละเอียดการสิ้นสุดการจ้างงาน</div>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}><Icon name="close" size={16} /></button>
        </div>
      </div>

      <div style={{ padding: 22 }}>
        <div className="glass" style={{ padding: 14, marginBottom: 18 }}>
          <div className="row gap-12">
            <Avatar person={person} size={42} />
            <div className="col">
              <div style={{ fontSize: 14, fontWeight: 500 }}>{person.fullName}</div>
              <div className="faint" style={{ fontSize: 12 }}>{person.position} · {person.deptName}</div>
              <div className="faint" style={{ fontSize: 11.5, marginTop: 2 }}>เริ่มงาน {fmtThaiDate(person.startDate)} · อายุงาน {fmtTenure(person.startDate)}</div>
            </div>
          </div>
        </div>

        <div className="col gap-14">
          <FormField label="วันที่สิ้นสุดการทำงาน" value={date} onChange={setDate} type="date" />
          <FormField label="ประเภทการลาออก" value={reason} onChange={setReason} type="select" options={[
            { value: "voluntary", label: "ลาออกโดยสมัครใจ" },
            { value: "termination", label: "เลิกจ้าง" },
            { value: "retirement", label: "เกษียณอายุ" },
            { value: "endcontract", label: "หมดสัญญา" },
          ]} />
          <div>
            <label className="field-label">หมายเหตุ</label>
            <textarea className="textarea" rows="3" value={note} onChange={(e) => setNote(e.target.value)}
              placeholder="เหตุผลเพิ่มเติม, ปลายทาง, ฯลฯ" />
          </div>
        </div>
      </div>

      <div style={{ padding: "14px 26px", borderTop: "1px solid var(--border)", display: "flex", justifyContent: "space-between", background: "rgba(0,0,0,0.18)" }}>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-danger btn-sm shine" onClick={submit}>
          <Icon name="user-minus" size={14} /> ยืนยันบันทึกการลาออก
        </button>
      </div>
    </Modal>
  );
};

Object.assign(window, { DrilldownModal, ProfileDrawer, NewEmployeeForm, ResignForm });
