/* ===== Task add/edit modal ===== */
const { useState: useStateM, useEffect: useEffectM } = React;

function TaskModal({ task, lockAssignee, members, onClose, onSave, onDelete, onManageMembers }) {
  const isNew = !task.id;
  const memberList = members || MEMBERS;
  const [form, setForm] = useStateM({
    title: task.title || "",
    desc: task.desc || "",
    assignee: task.assignee || memberList[0].id,
    status: task.status || "todo",
    priority: task.priority || "med",
    start: task.start || dayStr(0),
    deadline: task.deadline || dayStr(3),
  });
  const [err, setErr] = useStateM(false);

  useEffectM(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = () => {
    if (!form.title.trim()) { setErr(true); return; }
    onSave({ ...task, ...form, title: form.title.trim() });
  };

  return (
    <div style={tmStyles.overlay} onMouseDown={onClose}>
      <div style={tmStyles.sheet} className="scroll modal-sheet" onMouseDown={(e) => e.stopPropagation()}>
        <div style={tmStyles.head}>
          <div>
            <div style={tmStyles.kicker}>{isNew ? "งานใหม่ · New task" : "แก้ไขงาน · Edit task"}</div>
            <div style={tmStyles.headTitle}>{isNew ? "เพิ่มงานให้ทีม" : "รายละเอียดงาน"}</div>
          </div>
          <button style={tmStyles.x} className="tm-x" onClick={onClose}><CloseIcon /></button>
        </div>

        <div style={tmStyles.body}>
          <label style={tmStyles.field}>
            <span style={tmStyles.label}>ชื่องาน <b style={{color:"var(--high)"}}>*</b></span>
            <input
              autoFocus value={form.title}
              onChange={(e) => { set("title", e.target.value); setErr(false); }}
              placeholder="เช่น ออกแบบหน้า Dashboard"
              style={{ ...tmStyles.input, borderColor: err ? "var(--high)" : "var(--line)" }}
            />
            {err && <span style={tmStyles.errTxt}>กรุณาใส่ชื่องาน</span>}
          </label>

          <label style={tmStyles.field}>
            <span style={tmStyles.label}>รายละเอียด</span>
            <textarea
              value={form.desc} onChange={(e) => set("desc", e.target.value)}
              placeholder="อธิบายงานสั้นๆ ว่าต้องทำอะไรบ้าง"
              rows={3} style={{ ...tmStyles.input, resize: "vertical", lineHeight: 1.5 }}
            />
          </label>

          <div style={tmStyles.row2} className="modal-row2">
            <label style={tmStyles.field}>
              <span style={tmStyles.label}>ผู้รับผิดชอบ · Assignee</span>
              <MemberPicker value={form.assignee} onChange={(id) => set("assignee", id)}
                members={memberList} disabled={lockAssignee} onManage={onManageMembers} />
            </label>
            <label style={tmStyles.field}>
              <span style={tmStyles.label}>สถานะ · Status</span>
              <select value={form.status} onChange={(e) => set("status", e.target.value)} style={{ ...tmStyles.input, ...tmStyles.select }}>
                {STATUSES.map(s => <option key={s.id} value={s.id}>{s.label} · {s.th}</option>)}
              </select>
            </label>
          </div>

          <div style={tmStyles.field}>
            <span style={tmStyles.label}>ระดับความสำคัญ · Priority</span>
            <div style={{ display: "flex", gap: 8 }}>
              {PRIORITIES.map(p => {
                const on = form.priority === p.id;
                return (
                  <button key={p.id} onClick={() => set("priority", p.id)}
                    style={{
                      flex: 1, padding: "10px 8px", borderRadius: 11, fontWeight: 600, fontSize: 13.5,
                      border: "1.5px solid " + (on ? p.color : "var(--line)"),
                      background: on ? p.soft : "var(--surface)", color: on ? p.color : "var(--ink-2)",
                      display: "flex", alignItems: "center", justifyContent: "center", gap: 7, transition: ".12s",
                    }}>
                    <span className="dot" style={{ background: p.color, width: 9, height: 9 }}></span>
                    {p.th}
                  </button>
                );
              })}
            </div>
          </div>

          <div style={tmStyles.row2} className="modal-row2">
            <label style={tmStyles.field}>
              <span style={tmStyles.label}>วันที่เริ่ม · Start</span>
              <input type="date" value={form.start} onChange={(e) => set("start", e.target.value)} style={tmStyles.input} />
            </label>
            <label style={tmStyles.field}>
              <span style={tmStyles.label}>กำหนดส่ง · Deadline</span>
              <input type="date" value={form.deadline} onChange={(e) => set("deadline", e.target.value)} style={tmStyles.input} />
            </label>
          </div>
        </div>

        <div style={tmStyles.foot}>
          {!isNew
            ? <button className="btn" style={tmStyles.del} onClick={() => onDelete(task.id)}>ลบงาน</button>
            : <span />}
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
            <button className="btn btn-primary" onClick={submit}>{isNew ? "เพิ่มงาน" : "บันทึก"}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

const tmStyles = {
  overlay: {
    position: "fixed", inset: 0, zIndex: 100, background: "rgba(20,30,55,.42)",
    backdropFilter: "blur(4px)", display: "grid", placeItems: "center", padding: 20,
    animation: "overlayIn .2s ease both",
  },
  sheet: {
    width: "min(560px, 100%)", maxHeight: "92vh", overflowY: "auto",
    background: "var(--surface)", borderRadius: 22, boxShadow: "var(--shadow-pop)",
    animation: "sheetIn .3s cubic-bezier(.2,.7,.3,1) both",
  },
  head: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", padding: "24px 26px 6px" },
  kicker: { fontSize: 12, fontWeight: 700, color: "var(--primary)", letterSpacing: ".3px", textTransform: "uppercase" },
  headTitle: { fontSize: 21, fontWeight: 700, marginTop: 4 },
  x: { width: 36, height: 36, borderRadius: 10, border: "1px solid var(--line)", background: "var(--surface)", color: "var(--ink-2)", display: "grid", placeItems: "center" },
  body: { padding: "16px 26px 8px", display: "flex", flexDirection: "column", gap: 16 },
  field: { display: "flex", flexDirection: "column", gap: 7, flex: 1 },
  label: { fontSize: 13, fontWeight: 600, color: "var(--ink-2)" },
  input: {
    border: "1.5px solid var(--line)", borderRadius: 11, padding: "11px 13px",
    fontSize: 14.5, color: "var(--ink)", background: "var(--surface)", outline: "none", width: "100%",
  },
  select: { appearance: "none", cursor: "pointer" },
  row2: { display: "flex", gap: 12 },
  errTxt: { fontSize: 12, color: "var(--high)", fontWeight: 600 },
  foot: { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 26px 24px", marginTop: 6 },
  del: { background: "var(--high-soft)", color: "var(--high)" },
};

window.TaskModal = TaskModal;
