/* global React, I, UI, SSSData */
// =============== Project extras: work orders, job summary, create/edit, expenses ===============
const { useState: useStatePX } = React;

// ---------- Persistence ----------
const PX_KEY = "sss-project-extras";
function pxLoad() { try { return JSON.parse(localStorage.getItem(PX_KEY) || "{}"); } catch { return {}; } }
function pxSave(all) { try { localStorage.setItem(PX_KEY, JSON.stringify(all)); } catch {} }
function pxGet(code) { return pxLoad()[code] || {}; }
function pxSet(code, patch) { const all = pxLoad(); all[code] = { ...(all[code] || {}), ...patch }; pxSave(all); }

const UP_KEY = "sss-projects-user";
function pxUserLoad() { try { return JSON.parse(localStorage.getItem(UP_KEY) || "[]"); } catch { return []; } }
function pxUserSave(list) { try { localStorage.setItem(UP_KEY, JSON.stringify(list)); } catch {} }

// ---------- Date helpers ----------
const PX_MONTHS = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
function pxThaiDate(iso) {
  if (!iso) return "—";
  const [y, m, d] = iso.split("-").map(Number);
  return `${d} ${PX_MONTHS[m - 1]} ${y + 543}`;
}
function pxToday() { const d = new Date(); return `${d.getDate()} ${PX_MONTHS[d.getMonth()]} ${d.getFullYear() + 543}`; }
function pxTodayISO() { return new Date().toISOString().slice(0, 10); }

