// หน้างานซ่อม + ใบรับซ่อม
function RepairsPage({ ui, user }) {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const branch = ui.branch === "ALL" ? (user.branch || "B1") : ui.branch;
  const [filter, setFilter] = React.useState("งานค้าง");
  const [rq, setRq] = React.useState("");
  const [openId, setOpenId] = React.useState(ui.param || null);
  const [showForm, setShowForm] = React.useState(false);
  const [formBranch, setFormBranch] = React.useState(branch);
  const [printRp, setPrintRp] = React.useState(null);
  const [receiptRp, setReceiptRp] = React.useState(null);
  const [payRp, setPayRp] = React.useState(null);
  const [partCat, setPartCat] = React.useState("");
  const [partSub, setPartSub] = React.useState("");
  const [partPick, setPartPick] = React.useState("");
  const [lb, setLb] = React.useState(null);   // lightbox { imgs, index }
  const [f, setF] = React.useState({ customer: "", phone: "", brand: "Apple", brandOther: "", device: "", imei: "", code: "", color: "", accessories: [], imgs: [], issue: "", symptom: "", est: "", deposit: "", tech: "", due: "" });
  React.useEffect(() => { if (ui.param) setOpenId(ui.param); }, [ui.param]);

  const techs = st.users.filter((u) => u.role === "tech");
  // เจ้าของร้านและช่างทุกคน เห็นงานซ่อมทุกงานของทุกสาขา/ทุกคน
  const seeAll = user.role === "owner" || user.role === "tech";
  const all = st.repairs.filter((r) => seeAll || ui.branch === "ALL" || r.branch === ui.branch);
  const list = all.filter((r) =>
    (filter === "ทั้งหมด" ? true :
    filter === "งานค้าง" ? !["ส่งมอบแล้ว", "ยกเลิก"].includes(r.status) :
    r.status === filter)
    && (rq.trim() === "" || `${r.id} ${r.customer || ""} ${r.phone || ""} ${r.device || ""} ${r.brand || ""} ${r.imei || ""} ${r.code || ""} ${r.issue || ""}`.toLowerCase().includes(rq.trim().toLowerCase()))
  );
  const rp = st.repairs.find((r) => r.id === openId);
  // พนักงานขาย/ผู้จัดการสาขา: เมื่อรับเครื่องแล้วจนถึงก่อน "รอลูกค้ารับ" ดูได้อย่างเดียว แก้ไขไม่ได้
  const editLocked = rp && (user.role === "sales" || user.role === "manager") && (() => {
    const i = REPAIR_STATUSES.indexOf(rp.status);
    return i >= REPAIR_STATUSES.indexOf("รับเครื่องแล้ว") && i < REPAIR_STATUSES.indexOf("รอลูกค้ารับ");
  })();
  // เมื่อส่งมอบแล้ว: ช่างผู้รับผิดชอบ+เจ้าของร้าน แก้ได้ทุกสถานะ · พนักงานขาย/ผู้จัดการแก้กลับได้แค่ “กำลังซ่อม”
  const canSetStatus = (s) => {
    if (!rp || rp.status !== "ส่งมอบแล้ว") return true;
    if (s === "ส่งมอบแล้ว") return true; // คงสถานะเดิม
    if (user.role === "owner" || (user.role === "tech" && rp.tech === user.id)) return true;
    if ((user.role === "sales" || user.role === "manager") && s === "กำลังซ่อม") return true;
    return false;
  };
  const setE = (k) => (e) => setF((x) => ({ ...x, [k]: e.target.value }));

  const counts = {};
  REPAIR_STATUSES.forEach((s) => counts[s] = all.filter((r) => r.status === s).length);

  const submit = () => {
    if (!f.customer || !f.phone || !f.device || !f.issue) { toast("กรอกลูกค้า เบอร์โทร เครื่อง และอาการให้ครบ", "danger"); return; }
    const brand = f.brand === "อื่นๆ" ? (f.brandOther || "อื่นๆ") : f.brand;
    dispatch({ type: "REPAIR_ADD", repair: { ...f, brand, est: Number(f.est) || 0, deposit: Number(f.deposit) || 0, branch: formBranch, tech: f.tech || (techs[0] ? techs[0].id : ""), due: f.due ? new Date(f.due).getTime() : null, note: "" } });
    toast("เปิดใบรับซ่อมเรียบร้อย");
    setShowForm(false);
    setF({ customer: "", phone: "", brand: "Apple", brandOther: "", device: "", imei: "", code: "", color: "", accessories: [], imgs: [], issue: "", symptom: "", est: "", deposit: "", tech: "", due: "" });
    setTimeout(() => setPrintRp("LATEST"), 250);
  };
  const latestRp = printRp === "LATEST" ? st.repairs[0] : printRp;
  // สร้างใบเสร็จจากงานซ่อม (ค่าบริการ หักมัดจำที่ชำระแล้ว)
  const buildRepairSale = (id) => {
    if (!id) return null;
    const rp = st.repairs.find((r) => r.id === id);
    if (!rp) return null;
    const usedParts = rp.parts || [];
    // มีการเบิกอะไหล่ → ตัดค่าซ่อม (ประเมิน) เป็น 0 และไม่แสดงบนใบเสร็จ (ใบรับซ่อมยังคงแสดง)
    const items = usedParts.length > 0
      ? []
      : [{ productId: null, name: `ค่าบริการ/ค่าแรงซ่อม: ${rp.device}${rp.issue ? " — " + rp.issue : ""}`, qty: 1, price: Number(rp.est) || 0 }];
    // อะไหล่ที่ใช้ไปทั้งหมด — แสดงเป็นรายการในใบเสร็จ
    usedParts.forEach((pt) => {
      const pp = prodOf(st, pt.productId) || { name: "(อะไหล่)", price: pt.price || 0 };
      items.push({ productId: pt.productId, name: `อะไหล่: ${pp.name}`, qty: pt.qty || 1, price: pt.price != null ? pt.price : (pp.price || 0) });
    });
    if (Number(rp.deposit) > 0) items.push({ productId: null, name: "หักมัดจำที่ชำระแล้ว", qty: 1, price: -(Number(rp.deposit) || 0) });
    return { id: rp.invNo || rp.id, refRepair: rp.id, branch: rp.branch, ts: Date.now(), customer: `${rp.customer}${rp.phone ? " · " + rp.phone : ""}`, by: rp.tech, pay: rp.pay || "เงินสด", items, discount: Number(rp.discount) || 0 };
  };
  const openReceipt = (rp) => { dispatch({ type: "REPAIR_INVOICE", id: rp.id }); setReceiptRp(rp.id); };

  // ช่องชำระเงิน (แบบ POS)
  function PaymentModal({ open, onClose, customer, items, onSettle }) {
    const [pay, setPay] = React.useState("เงินสด");
    const [discount, setDiscount] = React.useState("");
    React.useEffect(() => { if (open) setDiscount(""); }, [open]);
    const subTotal = items.reduce((a, it) => a + (it.qty * it.price), 0);
    const disc = Math.min(Number(discount) || 0, subTotal);
    const total = Math.max(0, subTotal - disc);
    return (
      <Modal open={open} onClose={onClose} title="ชำระเงิน" width={420}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn onClick={() => { onSettle(pay, disc); setPay("เงินสด"); setDiscount(""); }}>✓ ชำระเงิน & พิมพ์ใบเสร็จ</Btn>
        </React.Fragment>}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ fontSize: 13, background: T.chipBg, borderRadius: 10, padding: "12px 14px" }}>
            <div style={{ color: T.sub, marginBottom: 6 }}>ลูกค้า</div>
            <div style={{ fontWeight: 600 }}>{customer}</div>
          </div>
          <div style={{ fontSize: 12.5, background: T.chipBg, borderRadius: 10, padding: "12px 14px", maxHeight: 200, overflowY: "auto" }}>
            <div style={{ color: T.sub, marginBottom: 8, fontWeight: 600 }}>รายการ</div>
            {items.map((it, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 12 }}>
                <span>{it.qty} × {it.name}</span>
                <span style={{ fontWeight: 600 }}>{fmtMoney(it.qty * it.price)}</span>
              </div>
            ))}
          </div>
          <Field label="ส่วนลด (บาท)">
            <NumInput value={discount} onChange={(e) => setDiscount(e.target.value)} placeholder="0" />
          </Field>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: T.infoBg, borderRadius: 10, padding: "12px 14px" }}>
            <span style={{ color: T.sub, fontWeight: 600 }}>รวมทั้งสิ้น</span>
            <span style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 18, color: T.primary }}>{fmtMoney(total)}</span>
          </div>
          <Field label="ชำระโดย">
            <Select value={pay} onChange={setPay} options={["เงินสด", "โอน/QR", "บัตรเครดิต"]} />
          </Field>
        </div>
      </Modal>
    );
  }
  Object.assign(window, { PaymentModal });

  const labLocs = rp ? st.locations.filter((l) => l.branch === rp.branch) : [];
  // หมวดอะไหล่
  const partCats = st.cats.filter((c) => c.parts);
  const partSubsInCat = partCat ? (partCats.find((c) => c.name === partCat)?.subs || []) : [];
  const partsInSub = rp && partCat && partSub ? st.products.filter((p) => p.cat === partCat && p.sub === partSub && stockTotal(p) > 0) : [];
  const usePart = () => {
    if (!partPick) return;
    const p = prodOf(st, partPick);
    // เบิกจากสาขาตัวเองก่อน ถ้าไม่มีดึงจากสาขาอื่น
    const loc = labLocs.find((l) => (p.stock[l.id] || 0) > 0)
      || st.locations.find((l) => l.branch === rp.branch && (p.stock[l.id] || 0) > 0)
      || st.locations.find((l) => (p.stock[l.id] || 0) > 0);
    if (!loc) { toast("อะไหล่นี้ไม่มีสต็อกในทุกสาขา", "danger"); return; }
    const otherBranch = loc.branch !== rp.branch;
    dispatch({ type: "REPAIR_USE_PART", id: rp.id, productId: partPick, qty: 1, locId: loc.id, by: user.id });
    toast(`ตัดสต็อก ${p.name} จาก ${loc.name}${otherBranch ? ` (${branchOf(st, loc.branch).short})` : ""} แล้ว`);
    setPartPick(""); setPartSub(""); setPartCat("");
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", gap: 7, alignItems: "center", flexWrap: "wrap" }}>
        {["งานค้าง", ...REPAIR_STATUSES, "ทั้งหมด"].map((s) => (
          <Btn key={s} sm kind={filter === s ? "primary" : "ghost"} onClick={() => setFilter(s)}>
            {s}{counts[s] != null && counts[s] > 0 ? ` (${counts[s]})` : ""}
          </Btn>
        ))}
        <div style={{ flex: 1, minWidth: 200, marginLeft: "auto" }}><SearchBox value={rq} onChange={setRq} placeholder="ค้นหา — เลขที่ใบซ่อม / ลูกค้า / เบอร์ / รุ่น / IMEI / อาการ…" /></div>
        <Btn onClick={() => setShowForm(true)}>⊕ เปิดใบรับซ่อม</Btn>
      </div>

      <Card style={{ padding: "6px 18px 8px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "86px 1fr 1.1fr 1fr 0.8fr 92px auto", gap: 10, fontSize: 11.5, color: T.sub, fontWeight: 700, padding: "10px 4px 8px", borderBottom: `1px solid ${T.border}` }}>
          <div>เลขที่</div><div>ลูกค้า / เครื่อง</div><div>งานซ่อม</div><div>ช่าง</div><div>นัดรับ</div><div>ค่าซ่อม</div><div>สถานะ</div>
        </div>
        {list.map((r, i) => {
          const od = r.due && r.due < Date.now() && !["ส่งมอบแล้ว", "ซ่อมเสร็จ", "รอลูกค้ารับ"].includes(r.status);
          return (
            <div key={r.id} className="ss-row" onClick={() => setOpenId(r.id)} style={{ display: "grid", gridTemplateColumns: "86px 1fr 1.1fr 1fr 0.8fr 92px auto", gap: 10, alignItems: "center", fontSize: 13, padding: "11px 4px", borderBottom: i < list.length - 1 ? `1px solid ${T.rowBorder}` : "none", cursor: "pointer", animation: `ss-rise .35s ${i * 35}ms ease backwards` }}>
              <div style={{ fontWeight: 700, color: T.primary, fontSize: 12.5 }}>{r.id}</div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.customer} · {r.brand ? r.brand + " " : ""}{r.device}</div>
                <div style={{ fontSize: 11, color: T.sub }}>{branchOf(st, r.branch).short} · รับ {fmtDate(r.ts)}</div>
              </div>
              <div style={{ color: T.sub, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.issue}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5 }}>
                <Avatar name={userOf(st, r.tech).name} img={userOf(st, r.tech).img} size={24} />{userOf(st, r.tech).name.split(" ")[0]}
              </div>
              <div style={{ fontSize: 12, color: od ? T.accent : T.sub, fontWeight: od ? 800 : 400 }}>{r.due ? fmtDate(r.due) : "—"}{od && " ⚠"}</div>
              <div style={{ fontWeight: 700 }}>{fmtMoney(r.est)}</div>
              <Badge tone={REPAIR_TONES[r.status]}>{r.status}</Badge>
            </div>
          );
        })}
        {list.length === 0 && <EmptyState text="ไม่มีงานซ่อมในสถานะนี้" />}
      </Card>

      {/* ── รายละเอียดงานซ่อม ── */}
      <Modal open={!!rp} onClose={() => setOpenId(null)} title={rp ? `${rp.id} · ${rp.device}` : ""} width={640}
        footer={rp && <React.Fragment>
          {rp.status === "รอลูกค้ารับ"
            ? <Btn kind="warn" style={{ background: "#E8833A", color: "#fff", borderColor: "#E8833A" }} onClick={() => setPayRp(rp)}>✓ ชำระเงิน</Btn>
            : rp.status === "ส่งมอบแล้ว"
              ? <Btn kind="warn" style={{ background: "#E8833A", color: "#fff", borderColor: "#E8833A" }} onClick={() => openReceipt(rp)}>⎙ ใบเสร็จ</Btn>
              : <Btn kind="ghost" onClick={() => setPrintRp(rp)}>⎙ พิมพ์ใบรับซ่อม</Btn>}
          <Btn kind="ghost" onClick={() => setOpenId(null)}>ปิด</Btn>
        </React.Fragment>}>
        {rp && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {editLocked && (
              <div style={{ display: "flex", alignItems: "center", gap: 9, background: T.warnBg, color: T.warnFg, borderRadius: 10, padding: "10px 14px", fontSize: 12.5, fontWeight: 600 }}>
                🔒 งานอยู่ระหว่างซ่อม — ดูได้อย่างเดียว · แก้ไขได้อีกครั้งเมื่อสถานะเป็น “รอลูกค้ารับ”
              </div>
            )}
            <div style={{ display: "flex", flexDirection: "column", gap: 14, ...(editLocked ? { pointerEvents: "none", opacity: 0.92 } : {}) }}>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {REPAIR_STATUSES.map((s, i) => {
                const cur = REPAIR_STATUSES.indexOf(rp.status);
                const allowed = canSetStatus(s);
                return (
                  <button key={s} className="ss-btn" disabled={!allowed} onClick={() => { if (!allowed) { toast("งานส่งมอบแล้ว — " + ((user.role === "sales" || user.role === "manager") ? "แก้กลับได้แค่‘กำลังซ่อม’" : "เฉพาะช่างผู้รับผิดชอบ/เจ้าของร้านเท่านั้นที่แก้ได้"), "danger"); return; } dispatch({ type: "REPAIR_SET", id: rp.id, patch: { status: s } }); toast(`อัปเดตสถานะ → ${s}`, "info"); }}
                    style={{
                      border: "none", cursor: allowed ? "pointer" : "not-allowed", fontFamily: T.bodyFont, fontWeight: 700, fontSize: 11.5,
                      padding: "6px 11px", borderRadius: 999, opacity: allowed ? 1 : 0.4,
                      background: s === rp.status ? T.heroGrad : i <= cur ? T.infoBg : T.chipBg,
                      color: s === rp.status ? "#fff" : i <= cur ? T.primary : T.sub,
                    }}>{i + 1}. {s}</button>
                );
              })}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px 20px", fontSize: 13, background: T.chipBg, borderRadius: 12, padding: "12px 16px" }}>
              <div><span style={{ color: T.sub }}>ลูกค้า:</span> <b>{rp.customer}</b> · {rp.phone}</div>
              <div><span style={{ color: T.sub }}>IMEI:</span> <span style={{ fontFamily: "monospace", fontSize: 12 }}>{rp.imei || "—"}</span></div>
              <div><span style={{ color: T.sub }}>ยี่ห้อ/สี:</span> {rp.brand || "—"} · {rp.color || "—"}</div>
              <div><span style={{ color: T.sub }}>รหัสเครื่อง:</span> <span style={{ fontFamily: "monospace" }}>{rp.code || "—"}</span></div>
              <div><span style={{ color: T.sub }}>อาการ:</span> {rp.issue}</div>
              <div><span style={{ color: T.sub }}>นัดรับ:</span> {rp.due ? fmtDate(rp.due) : "—"}</div>
              <div style={{ gridColumn: "1/-1" }}><span style={{ color: T.sub }}>รับมาด้วย:</span> {(rp.accessories && rp.accessories.length) ? rp.accessories.join(" · ") : "ไม่มี"}</div>
              <div style={{ gridColumn: "1/-1", color: T.sub, fontSize: 12 }}>{rp.symptom}</div>
            </div>
            <div style={{ display: "flex", gap: 12 }}>
              <div style={{ flex: 1 }}>
                <Field label="ช่างผู้รับผิดชอบ">
                  <Select value={rp.tech} onChange={(v) => dispatch({ type: "REPAIR_SET", id: rp.id, patch: { tech: v } })}
                    options={techs.map((t) => ({ value: t.id, label: t.name }))} />
                </Field>
              </div>
              <div style={{ flex: 1 }}>
                <Field label="ค่าซ่อม (ประเมิน)">
                  <NumInput value={rp.est} onChange={(e) => dispatch({ type: "REPAIR_SET", id: rp.id, patch: { est: Number(e.target.value) || 0 } })} />
                </Field>
              </div>
              <div style={{ flex: 1 }}>
                <Field label="มัดจำ">
                  <NumInput value={rp.deposit} onChange={(e) => dispatch({ type: "REPAIR_SET", id: rp.id, patch: { deposit: Number(e.target.value) || 0 } })} />
                </Field>
              </div>
            </div>
            <div>
              <SectionTitle>อะไหล่ที่ใช้ (ตัดสต็อกอัตโนมัติ)</SectionTitle>
              {rp.parts.length === 0 && <div style={{ fontSize: 12.5, color: T.sub, marginBottom: 8 }}>ยังไม่ได้เบิกอะไหล่</div>}
              {rp.parts.map((pt, i) => {
                const p = prodOf(st, pt.productId) || { name: "(อะไหล่ถูกลบ)", price: pt.price || 0, img: null, cat: "" };
                return (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, padding: "6px 0", borderBottom: `1px solid ${T.rowBorder}` }}>
                    <ProductImg p={p} size={30} />{p.sku ? p.sku + " · " : ""}{p.name}
                    <span style={{ marginLeft: "auto", fontWeight: 700 }}>× {pt.qty} · {fmtMoney((p.price || 0) * pt.qty)}</span>
                  </div>
                );
              })}
              {rp.status === "กำลังซ่อม" ? (
                <div style={{ background: T.chipBg, borderRadius: 12, padding: "12px 14px", marginTop: 10 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: T.sub, marginBottom: 8 }}>เบิกอะไหล่ — 1) เลือกหมวดหมู่ → 2) เลือกหมวดย่อย → 3) เลือกรายการ → 3) กดเบิกใช้</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                    <div style={{ display: "flex", gap: 8, alignItems: "flex-end", flexWrap: "wrap" }}>
                      <div style={{ flex: "1 1 150px" }}>
                        <div style={{ fontSize: 11, color: T.sub, marginBottom: 4 }}>1. หมวดหมู่</div>
                        <Select value={partCat} onChange={(v) => { setPartCat(v); setPartSub(""); setPartPick(""); }} placeholder="— เลือกหมวด —"
                          options={partCats.map((c) => ({ value: c.name, label: c.name }))} />
                      </div>
                      <div style={{ flex: "1 1 150px" }}>
                        <div style={{ fontSize: 11, color: T.sub, marginBottom: 4 }}>2. หมวดย่อย</div>
                        <Select value={partSub} onChange={(v) => { setPartSub(v); setPartPick(""); }} placeholder={partCat ? "— เลือกหมวด —" : "— เลือกหมวดหมู่ก่อน —"}
                          options={partSubsInCat.map((s) => ({ value: s, label: s }))} />
                      </div>
                      <div style={{ flex: "2 1 280px" }}>
                        <div style={{ fontSize: 11, color: T.sub, marginBottom: 4 }}>3. รายการอะไหล่</div>
                        <Select value={partPick} onChange={setPartPick} placeholder={partSub ? "— เลือกอะไหล่ —" : "— เลือกหมวดย่อยก่อน —"}
                          options={partsInSub.map((p) => { const here = stockInBranch(st, p, rp.branch); const tot = stockTotal(p); return { value: p.id, label: `${p.sku} · ${p.name} (${here > 0 ? `เหลือ ${here}` : `สาขาอื่น ${tot}`})` }; })} />
                      </div>
                    </div>
                    <Btn kind="ok" onClick={usePart} disabled={!partPick} style={{ alignSelf: "flex-start" }}>⊕ เบิกใช้ ตัดสต็อก</Btn>
                  </div>
                  {partSub && partsInSub.length === 0 && <div style={{ fontSize: 11.5, color: T.accent, marginTop: 7 }}>ไม่มีอะไหล่ในหมวดนี้ที่มีสต็อกในทุกสาขา</div>}
                </div>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 8, background: T.warnBg, color: T.warnFg, borderRadius: 10, padding: "9px 13px", marginTop: 10, fontSize: 12.5, fontWeight: 600 }}>
                  ⚠ เบิกอะไหล่ตัดสต็อกได้เมื่องานอยู่ในสถานะ “กำลังซ่อม” · กดสถานะด้านบนเพื่อเปลี่ยน
                </div>
              )}
            </div>
            <Field label="บันทึกช่าง">
              <TextArea value={rp.note} onChange={(e) => dispatch({ type: "REPAIR_SET", id: rp.id, patch: { note: e.target.value } })} placeholder="บันทึกการตรวจ/ซ่อม…" />
            </Field>
            </div>
          </div>
        )}
      </Modal>

      {/* ── ฟอร์มเปิดใบรับซ่อม ── */}
      <Modal open={showForm} onClose={() => setShowForm(false)} title="เปิดใบรับซ่อมใหม่" width={620}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setShowForm(false)}>ยกเลิก</Btn>
          <Btn onClick={submit}>บันทึก & พิมพ์ใบรับซ่อม</Btn>
        </React.Fragment>}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {user.role === "owner" && <Field label="ประจำสาขา"><Select value={formBranch} onChange={setFormBranch} options={st.branches.map((b) => ({ value: b.id, label: b.name }))} /></Field>}
          <Field label="ชื่อลูกค้า" req><TextInput value={f.customer} onChange={setE("customer")} /></Field>
          <Field label="เบอร์โทร" req><TextInput value={f.phone} onChange={setE("phone")} /></Field>
          <Field label="ยี่ห้อ" req>
            <Select value={f.brand} onChange={(v) => setF((x) => ({ ...x, brand: v }))}
              options={BRANDS.filter((b) => b !== "OEM")} />
          </Field>
          {f.brand === "อื่นๆ" ? (
            <Field label="ระบุยี่ห้ออื่นๆ"><TextInput value={f.brandOther} onChange={setE("brandOther")} placeholder="พิมพ์ชื่อยี่ห้อ" /></Field>
          ) : (
            <Field label="รุ่นเครื่อง" req><TextInput value={f.device} onChange={setE("device")} placeholder="เช่น iPhone 13 Pro" /></Field>
          )}
          {f.brand === "อื่นๆ" && (
            <Field label="รุ่นเครื่อง" req><TextInput value={f.device} onChange={setE("device")} placeholder="เช่น iPhone 13 Pro" /></Field>
          )}
          <Field label="สีเครื่อง"><TextInput value={f.color} onChange={setE("color")} placeholder="เช่น ดำ, ทอง, ฟ้า" /></Field>
          <Field label="IMEI / Serial"><TextInput value={f.imei} onChange={setE("imei")} /></Field>
          <Field label="รหัสเครื่อง (ปลดล็อกหน้าจอ)"><TextInput value={f.code} onChange={setE("code")} placeholder="เช่น 1234 หรือ ไม่มีรหัส" /></Field>
          <Field label="งานซ่อม / อาการหลัก" req><TextInput value={f.issue} onChange={setE("issue")} placeholder="เช่น เปลี่ยนจอ" /></Field>
          <Field label="ช่างผู้รับผิดชอบ">
            <Select value={f.tech} onChange={(v) => setF((x) => ({ ...x, tech: v }))} placeholder="— เลือกช่าง —" options={techs.map((t) => ({ value: t.id, label: t.name }))} />
          </Field>
          <Field label="สิ่งที่รับมาด้วย (ติ๊กได้หลายข้อ)" style={{ gridColumn: "1/-1" }}>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
              {ACCESSORY_OPTIONS.map((acc) => {
                const on = f.accessories.includes(acc);
                return (
                  <label key={acc} className="ss-btn" style={{
                    display: "flex", alignItems: "center", gap: 6, cursor: "pointer",
                    border: `1.5px solid ${on ? T.primary : T.border}`, borderRadius: 999,
                    padding: "6px 13px", fontSize: 12.5, fontWeight: 700,
                    background: on ? T.infoBg : "#fff", color: on ? T.primary : T.sub,
                  }}>
                    <input type="checkbox" checked={on} style={{ display: "none" }}
                      onChange={() => setF((x) => ({ ...x, accessories: on ? x.accessories.filter((z) => z !== acc) : [...x.accessories, acc] }))} />
                    {on ? "✓ " : ""}{acc}
                  </label>
                );
              })}
            </div>
          </Field>
          <Field label="ค่าซ่อมประเมิน (บาท)"><NumInput value={f.est} onChange={setE("est")} /></Field>
          <Field label="มัดจำ (บาท)"><NumInput value={f.deposit} onChange={setE("deposit")} /></Field>
          <Field label="วันนัดรับ"><TextInput type="date" value={f.due} onChange={setE("due")} /></Field>
          <Field label="รูปถ่ายสภาพเครื่อง (เพิ่มได้หลายรูป)"><MultiImgUpload value={f.imgs} onChange={(v) => setF((x) => ({ ...x, imgs: v }))} size={52} hint="ถ่ายตำหนิ/สภาพก่อนรับซ่อม" onView={(i) => setLb({ imgs: f.imgs, index: i })} /></Field>
          <Field label="รายละเอียดอาการ" style={{ gridColumn: "1/-1" }}><TextArea value={f.symptom} onChange={setE("symptom")} placeholder="อาการโดยละเอียด ตำหนิเครื่อง ฯลฯ" /></Field>
        </div>
      </Modal>

      <PrintModal open={!!printRp} onClose={() => setPrintRp(null)} kind="repair" data={latestRp} />
      <PaymentModal open={!!payRp} onClose={() => setPayRp(null)} customer={payRp ? `${payRp.customer}${payRp.phone ? " · " + payRp.phone : ""}` : ""} items={payRp ? buildRepairSale(payRp.id).items : []} onSettle={(pay, disc) => { const id = payRp.id; dispatch({ type: "REPAIR_INVOICE", id, pay, discount: disc }); setPayRp(null); setReceiptRp(id); }} />
      <PrintModal open={!!receiptRp} onClose={() => setReceiptRp(null)} kind="sale" data={buildRepairSale(receiptRp)} />
      {lb && <Lightbox images={lb.imgs} index={lb.index} onClose={() => setLb(null)} onIndex={(i) => setLb((x) => ({ ...x, index: i }))} />}
    </div>
  );
}
window.RepairsPage = RepairsPage;
