// หน้าสาขา + หน้าพนักงาน & สิทธิ์
function BranchesPage({ user }) {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const [openId, setOpenId] = React.useState(null);
  const [f, setF] = React.useState({ name: "", short: "", addr: "", tel: "", taxId: "" });
  const canEdit = user.role === "owner";
  const colors = ["#3498DB", "#E74C3C", "#2ECC71", "#F39C12", "#9B59B6", "#1ABC9C"];

  return (
    <div>
      <SectionTitle right={canEdit && <Btn sm onClick={() => { setOpenId("NEW"); setF({ name: "", short: "", addr: "", tel: "", taxId: "" }); }}>⊕ เพิ่มสาขา</Btn>}>สาขาทั้งหมด ({st.branches.length})</SectionTitle>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(290px, 1fr))", gap: 13, marginTop: 6 }}>
        {st.branches.map((b, i) => (
          <Card key={b.id} hover onClick={() => canEdit && (setOpenId(b.id), setF({ name: b.name, short: b.short, addr: b.addr, tel: b.tel, taxId: b.taxId || "" }))} style={{ cursor: canEdit ? "pointer" : "default", border: `2.5px solid ${colors[i % colors.length]}`, textAlign: "center" }}>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 8, color: colors[i % colors.length] }}>{b.name} <span style={{ fontSize: 11, color: T.sub, fontWeight: 500 }}>({b.short})</span></div>
            <div style={{ fontSize: 12.5, color: T.sub, lineHeight: 1.7 }}>
              <div>📍 {b.addr}</div>
              <div>📞 {b.tel}</div>
              {b.taxId && <div style={{ marginTop: 3, fontSize: 11.5 }}>เลขผู้เสียภาษี {b.taxId}</div>}
            </div>
          </Card>
        ))}
      </div>
      <Modal open={openId != null} onClose={() => setOpenId(null)} title={openId === "NEW" ? "เพิ่มสาขาใหม่" : "แก้ไขสาขา"} width={520}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setOpenId(null)}>ยกเลิก</Btn>
          {openId === "NEW" ? (
            <Btn onClick={() => { if (!f.name || !f.short) { toast("กรอกชื่อและตัวย่อ", "danger"); return; } dispatch({ type: "BRANCH_ADD", branch: f }); toast("เพิ่มสาขาเรียบร้อย"); setOpenId(null); }}>บันทึก</Btn>
          ) : (
            <React.Fragment>
              <Btn kind="danger" onClick={() => { if (st.branches.length <= 1) { toast("ต้องมีอย่างน้อย 1 สาขา", "danger"); return; } if (confirm("ลบสาขานี้?")) { dispatch({ type: "BRANCH_DEL", id: openId }); toast("ลบสาขาเรียบร้อย", "info"); setOpenId(null); } }}>ลบสาขา</Btn>
              <Btn style={{ marginLeft: "auto" }} onClick={() => { dispatch({ type: "BRANCH_SET", id: openId, patch: f }); toast("บันทึกเรียบร้อย"); setOpenId(null); }}>บันทึก</Btn>
            </React.Fragment>
          )}
        </React.Fragment>}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="ชื่อสาขา" req><TextInput value={f.name} onChange={(e) => setF((x) => ({ ...x, name: e.target.value }))} /></Field>
          <Field label="ตัวย่อ" req><TextInput value={f.short} onChange={(e) => setF((x) => ({ ...x, short: e.target.value }))} placeholder="เช่น B1" /></Field>
          <Field label="ที่อยู่" req style={{ gridColumn: "1/-1" }}><TextInput value={f.addr} onChange={(e) => setF((x) => ({ ...x, addr: e.target.value }))} /></Field>
          <Field label="เบอร์โทร" req><TextInput value={f.tel} onChange={(e) => setF((x) => ({ ...x, tel: e.target.value }))} /></Field>
          <Field label="เลขประจำตัวผู้เสียภาษี"><TextInput value={f.taxId} onChange={(e) => setF((x) => ({ ...x, taxId: e.target.value }))} /></Field>
        </div>
      </Modal>
    </div>
  );
}

function pwOk(s) { return /^[A-Za-z0-9]{8,}$/.test(s || ""); }