// ---------- Shared print modal ----------
function pxPrint(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 pxDocHeader(C, title, subtitle, accent) {
  return `
    <div style="display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid ${accent};padding-bottom:14px;margin-bottom:18px">
      <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 style="font-size:10.5px;color:#57534e">เลขผู้เสียภาษี ${C.taxId}</div>
        </div>
      </div>
      <div style="text-align:right">
        <h1 style="margin:0;font-size:22px;color:${accent};font-weight:700">${title}</h1>
        <div style="font-size:10.5px;color:#78716c;letter-spacing:0.08em">${subtitle}</div>
      </div>
    </div>`;
}

// ---------- Work order ----------
function pxNextWoNo() {
  const all = pxLoad();
  let count = 0;
  Object.values(all).forEach(x => { count += (x.workOrders || []).length; });
  return "WO-2569-" + String(count + 1).padStart(3, "0");
}

function printWorkOrderDoc(project, wo) {
  const D = window.SSSData;
  const C = D.Company;
  const accent = "#1d4ed8";
  const prio = wo.priority || "ปกติ";
  const prioColor = prio === "ด่วนมาก" ? "#b91c1c" : prio === "ด่วน" ? "#b45309" : "#15803d";
  const assignees = wo.assignees && wo.assignees.length ? wo.assignees : (wo.assignee ? [wo.assignee] : ["—"]);
  const photos = wo.photos || [];
  const steps = (wo.steps && wo.steps.length)
    ? wo.steps
    : assignees.map((a, i) => ({ name: a, role: (wo.assigneeRoles && wo.assigneeRoles[i]) || "", duty: "" }));

  // A4 pagination: หน้า 1 = รายละเอียดงาน · หน้า 2 = ผู้รับผิดชอบ (timeline) · จากนั้นรูป 2 รูป/หน้า
  const photoPages = [];
  for (let i = 0; i < photos.length; i += 2) photoPages.push(photos.slice(i, i + 2));
  const totalPages = 2 + photoPages.length;

  const pageFoot = (n) => `
    <div style="position:absolute;left:14mm;right:14mm;bottom:7mm;border-top:2px solid ${accent};padding-top:5px;font-size:9.5px;color:#78716c;display:flex;justify-content:space-between">
      <span>${C.name}</span>
      <span>${wo.no} · ออกโดยระบบ SSS</span>
      <span style="font-weight:700;color:#44403c">หน้าที่ ${n} / ${totalPages}</span>
    </div>`;
  const pageWrap = (inner, n) => `
    <div style="background:white;color:#0c0a09;width:100%;min-height:284mm;padding:12mm 14mm 22mm;box-sizing:border-box;position:relative;${n < totalPages ? "page-break-after:always;" : ""}">
      ${inner}
      ${pageFoot(n)}
    </div>`;

  // Signatures: ผู้สั่งงาน + ผู้รับงานทุกคน
  const sigBlocks = [
    `<div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:42px"><b>ผู้สั่งงาน</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ${wo.issuedBy} ) · ${wo.issueDate}</div></div></div>`,
    ...assignees.map(a => `<div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:42px"><b>ผู้รับงาน</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ${a} ) · วันที่ ....................</div></div></div>`)
  ];
  const sigCols = Math.min(3, sigBlocks.length);

  const page1 = `
    ${pxDocHeader(C, "ใบสั่งงาน", "WORK ORDER", accent)}
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
      <div style="font-size:12px">เลขที่ <b style="font-family:monospace;font-size:13px">${wo.no}</b> · ออกเมื่อ <b>${wo.issueDate}</b></div>
      <div style="font-size:11px;padding:3px 12px;border:1.5px solid ${prioColor};color:${prioColor};border-radius:99px;font-weight:700">ความสำคัญ: ${prio}</div>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:14px;font-size:12px">
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px">
        <div style="font-size:9.5px;color:#78716c;letter-spacing:0.05em;margin-bottom:2px">โปรเจกต์</div>
        <div style="font-weight:600">${project.name}</div>
        <div style="font-family:monospace;font-size:10.5px;color:#57534e">${project.code} · ลูกค้า: ${project.customer}</div>
      </div>
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px">
        <div style="font-size:9.5px;color:#78716c;letter-spacing:0.05em;margin-bottom:2px">ผู้รับผิดชอบ (${assignees.length} คน)</div>
        ${assignees.map((a, i) => `<div style="font-weight:600;font-size:11.5px">${i + 1}. ${a}${(wo.assigneeRoles && wo.assigneeRoles[i]) ? ` <span style="font-weight:400;color:#57534e;font-size:10.5px">— ${wo.assigneeRoles[i]}</span>` : ""}</div>`).join("")}
      </div>
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:8px 12px">
        <div style="font-size:9.5px;color:#78716c;letter-spacing:0.05em;margin-bottom:2px">ผู้สั่งงาน</div>
        <div style="font-weight:600">${wo.issuedBy}</div>
      </div>
      <div style="border:1.5px solid ${accent};border-radius:6px;padding:8px 12px;background:${accent}0d">
        <div style="font-size:9.5px;color:#78716c;letter-spacing:0.05em;margin-bottom:2px">กำหนดเวลา</div>
        <div style="font-weight:600">เริ่ม ${pxThaiDate(wo.startDate)} → ส่งงาน <span style="color:${accent}">${pxThaiDate(wo.due)}</span></div>
      </div>
    </div>
    <div style="margin-bottom:14px">
      <div style="font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#44403c;margin-bottom:5px">รายละเอียดของงาน</div>
      <div style="border:1px solid #d6d3d1;border-radius:6px;padding:12px 14px;font-size:12.5px;line-height:1.65;min-height:90px;max-height:118mm;overflow:hidden;white-space:pre-wrap">${(wo.detail || "").replace(/</g, "&lt;")}</div>
    </div>
    <div style="font-size:11px;color:#44403c;margin-bottom:8px;padding:7px 12px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:5px">👥 <b>ผู้รับผิดชอบและลำดับการส่งต่องาน (Timeline)</b> — ดูหน้าที่ 2 ของเอกสารนี้</div>
    ${photos.length > 0 ? `<div style="font-size:11px;color:#44403c;margin-bottom:12px;padding:7px 12px;background:#f7f6f4;border-radius:5px">📎 <b>รูปภาพประกอบ ${photos.length} รูป</b> — ดูหน้าที่ 3${totalPages > 3 ? `–${totalPages}` : ""} ของเอกสารนี้</div>` : ""}
    <div style="font-size:10.5px;color:#78716c;margin-bottom:8px">
      <b>เงื่อนไข:</b> ผู้รับผิดชอบต้องอัพเดทความคืบหน้าพร้อมรูปถ่ายหน้างานในระบบทุกครั้ง · แจ้งหัวหน้างานทันทีหากพบปัญหาที่กระทบกำหนดส่ง
    </div>
    <div style="display:grid;grid-template-columns:repeat(${sigCols}, 1fr);gap:24px;font-size:11px">
      ${sigBlocks.join("")}
    </div>`;

  const photoPagesHTML = photoPages.map((pair, pi) => {
    const inner = `
      <div style="display:flex;justify-content:space-between;align-items:center;border-bottom:2px solid ${accent};padding-bottom:8px;margin-bottom:10px">
        <div style="display:flex;gap:10px;align-items:center">
          <div style="width:34px;height:34px;background:#0c0a09;color:white;display:grid;place-items:center;font-weight:700;font-size:11px;border-radius:5px">SSS</div>
          <div>
            <div style="font-weight:700;font-size:12.5px">ใบสั่งงาน ${wo.no} — รูปภาพประกอบ</div>
            <div style="font-size:10.5px;color:#57534e">${project.code} · ${project.name}</div>
          </div>
        </div>
        <div style="font-size:10.5px;color:#78716c">ออกเมื่อ ${wo.issueDate}</div>
      </div>
      ${pair.map((ph, j) => `
        <div style="margin-bottom:8mm">
          <img src="${ph.url}" style="display:block;width:100%;max-height:112mm;object-fit:contain;border:1px solid #e7e5e4;border-radius:5px;background:#fafaf9"/>
          <div style="font-size:10px;color:#57534e;margin-top:3px;text-align:center">รูปที่ ${pi * 2 + j + 1}${ph.name && !/^camera/.test(ph.name) ? ` · ${ph.name}` : ""}</div>
        </div>`).join("")}`;
    return pageWrap(inner, pi + 3);
  }).join("");

  // ---------- หน้า 2: ผู้รับผิดชอบแบบ Timeline ----------
  const avatarOf = (name) => {
    const p = window.ChatProfiles ? window.ChatProfiles.get(name) : null;
    const color = p ? p.color : "#57534e";
    return p && p.avatar
      ? `<img src="${p.avatar}" style="width:52px;height:52px;border-radius:50%;object-fit:cover;border:3px solid ${color};flex-shrink:0"/>`
      : `<div style="width:52px;height:52px;border-radius:50%;background:${color};color:white;display:grid;place-items:center;font-weight:700;font-size:16px;flex-shrink:0">${String(name || "?").slice(0, 2)}</div>`;
  };
  const cb = `<span style="display:inline-block;width:12px;height:12px;border:1.5px solid #44403c;border-radius:2.5px;vertical-align:-2px;margin-right:5px"></span>`;
  const respInner = `
    ${pxDocHeader(C, "ผู้รับผิดชอบงาน", `RESPONSIBILITY TIMELINE · ${wo.no}`, accent)}
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;font-size:11.5px">
      <div>โปรเจกต์ <b>${project.name}</b> <span style="font-family:monospace;color:#57534e">(${project.code})</span></div>
      <div>กำหนดส่งงาน <b style="color:${accent}">${pxThaiDate(wo.due)}</b></div>
    </div>
    <div style="font-size:10.5px;color:#57534e;margin-bottom:14px;padding:6px 10px;background:#f7f6f4;border-radius:5px">ทำตามลำดับ — เสร็จจากคนแรกแล้วส่งต่อให้คนถัดไป · ติ้กช่อง "ทำเสร็จแล้ว" หรือ "เกิดปัญหา" พร้อมลงชื่อทุกครั้ง</div>
    <div style="position:relative;padding-left:30px">
      <div style="position:absolute;left:11px;top:10px;bottom:10px;width:2px;background:${accent}40"></div>
      ${steps.map((s, i) => `
        <div style="position:relative;page-break-inside:avoid">
          <div style="position:absolute;left:-30px;top:16px;width:24px;height:24px;border-radius:50%;background:${accent};color:white;font-size:11px;font-weight:700;display:grid;place-items:center;box-shadow:0 0 0 3px white">${i + 1}</div>
          <div style="border:1.5px solid #d6d3d1;border-radius:9px;padding:11px 14px;display:flex;gap:13px;align-items:flex-start;background:white">
            ${avatarOf(s.name)}
            <div style="flex:1;min-width:0">
              <div style="font-size:13px"><b>${s.name}</b> <span style="color:#78716c;font-size:10.5px">${s.role || ""}</span></div>
              <div style="font-size:9.5px;color:#78716c;text-transform:uppercase;letter-spacing:0.05em;margin-top:4px">หน้าที่</div>
              <div style="font-size:11.5px;line-height:1.55;white-space:pre-wrap">${s.duty ? s.duty.replace(/</g, "&lt;") : "................................................................"}</div>
            </div>
            <div style="width:165px;border-left:1px dashed #d6d3d1;padding-left:12px;flex-shrink:0;font-size:10.5px;line-height:2.1">
              <div>${cb} ทำเสร็จแล้ว</div>
              <div>${cb} <span style="color:#b91c1c">เกิดปัญหา</span></div>
              <div style="color:#78716c">หมายเหตุ ..............................</div>
              <div style="color:#78716c">..............................................</div>
              <div style="color:#78716c">ลงชื่อ ................. วันที่ ....../......</div>
            </div>
          </div>
          ${i < steps.length - 1
            ? `<div style="margin:4px 0 8px 4px;font-size:10.5px;color:${accent};font-weight:700">⬇ เสร็จแล้วส่งต่อให้ → ${steps[i + 1].name}</div>`
            : `<div style="margin:8px 0 0 4px;font-size:10.5px;color:#15803d;font-weight:700">🏁 จบงาน — ส่งหัวหน้างานตรวจ + ออกใบประเมินงาน</div>`}
        </div>`).join("")}
    </div>`;

  const html = pageWrap(page1, 1) + pageWrap(respInner, 2) + photoPagesHTML;
  pxPrint(`ใบสั่งงาน ${wo.no} — ${totalPages} หน้า A4`, html);
}

function WorkOrderModal({ project, onClose, onSaved }) {
  const D = window.SSSData;
  const { Btn, Drawer } = window.UI;
  const emps = D.Employees || [];
  const [f, setF] = useStatePX({
    no: pxNextWoNo(),
    detail: "",
    startDate: pxTodayISO(),
    due: project.end || pxTodayISO(),
    priority: "ปกติ"
  });
  const [steps, setSteps] = useStatePX(() => emps[0] ? [{ empId: emps[0].id, duty: "" }] : []);
  const [photos, setPhotos] = useStatePX([]);
  const [showCam, setShowCam] = useStatePX(false);
  const upd = (k, v) => setF(p => ({ ...p, [k]: v }));

  const empOf = (id) => emps.find(e => e.id === id);
  const updStep = (i, k, v) => setSteps(list => list.map((s, j) => j === i ? { ...s, [k]: v } : s));
  const moveStep = (i, dir) => setSteps(list => {
    const j = i + dir;
    if (j < 0 || j >= list.length) return list;
    const next = [...list];
    const tmp = next[i]; next[i] = next[j]; next[j] = tmp;
    return next;
  });

  const resize = (file, max) => window.DeliveryStore && window.DeliveryStore.resizeImage
    ? window.DeliveryStore.resizeImage(file, max)
    : new Promise(res => { const r = new FileReader(); r.onload = () => res(r.result); r.readAsDataURL(file); });
  const pickPhotos = async (e) => {
    const files = [...e.target.files].slice(0, 12);
    e.target.value = "";
    const loaded = [];
    for (const file of files) {
      const url = await resize(file, 800);
      if (url) loaded.push({ url, name: file.name });
    }
    setPhotos(p => [...p, ...loaded].slice(0, 12));
  };

  const save = (andPrint) => {
    if (steps.length === 0) { window.toast && window.toast("กรุณาเพิ่มผู้รับผิดชอบอย่างน้อย 1 คน"); return; }
    for (let i = 0; i < steps.length; i++) {
      const e = empOf(steps[i].empId);
      if (!e) { window.toast && window.toast(`กรุณาเลือกพนักงานในลำดับที่ ${i + 1}`); return; }
      if (!steps[i].duty.trim()) { window.toast && window.toast(`กรุณากรอกหน้าที่ของ ${e.name} (ลำดับที่ ${i + 1})`); return; }
    }
    if (!f.detail.trim()) { window.toast && window.toast("กรุณาใส่รายละเอียดของงาน"); return; }
    if (!f.due) { window.toast && window.toast("กรุณากำหนดวันส่งงาน"); return; }
    const woSteps = steps.map(s => { const e = empOf(s.empId); return { empId: e.id, name: e.name, role: `${e.role} · ${e.dept}`, duty: s.duty.trim() }; });
    const wo = {
      no: f.no,
      steps: woSteps,
      assigneeIds: woSteps.map(s => s.empId),
      assignees: woSteps.map(s => s.name),
      assigneeRoles: woSteps.map(s => s.role),
      assignee: [...new Set(woSteps.map(s => s.name))].join(", "),
      detail: f.detail.trim(), startDate: f.startDate, due: f.due, priority: f.priority,
      photos: [...photos],
      issuedBy: "ปิยะ ศ.", issueDate: pxToday(), status: "เปิดงาน"
    };
    const list = [wo, ...(pxGet(project.code).workOrders || [])];
    pxSet(project.code, { workOrders: list });
    window.logActivity && window.logActivity("ออกใบสั่งงาน", `${wo.no} → ${wo.assignee} (${project.code})`, "create");
    window.toast && window.toast(`ออกใบสั่งงาน ${wo.no} — ผู้รับผิดชอบ ${woSteps.length} ลำดับแล้ว`);
    onSaved && onSaved(list);
    onClose();
    if (andPrint) setTimeout(() => printWorkOrderDoc(project, wo), 150);
  };

  return (
    <Drawer open={true} onClose={onClose} title={`ออกใบสั่งงาน · ${project.code}`} 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}}>ลูกค้า {project.customer} · กำหนดส่งโปรเจกต์ {project.due}</div>
        </div>
        <div className="field-row cols-2">
          <div className="field"><label>เลขที่ใบสั่งงาน</label><input className="input mono" value={f.no} readOnly style={{background: "var(--surface-2)"}}></input></div>
          <div className="field"><label>ความสำคัญ</label>
            <div className="payseg" style={{display: "flex", width: "100%"}}>
              {["ปกติ", "ด่วน", "ด่วนมาก"].map(p => (
                <button key={p} type="button" className={"payseg-btn" + (f.priority === p ? " active" : "")} style={{flex: 1}} onClick={() => upd("priority", p)}>{p}</button>
              ))}
            </div>
          </div>
        </div>

        {/* ผู้รับผิดชอบแบบ Timeline — เลือกพนักงาน + หน้าที่ เรียงลำดับส่งต่อ */}
        <div className="field">
          <label>ผู้รับผิดชอบตามลำดับ (Timeline — เสร็จจากคนแรกแล้วส่งต่อคนถัดไป) *</label>
          <div style={{display: "flex", flexDirection: "column", gap: 4}}>
            {steps.map((st, i) => {
              const emp = empOf(st.empId);
              return (
                <React.Fragment key={i}>
                  <div style={{border: "1px solid var(--line)", borderRadius: 10, padding: 10, display: "flex", gap: 10, alignItems: "flex-start", background: "var(--surface)"}}>
                    <div style={{width: 24, height: 24, borderRadius: "50%", background: "var(--accent)", color: "var(--accent-ink)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, flexShrink: 0, marginTop: 4}}>{i + 1}</div>
                    {window.RankAvatar && emp ? <window.RankAvatar name={emp.name} size={34}/> : null}
                    <div style={{flex: 1, display: "flex", flexDirection: "column", gap: 6, minWidth: 0}}>
                      <select className="input" value={st.empId} onChange={e => updStep(i, "empId", e.target.value)} style={{height: 32}}>
                        {emps.map(e => <option key={e.id} value={e.id}>{e.name} — {e.role} ({e.dept})</option>)}
                      </select>
                      <textarea className="textarea" value={st.duty} onChange={e => updStep(i, "duty", e.target.value)} style={{minHeight: 44}}
                        placeholder="หน้าที่ เช่น ตัดแผ่นตามแบบ DWG-021 / เชื่อมประกอบช่วง 1-3 / QC + แพ็ค"></textarea>
                    </div>
                    <div style={{display: "flex", flexDirection: "column", gap: 2}}>
                      <button className="icon-btn" title="เลื่อนขึ้น" onClick={() => moveStep(i, -1)} style={i === 0 ? {opacity: 0.3, pointerEvents: "none"} : {}}><I.chevronUp size={12}/></button>
                      <button className="icon-btn" title="เลื่อนลง" onClick={() => moveStep(i, 1)} style={i === steps.length - 1 ? {opacity: 0.3, pointerEvents: "none"} : {}}><I.chevronDown size={12}/></button>
                      <button className="icon-btn" title="ลบ" onClick={() => setSteps(list => list.filter((_, j) => j !== i))}><I.trash size={12}/></button>
                    </div>
                  </div>
                  {i < steps.length - 1 && (
                    <div style={{paddingLeft: 16, fontSize: 11, color: "var(--ink-3)", fontWeight: 600}}>↓ เสร็จแล้วส่งต่อให้</div>
                  )}
                </React.Fragment>
              );
            })}
            <Btn size="sm" icon={I.plus} onClick={() => setSteps(s => [...s, { empId: emps[0] ? emps[0].id : "", duty: "" }])}>เพิ่มผู้รับผิดชอบลำดับถัดไป</Btn>
            <div style={{fontSize: 11, color: "var(--ink-3)"}}>พิมพ์เป็นหน้าที่ 2 ของใบสั่งงาน — กรอบ Timeline พร้อมรูปพนักงาน ช่องติ้ก "ทำเสร็จแล้ว / เกิดปัญหา" และช่องลงชื่อ</div>
          </div>
        </div>

        <div className="field"><label>รายละเอียดของงาน *</label>
          <textarea className="textarea" value={f.detail} onChange={e => upd("detail", e.target.value)} style={{minHeight: 110}}
            placeholder={"เช่น\n- ตัดแผ่นสแตนเลส 304 ตามแบบ DWG-021 จำนวน 8 แผ่น\n- เชื่อมประกอบราวบันไดช่วงที่ 1-3\n- เก็บงานขัดเงา + QC ก่อนส่ง"}></textarea>
        </div>

        {/* Photos */}
        <div className="field">
          <label>รูปภาพประกอบ (แบบ/หน้างาน — พิมพ์ต่อท้ายใบสั่งงาน)</label>
          <div style={{display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap"}}>
            <Btn size="sm" icon={I.camera} onClick={() => setShowCam(true)}>ถ่ายรูป</Btn>
            <label className="btn sm" style={{cursor: "pointer"}}>
              <input type="file" accept="image/*" multiple style={{display: "none"}} onChange={pickPhotos}></input>
              อัพโหลดรูป
            </label>
            <span style={{fontSize: 11, color: "var(--ink-3)"}}>{photos.length > 0 ? `${photos.length} รูป · พิมพ์เพิ่ม ${Math.ceil(photos.length / 2)} หน้า A4 (มีเลขหน้ากำกับ)` : "ไม่บังคับ · 2 รูปต่อ 1 หน้า A4"}</span>
          </div>
          {photos.length > 0 && (
            <div style={{display: "flex", gap: 6, flexWrap: "wrap", marginTop: 8}}>
              {photos.map((p, i) => (
                <div key={i} style={{position: "relative", width: 64, height: 64, borderRadius: 6, overflow: "hidden", border: "1px solid var(--line)"}}>
                  <img src={p.url} alt={p.name} style={{width: "100%", height: "100%", objectFit: "cover"}}/>
                  <span style={{position: "absolute", left: 3, bottom: 3, fontSize: 9, background: "rgba(0,0,0,0.6)", color: "white", padding: "0 5px", borderRadius: 3}}>{i + 1}</span>
                  <button onClick={() => setPhotos(ph => ph.filter((_, j) => j !== i))}
                    style={{position: "absolute", top: 2, right: 2, width: 16, height: 16, padding: 0, borderRadius: "50%", background: "rgba(0,0,0,0.7)", color: "white", border: 0, cursor: "pointer", fontSize: 10, lineHeight: "14px"}}>×</button>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="field-row cols-2">
          <div className="field"><label>วันที่เริ่มงาน</label><input className="input" type="date" value={f.startDate} onChange={e => upd("startDate", e.target.value)}></input></div>
          <div className="field"><label>กำหนดส่งงาน *</label><input className="input" type="date" value={f.due} onChange={e => upd("due", e.target.value)}></input></div>
        </div>
      </div>
      {showCam && window.CameraCaptureModal && (
        <window.CameraCaptureModal onClose={() => setShowCam(false)} onCapture={(url) => setPhotos(p => [...p, { url, name: "camera-" + Date.now() }].slice(0, 12))}/>
      )}
    </Drawer>
  );
}

// ---------- Job summary (ใบสรุปงาน: ค่าแรง + ค่าวัสดุ) ----------
function printJobSummaryDoc(project) {
  const D = window.SSSData;
  const C = D.Company;
  const accent = "#0f766e";
  const fmt = (n) => Math.round(n).toLocaleString();

  // Cost breakdown
  const labor = Math.round(project.actual * 0.40);
  const subcontract = Math.round(project.actual * 0.15);
  const materialTotal = project.actual - labor - subcontract;

  // Material detail: stock withdrawals for this job
  const moves = (D.InventoryMoves || []).filter(m => m.ref === project.code && m.qty < 0);
  const matRows = moves.map(m => {
    const prod = (D.Products || []).find(p => p.sku === m.sku);
    const cost = Math.abs(m.qty) * (prod?.cost || 0);
    return { name: m.name, qty: Math.abs(m.qty), unit: prod?.unit || "", cost };
  });
  const matFromStock = matRows.reduce((s, r) => s + r.cost, 0);
  // Linked expenses
  const linkedExtra = pxGet(project.code).linkedExpenses || [];
  const expenses = (D.Expenses || []).filter(e => (project.expenseLinks || []).includes(e.no) || linkedExtra.includes(e.no));
  const extraExpenses = pxGet(project.code).expenses || [];
  const expTotal = expenses.reduce((s, e) => s + e.amount, 0) + extraExpenses.reduce((s, e) => s + (+e.amount || 0), 0);
  const matOther = Math.max(0, materialTotal - matFromStock - expTotal);
  const matSum = matFromStock + expTotal + matOther;

  const profit = project.budget - project.actual;
  const margin = project.budget > 0 ? ((profit / project.budget) * 100).toFixed(1) : "0.0";

  const rowStyle = 'style="padding:8px 10px;border-bottom:1px solid #f1efeb;font-size:12px"';
  const rowR = 'style="padding:8px 10px;border-bottom:1px solid #f1efeb;font-size:12px;text-align:right;font-variant-numeric:tabular-nums"';

  const html = `<div style="background:white;color:#0c0a09;padding:36px 44px;min-height:90vh">
    ${pxDocHeader(C, "ใบสรุปงาน", "JOB SUMMARY · สรุปค่าแรงและค่าวัสดุ", accent)}
    <div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px;margin-bottom:18px;font-size:12.5px">
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:10px 14px">
        <div style="font-size:10px;color:#78716c;margin-bottom:2px">โปรเจกต์</div>
        <div style="font-weight:600">${project.name}</div>
        <div style="font-family:monospace;font-size:11px;color:#57534e">${project.code} · ${project.customer}</div>
      </div>
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:10px 14px">
        <div style="font-size:10px;color:#78716c;margin-bottom:2px">ระยะเวลา</div>
        <div style="font-weight:600">${pxThaiDate(project.start)} → ${pxThaiDate(project.end)}</div>
        <div style="font-size:11px;color:#57534e">หัวหน้างาน ${project.lead}</div>
      </div>
      <div style="border:1px solid #e7e5e4;border-radius:6px;padding:10px 14px">
        <div style="font-size:10px;color:#78716c;margin-bottom:2px">สถานะ · ความคืบหน้า</div>
        <div style="font-weight:600">${project.status} · ${project.progress}%</div>
        <div style="font-size:11px;color:#57534e">จัดทำเมื่อ ${pxToday()}</div>
      </div>
    </div>

    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#44403c;margin-bottom:6px">1. ค่าแรงพนักงาน</div>
    <table style="width:100%;border-collapse:collapse;margin-bottom:16px">
      <tr style="background:${accent};color:white"><th style="padding:7px 10px;font-size:10.5px;text-align:left">รายการ</th><th style="padding:7px 10px;font-size:10.5px;text-align:left">รายละเอียด</th><th style="padding:7px 10px;font-size:10.5px;text-align:right">จำนวนเงิน (บาท)</th></tr>
      <tr><td ${rowStyle}>ค่าจ้าง / OT ทีมผลิต</td><td ${rowStyle}>หัวหน้างาน ${project.lead} + ทีมผลิต (จากการลงเวลา)</td><td ${rowR}>${fmt(labor)}</td></tr>
      <tr><td ${rowStyle}>ค่าบริการภายนอก (subcontract)</td><td ${rowStyle}>ชุบ/พ่นสี/ขนส่ง ภายนอก</td><td ${rowR}>${fmt(subcontract)}</td></tr>
      <tr style="background:#f3f1ee;font-weight:700"><td colspan="2" style="padding:9px 10px;font-size:12px">รวมค่าแรง</td><td style="padding:9px 10px;font-size:12.5px;text-align:right">${fmt(labor + subcontract)}</td></tr>
    </table>

    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#44403c;margin-bottom:6px">2. ค่าวัสดุ</div>
    <table style="width:100%;border-collapse:collapse;margin-bottom:16px">
      <tr style="background:${accent};color:white"><th style="padding:7px 10px;font-size:10.5px;text-align:left">รายการ</th><th style="padding:7px 10px;font-size:10.5px;text-align:left">รายละเอียด</th><th style="padding:7px 10px;font-size:10.5px;text-align:right">จำนวนเงิน (บาท)</th></tr>
      ${matRows.map(r => `<tr><td ${rowStyle}>วัตถุดิบเบิกจากสต็อก</td><td ${rowStyle}>${r.name} × ${r.qty} ${r.unit}</td><td ${rowR}>${fmt(r.cost)}</td></tr>`).join("")}
      ${expenses.map(e => `<tr><td ${rowStyle}>ค่าใช้จ่ายผูกโปรเจกต์</td><td ${rowStyle}>${e.category} · ${e.vendor} (${e.no})</td><td ${rowR}>${fmt(e.amount)}</td></tr>`).join("")}
      ${extraExpenses.map(e => `<tr><td ${rowStyle}>ค่าใช้จ่ายเพิ่มเติม</td><td ${rowStyle}>${e.category} · ${e.vendor || "—"}</td><td ${rowR}>${fmt(+e.amount || 0)}</td></tr>`).join("")}
      ${matOther > 0 ? `<tr><td ${rowStyle}>วัสดุสิ้นเปลือง / อื่น ๆ</td><td ${rowStyle}>ลวดเชื่อม ใบตัด แก๊ส ฯลฯ</td><td ${rowR}>${fmt(matOther)}</td></tr>` : ""}
      <tr style="background:#f3f1ee;font-weight:700"><td colspan="2" style="padding:9px 10px;font-size:12px">รวมค่าวัสดุ</td><td style="padding:9px 10px;font-size:12.5px;text-align:right">${fmt(matSum)}</td></tr>
    </table>

    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#44403c;margin-bottom:6px">3. สรุปต้นทุนและกำไร</div>
    <table style="width:100%;border-collapse:collapse;margin-bottom:24px;font-size:12.5px">
      <tr><td style="padding:7px 10px;color:#57534e">รวมค่าแรงพนักงาน</td><td style="padding:7px 10px;text-align:right;font-variant-numeric:tabular-nums">${fmt(labor + subcontract)}</td></tr>
      <tr><td style="padding:7px 10px;color:#57534e">รวมค่าวัสดุ</td><td style="padding:7px 10px;text-align:right;font-variant-numeric:tabular-nums">${fmt(matSum)}</td></tr>
      <tr style="border-top:1px solid #d6d3d1"><td style="padding:8px 10px;font-weight:600">ต้นทุนรวมทั้งหมด</td><td style="padding:8px 10px;text-align:right;font-weight:700">${fmt(labor + subcontract + matSum)}</td></tr>
      <tr><td style="padding:7px 10px;color:#57534e">มูลค่างาน (Revenue)</td><td style="padding:7px 10px;text-align:right;font-variant-numeric:tabular-nums">${fmt(project.budget)}</td></tr>
      <tr style="border-top:2px solid ${accent};background:${accent}0d"><td style="padding:10px;font-weight:700;font-size:13.5px">กำไรขั้นต้น (Margin ${margin}%)</td><td style="padding:10px;text-align:right;font-weight:700;font-size:15px;color:${profit >= 0 ? "#15803d" : "#b91c1c"}">฿${fmt(profit)}</td></tr>
    </table>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:40px;font-size:11px">
      <div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:40px"><b>ผู้จัดทำ</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ดวงใจ บัญชี ) · ${pxToday()}</div></div></div>
      <div style="text-align:center"><div style="border-top:1px dashed #57534e;padding-top:6px;margin-top:40px"><b>ผู้อนุมัติ</b><div style="color:#78716c;font-size:10px;margin-top:2px">( ปิยะ ศรีสวัสดิ์ ) · ............................</div></div></div>
    </div>
    <div style="margin-top:30px;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>${project.code} · ใบสรุปงาน · ออกโดยระบบ SSS</span>
    </div>
  </div>`;
  pxPrint(`ใบสรุปงาน — ${project.code}`, html);
  window.logActivity && window.logActivity("ออกใบสรุปงาน", `${project.code} — ${project.name}`, "create");
}

// ---------- Create / Edit project ----------
function pxNextJobCode() {
  const D = window.SSSData;
  const nums = [...pxUserLoad(), ...(D.Projects || [])]
    .map(p => (String(p.code).match(/JOB-2569-(\d+)/) || [])[1])
    .filter(Boolean).map(Number);
  const n = (nums.length ? Math.max(...nums) : 0) + 1;
  return "JOB-2569-" + String(n).padStart(3, "0");
}

function ProjectFormModal({ project, onClose, onSaved }) {
  const D = window.SSSData;
  const { Btn, Drawer } = window.UI;
  const isEdit = !!project;
  const emps = (D.Employees || []).filter(e => /ผลิต|ออกแบบ/.test(e.dept || "") || true);
  const [f, setF] = useStatePX(() => isEdit ? { ...project } : {
    code: pxNextJobCode(), name: "", customer: "", budget: 0, actual: 0,
    progress: 0, status: "ร่าง", lead: emps[0]?.name || "",
    start: pxTodayISO(), end: pxTodayISO()
  });
  const upd = (k, v) => setF(p => ({ ...p, [k]: v }));

  const save = (thenWorkOrder) => {
    if (!f.name.trim()) { window.toast && window.toast("กรุณาใส่ชื่อโปรเจกต์"); return; }
    if (!f.customer.trim()) { window.toast && window.toast("กรุณาใส่ชื่อลูกค้า"); return; }
    const due = pxThaiDate(f.end);
    const record = { ...f, name: f.name.trim(), customer: f.customer.trim(), budget: +f.budget || 0, due };
    if (isEdit) {
      const users = pxUserLoad();
      if (users.some(u => u.code === record.code)) {
        pxUserSave(users.map(u => u.code === record.code ? { ...u, ...record } : u));
      } else {
        pxSet(record.code, { fields: { name: record.name, customer: record.customer, budget: record.budget, lead: record.lead, start: record.start, end: record.end, due } });
      }
      window.toast && window.toast("บันทึกการแก้ไขโปรเจกต์แล้ว");
    } else {
      record.updates = [{ date: pxTodayISO(), who: "ปิยะ ศ.", text: "สร้างโปรเจกต์", type: "milestone" }];
      record.expenseLinks = [];
      pxUserSave([record, ...pxUserLoad()]);
      window.logActivity && window.logActivity("สร้างโปรเจกต์", `${record.code} — ${record.name}`, "create");
      window.toast && window.toast(`สร้างโปรเจกต์ ${record.code} แล้ว`);
    }
    onSaved && onSaved(record, thenWorkOrder);
    onClose();
  };

  return (
    <Drawer open={true} onClose={onClose} title={isEdit ? `แก้ไขโปรเจกต์ · ${f.code}` : "สร้างโปรเจกต์ใหม่"} wide
      footer={<>
        <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
        {!isEdit && <Btn kind="ghost" icon={I.doc} onClick={() => save(true)}>บันทึก + ออกใบสั่งงาน</Btn>}
        <Btn kind="primary" icon={I.check} onClick={() => save(false)}>{isEdit ? "บันทึกการแก้ไข" : "บันทึกโปรเจกต์"}</Btn>
      </>}>
      <div style={{display: "flex", flexDirection: "column", gap: 12}}>
        <div className="field-row cols-2">
          <div className="field"><label>รหัสโปรเจกต์</label><input className="input mono" value={f.code} readOnly style={{background: "var(--surface-2)"}}></input></div>
          <div className="field"><label>หัวหน้างาน</label>
            <select className="input" value={f.lead} onChange={e => upd("lead", e.target.value)}>
              {emps.map(e => <option key={e.id} value={e.name}>{e.name} — {e.role}</option>)}
            </select>
          </div>
        </div>
        <div className="field"><label>ชื่อโปรเจกต์ *</label><input className="input" value={f.name} onChange={e => upd("name", e.target.value)} placeholder="เช่น ราวบันไดสแตนเลส โครงการ..."></input></div>
        <div className="field"><label>ลูกค้า *</label><input className="input" value={f.customer} onChange={e => upd("customer", e.target.value)} placeholder="ชื่อบริษัทลูกค้า"></input></div>
        <div className="field-row cols-2">
          <div className="field"><label>มูลค่างาน / งบประมาณ (บาท)</label><input className="input" type="number" value={f.budget} onChange={e => upd("budget", +e.target.value)}></input></div>
          <div className="field"><label>สถานะเริ่มต้น</label>
            <select className="input" value={f.status} onChange={e => upd("status", e.target.value)}>
              {["ร่าง", "ออกแบบ 3D", "กำลังผลิต", "ตรวจสอบคุณภาพ", "รอเก็บเงิน", "ส่งงาน"].map(s => <option key={s}>{s}</option>)}
            </select>
          </div>
        </div>
        <div className="field-row cols-2">
          <div className="field"><label>วันที่เริ่ม</label><input className="input" type="date" value={f.start} onChange={e => upd("start", e.target.value)}></input></div>
          <div className="field"><label>กำหนดส่ง</label><input className="input" type="date" value={f.end} onChange={e => upd("end", e.target.value)}></input></div>
        </div>
        {!isEdit && (
          <div style={{padding: "10px 14px", background: "var(--brand-bg, var(--surface-2))", border: "1px solid var(--line)", borderRadius: 8, fontSize: 12, color: "var(--ink-3)"}}>
            หลังบันทึก สามารถ <b style={{color: "var(--ink-1)"}}>ออกใบสั่งงาน</b> เพื่อกำหนดผู้รับผิดชอบ รายละเอียดงาน และกำหนดส่งได้ทันที
          </div>
        )}
      </div>
    </Drawer>
  );
}

// ---------- Add expense ----------
function ProjectExpenseModal({ project, onClose, onSaved }) {
  const { Btn } = window.UI;
  const [f, setF] = useStatePX({ category: "ค่าวัสดุ/วัตถุดิบ", vendor: "", amount: "" });
  const upd = (k, v) => setF(p => ({ ...p, [k]: v }));
  const save = () => {
    if (!f.amount || +f.amount <= 0) { window.toast && window.toast("กรอกจำนวนเงินให้ถูกต้อง"); return; }
    const exp = { date: pxToday(), category: f.category, vendor: f.vendor || "—", amount: +f.amount, status: "บันทึกแล้ว" };
    const list = [...(pxGet(project.code).expenses || []), exp];
    pxSet(project.code, { expenses: list });
    window.toast && window.toast(`เพิ่มค่าใช้จ่าย ฿${(+f.amount).toLocaleString()} แล้ว`);
    onSaved && onSaved(list);
    onClose();
  };
  return (
    <>
      <div className="scrim" style={{zIndex: 80}} onClick={onClose}></div>
      <div style={{position: "fixed", left: "50%", top: "50%", transform: "translate(-50%, -50%)", zIndex: 81, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 10, padding: 18, width: 400, maxWidth: "94vw", boxShadow: "var(--shadow-lg)"}}>
        <div style={{fontSize: 14, fontWeight: 600, marginBottom: 12}}>เพิ่มค่าใช้จ่าย · {project.code}</div>
        <div className="field mb"><label>หมวด</label>
          <select className="input" value={f.category} onChange={e => upd("category", e.target.value)}>
            {["ค่าวัสดุ/วัตถุดิบ", "ค่าแรงภายนอก", "ค่าขนส่ง", "ค่าเครื่องมือ/อุปกรณ์", "อื่น ๆ"].map(c => <option key={c}>{c}</option>)}
          </select>
        </div>
        <div className="field mb"><label>ผู้ขาย / รายละเอียด</label><input className="input" value={f.vendor} onChange={e => upd("vendor", e.target.value)} placeholder="เช่น ร้านวัสดุสามพราน"></input></div>
        <div className="field mb"><label>จำนวนเงิน (บาท)</label><input className="input" type="number" min="0" value={f.amount} onChange={e => upd("amount", e.target.value)} autoFocus></input></div>
        <div style={{display: "flex", gap: 8, justifyContent: "flex-end"}}>
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="primary" icon={I.check} onClick={save}>บันทึก</Btn>
        </div>
      </div>
    </>
  );
}

window.ProjX = { pxGet, pxSet, upLoad: pxUserLoad, upSave: pxUserSave, pxThaiDate, pxToday, pxTodayISO, printWorkOrderDoc, printJobSummaryDoc };
window.WorkOrderModal = WorkOrderModal;
window.ProjectFormModal = ProjectFormModal;
window.ProjectExpenseModal = ProjectExpenseModal;
