/* global React, I, UI, SSSData */
// =============== ใบประเมินงาน · Work Evaluation ===============
// ออกหลังจากมีใบสั่งงาน — ดึงว่าใครรับผิดชอบอะไร แล้วให้คะแนน + แจ้งพนักงาน
// คะแนนถูกเก็บรวมเพื่อใช้คำนวณ KPI รายเดือนอัตโนมัติ
const { useState: useStateWE } = React;

const WE_KEY = "sss-work-evals";
const WE_MONTHS = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
function weToday() { const d = new Date(); return `${d.getDate()} ${WE_MONTHS[d.getMonth()]} ${d.getFullYear() + 543}`; }

function weLoad() { try { return JSON.parse(localStorage.getItem(WE_KEY) || "[]"); } catch { return []; } }
function weSaveAll(list) {
  try { localStorage.setItem(WE_KEY, JSON.stringify(list)); } catch {}
  window.dispatchEvent(new Event("sss-evals-changed"));
}
function weNextNo() { return "EV-2569-" + String(weLoad().length + 1).padStart(3, "0"); }

window.WorkEvalStore = {
  load: weLoad,
  byProject(code) { return weLoad().filter(e => e.project === code); },
  remove(no) { weSaveAll(weLoad().filter(e => e.no !== no)); }
};

const WE_SCORE_LABEL = { 5: "ดีมาก", 4: "ดี", 3: "พอใช้", 2: "ต้องปรับปรุง", 1: "ไม่ผ่าน" };

// ---------- พิมพ์ใบประเมินงาน A4 ----------
function wePrintModal(barTitle, html) {
  document.getElementById("__print_modal")?.remove();
  document.body.classList.remove("printing-modal");
  const modal = document.createElement("div");
  modal.id = "__print_modal";
  modal.className = "print-modal";
  modal.innerHTML = `
    <div class="print-modal-bar no-print">
      <div style="font-weight:600;font-size:14px;flex:1">${barTitle}</div>
      <button id="__print_close" class="pm-btn pm-btn-ghost">ปิด (Esc)</button>
      <button id="__print_btn" class="pm-btn pm-btn-primary">🖨 พิมพ์ / บันทึก PDF</button>
    </div>
    <div class="print-modal-paper">${html}</div>
  `;
  document.body.appendChild(modal);
  document.body.classList.add("printing-modal");
  const cleanup = () => { modal.remove(); document.body.classList.remove("printing-modal"); document.removeEventListener("keydown", onKey); };
  const onKey = (e) => { if (e.key === "Escape") cleanup(); };
  document.addEventListener("keydown", onKey);
  modal.addEventListener("click", e => { if (e.target === modal) cleanup(); });
  document.getElementById("__print_btn").addEventListener("click", () => window.print());
  document.getElementById("__print_close").addEventListener("click", cleanup);
}

function weAvatarHTML(name, size) {
  const p = window.ChatProfiles ? window.ChatProfiles.get(name) : null;
  const color = p ? p.color : "#57534e";
  if (p && p.avatar) return `<img src="${p.avatar}" style="width:${size}px;height:${size}px;border-radius:50%;object-fit:cover;border:2.5px solid ${color};flex-shrink:0"/>`;
  return `<div style="width:${size}px;height:${size}px;border-radius:50%;background:${color};color:white;display:grid;place-items:center;font-weight:700;font-size:${Math.round(size * 0.3)}px;flex-shrink:0">${String(name || "?").slice(0, 2)}</div>`;
}