function StaffPage({ user }) {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const [openId, setOpenId] = React.useState(null);
  const [f, setF] = React.useState(null);
  const isOwner = user.role === "owner";

  // ทุกเมนู/ฟีเจอร์ที่กำหนดสิทธิ์ได้ (ตรงกับ NAV) — settings เป็นของเจ้าของร้านเท่านั้น
  const PAGE_PERMS = [
    ["dashboard", "แดชบอร์ด"], ["income", "รายรับรายวัน"], ["pos", "ขาย (POS)"], ["buyin", "รับซื้อ/เทิร์น"],
    ["pawns", "จำนำ"], ["repairs", "งานซ่อม"], ["stock", "สต็อกสินค้า"], ["parts", "สต็อกอะไหล่"],
    ["locations", "คลัง & Location"], ["reports", "รายงาน"], ["branches", "สาขา"], ["staff", "พนักงาน & สิทธิ์"],
  ];
  const STOCK_OPTS = [
    { value: "all", label: "ทุกสาขา (รวมอะไหล่)" }, { value: "all-no-parts", label: "ทุกสาขา (ไม่รวมอะไหล่)" },
    { value: "own", label: "เฉพาะสาขาตน" }, { value: "own-no-parts", label: "สาขาตน (ไม่รวมอะไหล่)" }, { value: "none", label: "ไม่มีสิทธิ์" },
  ];
  const PARTS_OPTS = [{ value: "all", label: "ทุกสาขา" }, { value: "own", label: "เฉพาะสาขาตน" }, { value: "none", label: "ไม่มีสิทธิ์" }];

  const togglePage = (rk, pg) => {
    const role = st.roles[rk];
    const has = role.pages.includes(pg);
    const order = PAGE_PERMS.map((p) => p[0]).concat(["settings"]);
    const next = has ? role.pages.filter((p) => p !== pg) : [...role.pages, pg].sort((a, b) => order.indexOf(a) - order.indexOf(b));
    dispatch({ type: "ROLE_PAGES_SET", role: rk, pages: next });
    toast(`${has ? "ปิด" : "เปิด"}สิทธิ์ “${PAGE_PERMS.find((p) => p[0] === pg)?.[1] || pg}” · ${role.label}`, "info");
  };
  const setPerm = (rk, perm, value) => dispatch({ type: "ROLE_PERM_SET", role: rk, perm, value });

  // ปุ่มเปิด/ปิดในตาราง
  const PermCell = ({ on, locked, onClick }) => (
    <span onClick={locked ? undefined : onClick} className={locked ? "" : "ss-btn"} style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center", width: 26, height: 26, borderRadius: 8,
      fontWeight: 800, fontSize: 14, cursor: locked ? "default" : "pointer",
      background: on ? T.okBg : (locked ? "transparent" : T.chipBg),
      color: on ? T.okFg : "#C4CDE0", border: locked ? "none" : `1px solid ${on ? "#B6E6CC" : T.border}`,
    }}>{on ? "✓" : (locked ? "—" : "")}</span>
  );

  const openEdit = (u) => { setOpenId(u.id); setF({ ...u }); };
  const openNew = () => { setOpenId("NEW"); setF({ name: "", role: "sales", branch: st.branches[0]?.id || "B1", username: "", password: "", img: null }); };

  const save = () => {
    if (!f.name) { toast("กรอกชื่อพนักงาน", "danger"); return; }
    if (!f.username) { toast("กรอกชื่อผู้ใช้ (User)", "danger"); return; }
    if (usernameTaken(st, f.username, openId === "NEW" ? null : openId)) { toast("ชื่อผู้ใช้นี้ถูกใช้แล้ว", "danger"); return; }
    if (!pwOk(f.password)) { toast("รหัสต้องเป็นอังกฤษ+ตัวเลข อย่างน้อย 8 หลัก", "danger"); return; }
    if (passwordTaken(st, f.password, openId === "NEW" ? null : openId)) { toast("รหัสนี้ถูกใช้แล้ว — ใช้รหัสอื่น", "danger"); return; }
    if (openId === "NEW") { dispatch({ type: "USER_ADD", user: f }); toast("เพิ่มพนักงานเรียบร้อย"); }
    else { dispatch({ type: "USER_SET", id: openId, patch: f }); toast("บันทึกเรียบร้อย"); }
    setOpenId(null);
  };

  return (
    <div>
      <SectionTitle right={isOwner && <Btn sm onClick={openNew}>⊕ เพิ่มพนักงาน</Btn>}>พนักงาน & สิทธิ์</SectionTitle>

      {/* ── ตารางสิทธิ์การเข้าเมนู (แก้ไขได้) ── */}
      {isOwner && (
        <Card style={{ marginBottom: 16, overflowX: "auto" }}>
          <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 15, marginBottom: 4 }}>สิทธิ์การเข้าถึงเมนู</div>
          <div style={{ fontSize: 11.5, color: T.sub, marginBottom: 12 }}>คลิกช่องเพื่อเปิด/ปิดเมนูของแต่ละบทบาท · เจ้าของร้านเข้าถึงทุกเมนูถาวร</div>
          <table style={{ borderCollapse: "collapse", fontSize: 12.5, minWidth: "100%" }}>
            <thead>
              <tr style={{ background: T.chipBg }}>
                <th style={{ textAlign: "left", padding: "10px 12px", fontWeight: 700, borderRadius: "8px 0 0 8px", position: "sticky", left: 0, background: T.chipBg, whiteSpace: "nowrap" }}>บทบาท</th>
                {PAGE_PERMS.map((p, i) => <th key={p[0]} style={{ textAlign: "center", padding: "10px 10px", fontWeight: 700, whiteSpace: "nowrap", borderRadius: i === PAGE_PERMS.length - 1 ? "0 8px 8px 0" : 0 }}>{p[1]}</th>)}
              </tr>
            </thead>
            <tbody>
              {Object.entries(st.roles).map(([rk, role]) => {
                const locked = rk === "owner";
                return (
                  <tr key={rk} style={{ borderBottom: `1px solid ${T.rowBorder}` }}>
                    <td style={{ padding: "11px 12px", fontWeight: 700, position: "sticky", left: 0, background: T.surface, whiteSpace: "nowrap" }}>{role.label}{role.allBranch && <span style={{ fontSize: 10.5, color: T.sub, fontWeight: 500 }}> · ทุกสาขา</span>}</td>
                    {PAGE_PERMS.map(([pg]) => {
                      const on = locked ? true : role.pages.includes(pg);
                      return (
                        <td key={pg} style={{ textAlign: "center", padding: "9px 10px" }}>
                          <PermCell on={on} locked={locked} onClick={() => togglePage(rk, pg)} />
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      )}

      {/* ── ขอบเขตข้อมูล (แก้ไขได้) ── */}
      {isOwner && (
        <Card style={{ marginBottom: 16, overflowX: "auto" }}>
          <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 15, marginBottom: 4 }}>ขอบเขตข้อมูล & สิทธิ์พิเศษ</div>
          <div style={{ fontSize: 11.5, color: T.sub, marginBottom: 12 }}>กำหนดว่าแต่ละบทบาทเห็นข้อมูลข้ามสาขาได้แค่ไหน และเห็นยอดเงินบนแดชบอร์ดหรือไม่</div>
          <table style={{ borderCollapse: "collapse", fontSize: 12.5, minWidth: "100%" }}>
            <thead>
              <tr style={{ background: T.chipBg }}>
                <th style={{ textAlign: "left", padding: "10px 12px", fontWeight: 700, borderRadius: "8px 0 0 8px", whiteSpace: "nowrap" }}>บทบาท</th>
                <th style={{ textAlign: "center", padding: "10px 12px", fontWeight: 700, whiteSpace: "nowrap" }}>เห็นทุกสาขา</th>
                <th style={{ textAlign: "center", padding: "10px 12px", fontWeight: 700, whiteSpace: "nowrap" }}>ยอดเงินแดชบอร์ด</th>
                <th style={{ textAlign: "left", padding: "10px 12px", fontWeight: 700, whiteSpace: "nowrap" }}>ขอบเขตสต็อกสินค้า</th>
                <th style={{ textAlign: "left", padding: "10px 12px", fontWeight: 700, borderRadius: "0 8px 8px 0", whiteSpace: "nowrap" }}>ขอบเขตอะไหล่</th>
              </tr>
            </thead>
            <tbody>
              {Object.entries(st.roles).map(([rk, role]) => {
                const locked = rk === "owner";
                return (
                  <tr key={rk} style={{ borderBottom: `1px solid ${T.rowBorder}` }}>
                    <td style={{ padding: "11px 12px", fontWeight: 700, whiteSpace: "nowrap" }}>{role.label}</td>
                    <td style={{ textAlign: "center", padding: "9px 12px" }}>
                      <PermCell on={locked ? true : !!role.allBranch} locked={locked} onClick={() => setPerm(rk, "allBranch", !role.allBranch)} />
                    </td>
                    <td style={{ textAlign: "center", padding: "9px 12px" }}>
                      <PermCell on={locked ? true : !!role.dashboardAccess} locked={locked} onClick={() => setPerm(rk, "dashboardAccess", !role.dashboardAccess)} />
                    </td>
                    <td style={{ padding: "8px 12px" }}>
                      {locked ? <span style={{ color: T.sub }}>ทุกสาขา (รวมอะไหล่)</span>
                        : <Select value={role.stockAccess} onChange={(v) => setPerm(rk, "stockAccess", v)} options={STOCK_OPTS} style={{ minWidth: 200, padding: "7px 10px" }} />}
                    </td>
                    <td style={{ padding: "8px 12px" }}>
                      {locked ? <span style={{ color: T.sub }}>ทุกสาขา</span>
                        : <Select value={role.partsAccess} onChange={(v) => setPerm(rk, "partsAccess", v)} options={PARTS_OPTS} style={{ minWidth: 140, padding: "7px 10px" }} />}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      )}

      {/* ── การ์ดพนักงาน ── */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 12 }}>
        {st.users.map((x) => (
          <Card key={x.id} hover onClick={() => isOwner ? openEdit(x) : null} style={{ cursor: isOwner ? "pointer" : "default" }}>
            <div style={{ display: "flex", gap: 13, alignItems: "center" }}>
              <Avatar name={x.name} img={x.img} size={50} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{x.name}</div>
                <div style={{ fontSize: 11.5, color: T.sub }}>{st.roles[x.role]?.label} · {branchOf(st, x.branch).short}</div>
                <div style={{ fontSize: 11.5, color: T.primary, marginTop: 3, fontWeight: 600 }}>@{x.username}</div>
              </div>
              {isOwner && <span style={{ color: T.sub, fontSize: 16 }}>›</span>}
            </div>
          </Card>
        ))}
      </div>

      {/* ── modal เพิ่ม/แก้ไขพนักงาน ── */}
      <Modal open={openId != null} onClose={() => setOpenId(null)} title={openId === "NEW" ? "เพิ่มพนักงานใหม่" : "แก้ไขพนักงาน"} width={520}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setOpenId(null)}>ยกเลิก</Btn>
          {openId !== "NEW" && <Btn kind="danger" onClick={() => { if (openId === user.id) { toast("ลบบัญชีตัวเองไม่ได้", "danger"); return; } if (confirm("ลบพนักงานคนนี้?")) { dispatch({ type: "USER_DEL", id: openId }); toast("ลบเรียบร้อย", "info"); setOpenId(null); } }}>ลบ</Btn>}
          <Btn style={{ marginLeft: "auto" }} onClick={save}>บันทึก</Btn>
        </React.Fragment>}>
        {f && (
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            <div style={{ display: "flex", justifyContent: "center" }}>
              <ImgUpload shape="circle" size={90} value={f.img} onChange={(v) => setF((x) => ({ ...x, img: v }))} hint="รูปโปรไฟล์" />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="ชื่อ-นามสกุล" req><TextInput value={f.name} onChange={(e) => setF((x) => ({ ...x, name: e.target.value }))} /></Field>
              <Field label="ระดับผู้ใช้"><Select value={f.role} onChange={(v) => setF((x) => ({ ...x, role: v }))} options={Object.entries(st.roles).map(([k, r]) => ({ value: k, label: r.label }))} /></Field>
              <Field label="ประจำสาขา"><Select value={f.branch} onChange={(v) => setF((x) => ({ ...x, branch: v }))} options={st.branches.map((b) => ({ value: b.id, label: b.name }))} /></Field>
            </div>
            <div style={{ borderTop: `1px solid ${T.border}`, paddingTop: 13 }}>
              <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 14, marginBottom: 10 }}>บัญชีเข้าระบบ</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="ชื่อผู้ใช้ (User)" req><TextInput value={f.username} onChange={(e) => setF((x) => ({ ...x, username: e.target.value }))} placeholder="เช่น somchai" /></Field>
                <Field label="รหัสผ่าน (อังกฤษ+เลข ≥8 หลัก)" req><TextInput value={f.password} onChange={(e) => setF((x) => ({ ...x, password: e.target.value }))} placeholder="ตั้งรหัสใหม่" /></Field>
              </div>
              <div style={{ fontSize: 11.5, color: T.sub, marginTop: 8 }}>* รหัสของแต่ละคนต้องไม่ซ้ำกัน เจ้าของร้านเป็นผู้ตั้ง/แก้ไขรหัส</div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

Object.assign(window, { BranchesPage, StaffPage });