function printWorkEvalDoc(ev) {
  const C = window.SSSData.Company;
  const accent = "#7c3aed";
  const stars = (n) => "★".repeat(n) + "☆".repeat(5 - n);
  const avg = ev.rows.reduce((s, r) => s + r.score, 0) / (ev.rows.length || 1);
  const issues = ev.rows.filter(r => r.result === "พบปัญหา").length;

  const html = `<div style="background:white;color:#0c0a09;padding:34px 42px;min-height:90vh">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid ${accent};padding-bottom:14px;margin-bottom:16px">
      <div style="display:flex;gap:12px;align-items:center">
        <div style="width:48px;height:48px;background:#0c0a09;color:white;display:grid;place-items:center;font-weight:700;font-size:15px;border-radius:6px">SSS</div>
        <div>
          <div style="font-weight:700;font-size:14px">${C.name}</div>
          <div style="font-size:10.5px;color:#57534e;max-width:320px">${C.address || ""}</div>
        </div>
      </div>
      <div style="text-align:right">
        <h1 style="margin:0;font-size:22px;color:${accent};font-weight:700">ใบประเมินงาน</h1>
        <div style="font-size:10.5px;color:#78716c;letter-spacing:0.08em">WORK EVALUATION</div>
        <div style="font-size:11.5px;margin-top:6px">เลขที่ <b style="font-family:monospace">${ev.no}</b> · วันที่ <b>${ev.date}</b></div>
      </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:16px;font-size:12px">
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px">
        <div style="font-size:9.5px;color:#78716c;margin-bottom:2px">อ้างอิงใบสั่งงาน</div>
        <div style="font-weight:700;font-family:monospace">${ev.woNo}</div>
      </div>
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px">
        <div style="font-size:9.5px;color:#78716c;margin-bottom:2px">โปรเจกต์</div>
        <div style="font-weight:600;font-size:11.5px">${ev.projectName}</div>
        <div style="font-family:monospace;font-size:10px;color:#57534e">${ev.project}</div>
      </div>
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px">
        <div style="font-size:9.5px;color:#78716c;margin-bottom:2px">ผู้ประเมิน</div>
        <div style="font-weight:600">${ev.by}</div>
      </div>
    </div>

    ${ev.rows.map((r, i) => `
      <div style="border:1.5px solid ${r.result === "พบปัญหา" ? "#fca5a5" : "#d6d3d1"};border-radius:8px;padding:10px 14px;margin-bottom:8px;display:flex;gap:12px;align-items:flex-start;page-break-inside:avoid;background:${r.result === "พบปัญหา" ? "#fef2f2" : "white"}">
        <div style="width:22px;height:22px;border-radius:50%;background:${accent};color:white;display:grid;place-items:center;font-size:10.5px;font-weight:700;flex-shrink:0;margin-top:2px">${i + 1}</div>
        ${weAvatarHTML(r.name, 44)}
        <div style="flex:1;min-width:0">
          <div style="font-size:13px"><b>${r.name}</b> <span style="color:#78716c;font-size:11px">${r.role || ""}</span></div>
          <div style="font-size:9.5px;color:#78716c;text-transform:uppercase;letter-spacing:0.05em;margin-top:3px">หน้าที่ที่ได้รับ</div>
          <div style="font-size:11.5px;line-height:1.5;white-space:pre-wrap">${(r.duty || "—").replace(/</g, "&lt;")}</div>
          ${r.comment ? `<div style="font-size:11px;color:#57534e;margin-top:4px"><b>ความเห็น:</b> ${r.comment.replace(/</g, "&lt;")}</div>` : ""}
        </div>
        <div style="width:150px;border-left:1px dashed #d6d3d1;padding-left:12px;flex-shrink:0;font-size:11px">
          <div style="font-size:9.5px;color:#78716c;margin-bottom:2px">ผลงาน</div>
          <div style="font-weight:700;color:${r.result === "พบปัญหา" ? "#b91c1c" : "#15803d"}">${r.result === "พบปัญหา" ? "⚠ พบปัญหา" : "✓ เรียบร้อย"}</div>
          <div style="font-size:9.5px;color:#78716c;margin:6px 0 2px">คะแนน</div>
          <div style="font-size:14px;color:#b45309;letter-spacing:1px">${stars(r.score)}</div>
          <div style="font-weight:700">${r.score}/5 · ${WE_SCORE_LABEL[r.score]}</div>
        </div>
      </div>`).join("")}

    <div style="display:flex;justify-content:space-between;align-items:center;border:2px solid ${accent};border-radius:8px;padding:10px 16px;margin:14px 0;background:${accent}0d">
      <div style="font-size:12px"><b>สรุปผล:</b> ประเมิน ${ev.rows.length} คน · เรียบร้อย ${ev.rows.length - issues} · พบปัญหา ${issues}</div>
      <div style="font-size:14px;font-weight:700;color:${accent}">คะแนนเฉลี่ย ${avg.toFixed(1)} / 5</div>
    </div>

    ${ev.note ? `<div style="font-size:11.5px;border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px;margin-bottom:14px"><b>หมายเหตุรวม:</b> ${ev.note.replace(/</g, "&lt;")}</div>` : ""}

    <div style="font-size:10px;color:#78716c;margin-bottom:6px">เกณฑ์คะแนน: 5 ดีมาก · 4 ดี · 3 พอใช้ · 2 ต้องปรับปรุง · 1 ไม่ผ่าน — คะแนนจะถูกรวมเข้า KPI ประจำเดือนของพนักงานโดยอัตโนมัติ</div>

    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:24px;font-size:11px;margin-top:28px">
      <div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:36px"><b>ผู้ประเมิน</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ${ev.by} ) · ${ev.date}</div></div></div>
      <div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:36px"><b>หัวหน้างาน</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ........................... )</div></div></div>
      <div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:36px"><b>พนักงานรับทราบผล</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ........................... )</div></div></div>
    </div>
    <div style="margin-top:26px;padding-top:8px;border-top:2px solid ${accent};font-size:9.5px;color:#78716c;display:flex;justify-content:space-between">
      <span>${C.name}</span><span>${ev.no} · ใบประเมินงาน · ออกโดยระบบ SSS</span>
    </div>
  </div>`;
  wePrintModal(`ใบประเมินงาน ${ev.no}`, html);
}
window.printWorkEvalDoc = printWorkEvalDoc;

// ---------- Modal ประเมินงาน ----------
function WorkEvalModal({ project, wo, onClose, onSaved }) {
  const { Btn, Drawer } = window.UI;
  const initial = (wo.steps && wo.steps.length
    ? wo.steps.map(s => ({ empId: s.empId, name: s.name, role: s.role, duty: s.duty }))
    : (wo.assignees || []).map((a, i) => ({ empId: (wo.assigneeIds || [])[i] || "", name: a, role: (wo.assigneeRoles || [])[i] || "", duty: "" }))
  ).map(r => ({ ...r, score: 5, result: "เรียบร้อย", comment: "" }));
  const [rows, setRows] = useStateWE(initial);
  const [note, setNote] = useStateWE("");
  const [notify, setNotify] = useStateWE(true);
  const updRow = (i, k, v) => setRows(list => list.map((r, j) => j === i ? { ...r, [k]: v } : r));

  const save = (andPrint) => {
    const ev = {
      no: weNextNo(), woNo: wo.no, project: project.code, projectName: project.name,
      customer: project.customer, date: weToday(), by: "ปิยะ ศ.",
      rows: rows.map(r => ({ ...r, comment: r.comment.trim() })),
      note: note.trim(),
      avg: +(rows.reduce((s, r) => s + r.score, 0) / (rows.length || 1)).toFixed(2)
    };
    weSaveAll([ev, ...weLoad()]);
    window.logActivity && window.logActivity("ออกใบประเมินงาน", `${ev.no} จาก ${wo.no} — เฉลี่ย ${ev.avg}/5`, "create");
    window.toast && window.toast(`ออกใบประเมินงาน ${ev.no} แล้ว${notify ? ` · แจ้งผลให้พนักงาน ${rows.length} คนทางแชทแล้ว` : ""} — คะแนนรวมเข้า KPI อัตโนมัติ`);
    onSaved && onSaved(ev);
    onClose();
    if (andPrint) setTimeout(() => printWorkEvalDoc(ev), 150);
  };

  return (
    <Drawer open={true} onClose={onClose} title={`ออกใบประเมินงาน · ${wo.no}`} wide
      footer={<>
        <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
        <Btn kind="ghost" icon={I.print} onClick={() => save(true)}>บันทึก + พิมพ์</Btn>
        <Btn kind="primary" icon={I.check} onClick={() => save(false)}>บันทึกใบประเมิน</Btn>
      </>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ padding: "10px 14px", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 8, fontSize: 12.5 }}>
          <b>{project.name}</b>
          <div style={{ color: "var(--ink-3)", fontSize: 11.5, marginTop: 2 }}>
            ใบสั่งงาน <span className="mono">{wo.no}</span> · ออกเมื่อ {wo.issueDate} · ดึงผู้รับผิดชอบและหน้าที่มาอัตโนมัติ
          </div>
        </div>

        {rows.map((r, i) => (
          <div key={i} style={{ border: "1px solid var(--line)", borderRadius: 10, padding: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              {window.RankAvatar ? <window.RankAvatar name={r.name} size={34} /> : <div className="avatar" style={{ width: 34, height: 34 }}>{r.name.slice(0, 2)}</div>}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{i + 1}. {r.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{r.role}</div>
              </div>
              <div className="payseg" style={{ display: "flex" }}>
                {["เรียบร้อย", "พบปัญหา"].map(s => (
                  <button key={s} type="button" className={"payseg-btn" + (r.result === s ? " active" : "")} onClick={() => updRow(i, "result", s)}
                    style={r.result === s && s === "พบปัญหา" ? { color: "var(--danger)" } : {}}>
                    {s === "เรียบร้อย" ? "✓ เรียบร้อย" : "⚠ พบปัญหา"}
                  </button>
                ))}
              </div>
            </div>
            {r.duty && <div style={{ fontSize: 12, color: "var(--ink-2)", padding: "6px 10px", background: "var(--surface-2)", borderRadius: 6, whiteSpace: "pre-wrap" }}><span style={{ color: "var(--ink-3)", fontSize: 10.5 }}>หน้าที่: </span>{r.duty}</div>}
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <span style={{ fontSize: 12, color: "var(--ink-3)", minWidth: 50 }}>คะแนน</span>
              <div style={{ display: "flex", gap: 4 }}>
                {[1, 2, 3, 4, 5].map(s => (
                  <button key={s} type="button" onClick={() => updRow(i, "score", s)} title={`${s} — ${WE_SCORE_LABEL[s]}`}
                    style={{ width: 32, height: 30, borderRadius: 7, cursor: "pointer", fontWeight: 700, fontSize: 13, fontFamily: "var(--font)",
                      border: r.score === s ? "1.5px solid var(--accent)" : "1px solid var(--line)",
                      background: r.score >= s ? "var(--accent)" : "var(--surface)",
                      color: r.score >= s ? "var(--accent-ink)" : "var(--ink-3)" }}>{s}</button>
                ))}
              </div>
              <span style={{ fontSize: 12, fontWeight: 600 }}>{r.score}/5 · {WE_SCORE_LABEL[r.score]}</span>
              <input className="input" style={{ flex: 1, minWidth: 160, height: 30, fontSize: 12 }} placeholder="ความเห็น (ไม่บังคับ)…" value={r.comment} onChange={e => updRow(i, "comment", e.target.value)}></input>
            </div>
          </div>
        ))}

        <div className="field"><label>หมายเหตุรวม</label>
          <textarea className="textarea" value={note} onChange={e => setNote(e.target.value)} style={{ minHeight: 52 }} placeholder="เช่น งานเสร็จก่อนกำหนด 2 วัน คุณภาพรวมดีมาก"></textarea>
        </div>
        <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, cursor: "pointer" }}>
          <input type="checkbox" checked={notify} onChange={e => setNotify(e.target.checked)}></input>
          แจ้งผลประเมินให้พนักงานทุกคนทางแชทอัตโนมัติ
        </label>
      </div>
    </Drawer>
  );
}

window.WorkEvalModal = WorkEvalModal;
