// Users & Groups + Settings

const PERM_LABELS = {
  view_all: "ดูข้อมูลทั้งหมด",
  view_own: "ดูเฉพาะของตน",
  create: "สร้างรายการ",
  edit_own: "แก้ไขของตน",
  edit_all: "แก้ไขทั้งหมด",
  attach_po: "Attach PO",
  approve: "อนุมัติ",
  manage_master: "จัดการ Master Data",
  manage_users: "จัดการผู้ใช้",
  setup_groups: "ตั้งค่ากลุ่ม",
};

// ─── Confirm dialog ──────────────────────────────────────────────
function ConfirmModal({ title, message, confirmLabel = "ยืนยัน", confirmStyle = "btn--danger", onConfirm, onClose }) {
  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(11,21,49,0.45)", display: "grid",
                  placeItems: "center", zIndex: 200 }} onClick={onClose}>
      <div className="card" style={{ width: 420, maxWidth: "92vw", boxShadow: "var(--shadow-pop)" }}
           onClick={e => e.stopPropagation()}>
        <div className="card__header">
          <h3 className="card__title">{title}</h3>
          <button className="btn btn--ghost btn--sm" onClick={onClose}><Icon name="x" size={14}/></button>
        </div>
        <div className="card__body">
          <p style={{ margin: 0, color: "var(--text-muted)", fontSize: 14, lineHeight: 1.6 }}>{message}</p>
        </div>
        <div style={{ padding: "14px 18px", borderTop: "1px solid var(--border)", display: "flex",
                      justifyContent: "flex-end", gap: 8 }}>
          <button className="btn" onClick={onClose}>ยกเลิก</button>
          <button className={"btn " + confirmStyle} onClick={() => { onConfirm(); onClose(); }}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

// ─── Main component ──────────────────────────────────────────────
function UsersAndGroups({ ctx }) {
  // State lives in App so it survives screen navigation
  const { appUsers: users, setAppUsers: setUsers, appGroups: groups, setAppGroups: setGroups } = ctx;

  const [tab, setTab]                   = React.useState("users");
  const [statusFilter, setStatusFilter] = React.useState("active");
  const [editingUser, setEditingUser]   = React.useState(null);
  const [editingGroup, setEditingGroup] = React.useState(null);
  const [confirm, setConfirm]           = React.useState(null);
  const [inviteResult, setInviteResult] = React.useState(null); // { email, sent, error }

  // ── Filtered lists (sort inactive to the bottom in "All" view)
  const visibleUsers = (
    statusFilter === "active"
      ? users.filter(u => u.status !== "inactive")
      : users
  ).slice().sort((a, b) => (a.status === "inactive") - (b.status === "inactive"));

  const visibleGroups = (
    statusFilter === "active"
      ? groups.filter(g => g.status !== "inactive")
      : groups
  ).slice().sort((a, b) => (a.status === "inactive") - (b.status === "inactive"));

  // ── User actions (update local state + sync Supabase)
  const toggleUserStatus = (u) => {
    const next = u.status === "inactive" ? "active" : "inactive";
    setUsers(users.map(x => x.id === u.id ? { ...x, status: next } : x));
    if (window.sb) {
      window.sb.from('profiles').update({ status: next }).eq('id', u.id)
        .then(({ error }) => { if (error) console.warn('Status update failed (no status column yet?):', error.message); });
    }
  };

  const saveUser = async (u) => {
    if (u.isNew) {
      // Single-call invite — REQUIRES "Confirm email" OFF in Supabase Auth settings.
      // With confirmation disabled, signInWithOtp sends the Magic Link template
      // (which creates a session on click), NOT the Confirm Signup template
      // (which does not). The handle_new_user trigger creates the profile with
      // password_set=false → SetPasswordScreen appears after click.
      if (!u.email || u.email === "—") {
        alert('กรุณากรอก Email ก่อนบันทึก');
        return;
      }
      setEditingUser(null);

      const emailLower = u.email.trim();

      const { error } = await window.sb.auth.signInWithOtp({
        email: emailLower,
        options: {
          shouldCreateUser: true,
          emailRedirectTo:  window.location.origin,
          data: {
            name:       u.name  || emailLower.split('@')[0],
            role:       u.role  || 'User',
            title:      u.title || '',
            group_name: u.group || 'Sales BKK',
          },
        },
      });

      const errMsg = error
        ? (error.message || error.error_description || JSON.stringify(error))
        : null;

      // Optimistic UI update (real row arrives via reload below)
      const optimistic = { ...u, id: 'pending-' + Date.now(), isNew: undefined, lastLogin: '—', status: 'active' };
      setUsers(prev => [...prev, optimistic]);

      setInviteResult({ email: u.email, sent: !error, error: errMsg });

      if (!error) {
        setTimeout(async () => {
          const { data } = await window.sb.from('profiles').select('*').order('created_at', { ascending: true });
          if (data) setUsers(data.map(window.rowToUser));
        }, 2500);
      }
    } else {
      setUsers(users.map(x => x.id === u.id ? u : x));
      if (window.sb) {
        window.sb.from('profiles').update(window.userToRow(u)).eq('id', u.id)
          .then(({ error }) => { if (error) console.warn('Save user failed:', error.message); });
      }
      setEditingUser(null);
    }
  };

  // NOTE: permanent user delete removed by design — use Disable instead.
  //       Deleting auth.users requires service_role key (server-only); soft-disable
  //       preserves transaction history and is safer.

  // ── Group actions
  const toggleGroupStatus = (g) => {
    const next = g.status === "inactive" ? "active" : "inactive";
    setGroups(groups.map(x => x.name === g.name ? { ...x, status: next } : x));
  };

  const saveGroup = (g) => {
    if (g.isNew) setGroups([...groups, { ...g, users: 0, isNew: undefined, status: "active" }]);
    else setGroups(groups.map(x => x.name === g.name ? g : x));
    setEditingGroup(null);
  };

  const deleteGroup = (g) => {
    // Remove the group
    setGroups(groups.filter(x => x.name !== g.name));
    // Auto-clear any users who were in this group
    const remaining = groups.filter(x => x.name !== g.name && x.status !== "inactive");
    const fallback  = remaining.length > 0 ? remaining[0].name : "—";
    setUsers(users.map(u => u.group === g.name ? { ...u, group: fallback } : u));
  };

  const activeCount   = users.filter(u => u.status !== "inactive").length;
  const inactiveCount = users.filter(u => u.status === "inactive").length;
  const activeGCount  = groups.filter(g => g.status !== "inactive").length;

  return (
    <div className="page">
      <div className="page__header">
        <div>
          <h1 className="page__title">Users & Groups</h1>
          <p className="page__sub">จัดการผู้ใช้และสิทธิ์ตามกลุ่ม — ปิดใช้งานผู้ใช้โดยไม่ลบประวัติธุรกรรม</p>
        </div>
        <div className="page__actions">
          {tab === "users"  && <button className="btn btn--primary" onClick={() => setEditingUser({ name: "", email: "", role: "User", group: "Sales BKK", status: "active", isNew: true })}><Icon name="plus" size={14}/> เพิ่มผู้ใช้</button>}
          {tab === "groups" && <button className="btn btn--primary" onClick={() => setEditingGroup({ name: "", perms: [], status: "active", isNew: true })}><Icon name="plus" size={14}/> สร้างกลุ่มใหม่</button>}
        </div>
      </div>

      {/* Tab + status filter */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div className="filter-row" style={{ borderBottom: 0 }}>
          <button className={"chip " + (tab === "users"  ? "is-active" : "")} onClick={() => setTab("users")}>
            Users <span className="count">{users.length}</span>
          </button>
          <button className={"chip " + (tab === "groups" ? "is-active" : "")} onClick={() => setTab("groups")}>
            Groups <span className="count">{groups.length}</span>
          </button>
          <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
            <button className={"chip " + (statusFilter === "active" ? "is-active" : "")}
                    onClick={() => setStatusFilter("active")}>
              Active <span className="count">{tab === "users" ? activeCount : activeGCount}</span>
            </button>
            <button className={"chip " + (statusFilter === "all" ? "is-active" : "")}
                    onClick={() => setStatusFilter("all")}>
              All {inactiveCount > 0 && <span className="count" style={{ background: "var(--text-muted)" }}>{tab === "users" ? users.length : groups.length}</span>}
            </button>
          </div>
        </div>
      </div>

      {/* ── Users table ── */}
      {tab === "users" && (
        <div className="card">
          <table className="table">
            <thead>
              <tr>
                <th>User</th>
                <th>Username</th>
                <th>Email</th>
                <th>Role</th>
                <th>Group</th>
                <th>Last login</th>
                <th>Status</th>
                <th style={{ width: 120 }}></th>
              </tr>
            </thead>
            <tbody>
              {visibleUsers.length === 0 && (
                <tr><td colSpan="8" style={{ textAlign: "center", padding: 32, color: "var(--text-muted)" }}>ไม่มีผู้ใช้ในรายการ</td></tr>
              )}
              {visibleUsers.map(u => {
                const inactive = u.status === "inactive";
                return (
                  <tr key={u.id} style={{ opacity: inactive ? 0.55 : 1 }}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <div className="avatar" style={{ background: inactive ? "var(--text-muted)" : avatarColor(u.name) }}>
                          {u.name.split(" ").map(p => p[0]).slice(0, 2).join("")}
                        </div>
                        <strong style={{ textDecoration: inactive ? "line-through" : "none" }}>{u.name}</strong>
                      </div>
                    </td>
                    <td><span className="mono small" style={{ color: "var(--text-body)" }}>{u.username || <span className="muted">—</span>}</span></td>
                    <td className="muted">{u.email}</td>
                    <td>
                      <span className={"badge " + (u.role === "Admin" ? "badge--solid" : u.role === "Manager" ? "badge--info" : "badge--active")}>
                        {u.role}
                      </span>
                    </td>
                    <td>{u.group}</td>
                    <td className="small">{u.lastLogin || "—"}</td>
                    <td>
                      {inactive
                        ? <span className="badge badge--draft">Inactive</span>
                        : <span className="badge badge--active">Active</span>}
                    </td>
                    <td>
                      <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                        {/* Edit */}
                        <button className="btn btn--ghost btn--sm" title="แก้ไข"
                                onClick={() => setEditingUser(u)}>
                          <Icon name="edit" size={13}/>
                        </button>
                        {/* Disable / Enable */}
                        <button className={"btn btn--ghost btn--sm"}
                                title={inactive ? "เปิดใช้งาน" : "ปิดใช้งาน"}
                                style={{ color: inactive ? "var(--green-600)" : "var(--text-muted)" }}
                                onClick={() => {
                                  if (inactive) {
                                    toggleUserStatus(u);
                                  } else {
                                    setConfirm({ type: "disableUser", payload: u });
                                  }
                                }}>
                          <Icon name={inactive ? "check" : "x"} size={13}/>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {inactiveCount > 0 && statusFilter === "active" && (
            <div style={{ padding: "10px 18px", borderTop: "1px solid var(--border)", fontSize: 13, color: "var(--text-muted)", display: "flex", alignItems: "center", gap: 6 }}>
              <Icon name="x" size={12}/> {inactiveCount} ผู้ใช้ถูกปิดใช้งาน —
              <button className="btn btn--ghost btn--sm" style={{ padding: "2px 8px" }}
                      onClick={() => setStatusFilter("all")}>ดูทั้งหมด</button>
            </div>
          )}
        </div>
      )}

      {/* ── Groups grid ── */}
      {tab === "groups" && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(360px, 1fr))", gap: 14 }}>
          {visibleGroups.length === 0 && (
            <div style={{ padding: 32, color: "var(--text-muted)", gridColumn: "span 2", textAlign: "center" }}>ไม่มีกลุ่มในรายการ</div>
          )}
          {visibleGroups.map(g => {
            const inactive = g.status === "inactive";
            return (
              <div key={g.name} className="card" style={{ opacity: inactive ? 0.6 : 1 }}>
                <div className="card__header">
                  <div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <h3 className="card__title" style={{ textDecoration: inactive ? "line-through" : "none" }}>{g.name}</h3>
                      {inactive && <span className="badge badge--draft" style={{ fontSize: 11 }}>Inactive</span>}
                    </div>
                    <p className="card__sub">{g.users || 0} ผู้ใช้</p>
                  </div>
                  <div style={{ display: "flex", gap: 4 }}>
                    <button className="btn btn--ghost btn--sm" title="แก้ไข"
                            onClick={() => setEditingGroup(g)}>
                      <Icon name="edit" size={13}/>
                    </button>
                    <button className="btn btn--ghost btn--sm"
                            title={inactive ? "เปิดใช้งาน" : "ปิดใช้งาน"}
                            style={{ color: inactive ? "var(--green-600)" : "var(--text-muted)" }}
                            onClick={() => {
                              if (inactive) {
                                toggleGroupStatus(g);
                              } else {
                                setConfirm({ type: "disableGroup", payload: g });
                              }
                            }}>
                      <Icon name={inactive ? "check" : "x"} size={13}/>
                    </button>
                    <button className="btn btn--ghost btn--sm" title="ลบกลุ่ม"
                            style={{ color: "var(--red-500, #e11d48)" }}
                            onClick={() => setConfirm({ type: "deleteGroup", payload: g })}>
                      <Icon name="trash" size={13}/>
                    </button>
                  </div>
                </div>
                <div className="card__body">
                  <h4 className="section-h" style={{ margin: 0, marginBottom: 10 }}>Permissions</h4>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                    {(g.perms || []).map(p => <span key={p} className="perm-chip">{p}</span>)}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* ── Modals ── */}
      {editingUser && (
        <EditUserModal
          user={editingUser}
          groups={groups.filter(g => g.status !== "inactive")}
          onClose={() => setEditingUser(null)}
          onSave={saveUser}
        />
      )}

      {editingGroup && (
        <EditGroupModal
          group={editingGroup}
          onClose={() => setEditingGroup(null)}
          onSave={saveGroup}
        />
      )}

      {/* ── Confirm dialogs ── */}
      {confirm?.type === "disableUser" && (
        <ConfirmModal
          title="ปิดใช้งานผู้ใช้"
          message={`ปิดใช้งาน "${confirm.payload.name}" — ผู้ใช้จะไม่สามารถเข้าสู่ระบบได้ แต่ประวัติธุรกรรมทั้งหมดที่เคยสร้างจะยังคงแสดงอยู่ในระบบ`}
          confirmLabel="ปิดใช้งาน"
          confirmStyle="btn--primary"
          onConfirm={() => toggleUserStatus(confirm.payload)}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm?.type === "disableGroup" && (
        <ConfirmModal
          title="ปิดใช้งานกลุ่ม"
          message={`ปิดใช้งานกลุ่ม "${confirm.payload.name}" — ผู้ใช้ในกลุ่มนี้จะไม่ได้รับสิทธิ์ตามกลุ่มนี้อีกต่อไป`}
          confirmLabel="ปิดใช้งาน"
          confirmStyle="btn--primary"
          onConfirm={() => toggleGroupStatus(confirm.payload)}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm?.type === "deleteGroup" && (
        <ConfirmModal
          title="ลบกลุ่ม"
          message={`ลบกลุ่ม "${confirm.payload.name}" ถาวร — ผู้ใช้ในกลุ่มนี้จะถูกย้ายไปกลุ่มถัดไปอัตโนมัติ`}
          confirmLabel="ลบถาวร"
          confirmStyle="btn--danger"
          onConfirm={() => deleteGroup(confirm.payload)}
          onClose={() => setConfirm(null)}
        />
      )}

      {/* ── Invite modal (shown after creating a new user) ── */}
      {inviteResult && (
        <InviteModal
          email={inviteResult.email}
          sent={inviteResult.sent}
          error={inviteResult.error}
          onResend={async () => {
            // Resend the magic link (user already exists at this point)
            const { error } = await window.sb.auth.signInWithOtp({
              email: inviteResult.email,
              options: { shouldCreateUser: false, emailRedirectTo: window.location.origin },
            });
            const errMsg = error
              ? (error.message || error.error_description || JSON.stringify(error))
              : null;
            setInviteResult({ ...inviteResult, sent: !error, error: errMsg });
          }}
          onClose={() => setInviteResult(null)}
        />
      )}
    </div>
  );
}

// ─── Edit User Modal ──────────────────────────────────────────────
function EditUserModal({ user, groups, onClose, onSave }) {
  const validGroup = groups.find(g => g.name === user.group) ? user.group : (groups[0]?.name || "—");
  const [form, setForm] = React.useState({ ...user, group: validGroup });

  return (
    <Modal onClose={onClose} title={user.isNew ? "เพิ่มผู้ใช้" : "แก้ไขผู้ใช้"} onSave={() => onSave(form)}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <UField label="ชื่อ-นามสกุล">
          <input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })}
                 placeholder="ชื่อ-นามสกุลผู้ใช้"/>
        </UField>
        <UField label="Title / ตำแหน่ง">
          <input className="input" value={form.title || ""} onChange={e => setForm({ ...form, title: e.target.value })}
                 placeholder="เช่น Sales, Engineer"/>
        </UField>
      </div>
      <UField label="Email (ใช้ Login และรับ Magic Link)">
        <input className="input" type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })}
               placeholder="user@journey-tech.co.th"/>
      </UField>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <UField label="Role">
          <select className="input" value={form.role} onChange={e => setForm({ ...form, role: e.target.value })}>
            <option>Admin</option>
            <option>Manager</option>
            <option>User</option>
          </select>
        </UField>
        <UField label="Group">
          <select className="input" value={form.group} onChange={e => setForm({ ...form, group: e.target.value })}>
            {groups.map(g => <option key={g.name}>{g.name}</option>)}
            {groups.length === 0 && <option value="—">— (ไม่มีกลุ่ม)</option>}
          </select>
        </UField>
      </div>
    </Modal>
  );
}

// ─── Edit Group Modal ─────────────────────────────────────────────
function EditGroupModal({ group, onClose, onSave }) {
  const [form, setForm] = React.useState(group);
  const allPerms = Object.keys(PERM_LABELS);
  const togglePerm = (p) => {
    const perms = form.perms.includes(p) ? form.perms.filter(x => x !== p) : [...form.perms, p];
    setForm({ ...form, perms });
  };
  return (
    <Modal onClose={onClose} title={group.isNew ? "สร้างกลุ่มใหม่" : "แก้ไขกลุ่ม"} onSave={() => onSave(form)} width={560}>
      <UField label="Group name">
        <input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })}/>
      </UField>
      <div className="field">
        <label>Permissions</label>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 6 }}>
          {allPerms.map(p => (
            <label key={p} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px",
                                    border: "1px solid var(--border)", borderRadius: 8, cursor: "pointer",
                                    background: form.perms.includes(p) ? "var(--jt-navy-50)" : "var(--surface)" }}>
              <input type="checkbox" checked={form.perms.includes(p)} onChange={() => togglePerm(p)}/>
              <div>
                <div className="mono small">{p}</div>
                <div className="muted small">{PERM_LABELS[p]}</div>
              </div>
            </label>
          ))}
        </div>
      </div>
    </Modal>
  );
}

// ─── Helpers ──────────────────────────────────────────────────────
function UField({ label, children }) {
  return (<div className="field"><label>{label}</label>{children}</div>);
}

function Modal({ title, children, onClose, onSave, width = 460 }) {
  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(11,21,49,0.4)", display: "grid",
                  placeItems: "center", zIndex: 100 }} onClick={onClose}>
      <div className="card" style={{ width, maxWidth: "92vw", boxShadow: "var(--shadow-pop)" }}
           onClick={e => e.stopPropagation()}>
        <div className="card__header">
          <h3 className="card__title">{title}</h3>
          <button className="btn btn--ghost btn--sm" onClick={onClose}><Icon name="x" size={14}/></button>
        </div>
        <div className="card__body" style={{ display: "grid", gap: 12 }}>{children}</div>
        <div style={{ padding: "14px 18px", borderTop: "1px solid var(--border)",
                      display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn" onClick={onClose}>ยกเลิก</button>
          <button className="btn btn--primary" onClick={onSave}><Icon name="check" size={14}/> บันทึก</button>
        </div>
      </div>
    </div>
  );
}

function avatarColor(name) {
  const palette = ["#0f2a6b","#1a3a8f","#2851b3","#16a34a","#d97706","#7c3aed","#0d9488","#e11d48"];
  let h = 0;
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
  return palette[h % palette.length];
}

// ─── Settings ────────────────────────────────────────────────────
function Settings({ ctx }) {
  return (
    <div className="page" style={{ maxWidth: 880 }}>
      <div className="page__header">
        <div>
          <h1 className="page__title">Settings</h1>
          <p className="page__sub">การตั้งค่าระบบ ARS Service Management</p>
        </div>
      </div>
      <div style={{ display: "grid", gap: 16 }}>
        <div className="card">
          <div className="card__header"><h3 className="card__title">Company Information</h3></div>
          <div className="card__body" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <SField label="Company name"><input className="input" defaultValue="Journey Tech Co., Ltd."/></SField>
            <SField label="Tax ID"><input className="input mono" defaultValue="0125564021847"/></SField>
            <div style={{ gridColumn: "span 2" }}>
              <SField label="Address"><input className="input" defaultValue="98/369 Moo 10 Bangmaenang Bangyai Nonthaburi 11140"/></SField>
            </div>
            <SField label="Phone"><input className="input mono" defaultValue="065-259-1661"/></SField>
            <SField label="Email"><input className="input" defaultValue="sales@journey-tech.co.th"/></SField>
          </div>
        </div>
        <div className="card">
          <div className="card__header"><h3 className="card__title">Certificate Template</h3></div>
          <div className="card__body">
            <div className="spread"><span>Helpdesk Phone</span><input className="input mono" style={{maxWidth:200}} defaultValue="02-001-4902"/></div>
            <div className="divider"></div>
            <div className="spread"><span>Helpdesk Email</span><input className="input" style={{maxWidth:300}} defaultValue="support@helpdesk.in.th"/></div>
            <div className="divider"></div>
            <div className="spread"><span>Service hours (Mon–Fri)</span><input className="input" style={{maxWidth:200}} defaultValue="9.00 – 17.00"/></div>
            <div className="divider"></div>
            <div className="spread"><span>Service hours (Sat–Sun)</span><input className="input" style={{maxWidth:200}} defaultValue="10.00 – 15.00"/></div>
            <div className="divider"></div>
            <div className="spread"><span>24×7 Support</span>
              <label style={{ display:"inline-flex", alignItems:"center", gap:8 }}>
                <input type="checkbox" defaultChecked/><span>เปิด</span>
              </label>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="card__header"><h3 className="card__title">Notifications</h3></div>
          <div className="card__body">
            <NotifRow label="แจ้งเตือนเมื่อมีคำขอรอ approve" checked />
            <NotifRow label="แจ้งเตือนเมื่อ Certificate ถูกออก" checked />
            <NotifRow label="แจ้งเตือนเมื่อ warranty จะหมดอายุภายใน 90 วัน" checked />
            <NotifRow label="ส่งรายงานสรุปรายเดือนทาง email" />
          </div>
        </div>
        <div className="card">
          <div className="card__header"><h3 className="card__title">Integration</h3></div>
          <div className="card__body" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
            <IntegrationCard name="ERP — SAP B1" status="connected" desc="Sync PO และ Article master"/>
            <IntegrationCard name="LINE Official @journeytech" status="connected" desc="ส่ง Certificate ให้ลูกค้า"/>
            <IntegrationCard name="Email — sales@journey-tech.co.th" status="connected" desc="ส่ง PDF Certificate"/>
            <IntegrationCard name="QNAP Partner Portal" status="disconnected" desc="ดึงข้อมูล warranty package"/>
          </div>
        </div>
      </div>
    </div>
  );
}

function SField({ label, children }) {
  return (<div className="field"><label>{label}</label>{children}</div>);
}
function NotifRow({ label, checked }) {
  const [on, setOn] = React.useState(!!checked);
  return (
    <div className="spread" style={{ padding:"10px 0", borderBottom:"1px solid var(--border)" }}>
      <span>{label}</span>
      <button onClick={() => setOn(!on)}
              style={{ width:36, height:20, borderRadius:999, background: on ? "var(--green-600)" : "var(--border-strong)",
                       border:0, position:"relative", cursor:"pointer" }}>
        <span style={{ width:14, height:14, borderRadius:"50%", background:"#fff", position:"absolute",
                       top:3, left: on ? 19 : 3, transition:"left 0.15s" }}></span>
      </button>
    </div>
  );
}
function IntegrationCard({ name, status, desc }) {
  return (
    <div style={{ padding:14, border:"1px solid var(--border)", borderRadius:10, background:"var(--surface-2)" }}>
      <div className="spread">
        <strong style={{ fontSize:13 }}>{name}</strong>
        <span className={"badge " + (status === "connected" ? "badge--active" : "badge--draft")}>{status}</span>
      </div>
      <div className="muted small" style={{ marginTop:4 }}>{desc}</div>
      <button className="btn btn--sm btn--ghost" style={{ marginTop:8, padding:"4px 0" }}>Configure →</button>
    </div>
  );
}

// ─── Invite Modal ────────────────────────────────────────────────
function InviteModal({ email, sent, error, onResend, onClose }) {
  const [resending, setResending] = React.useState(false);
  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(11,21,49,0.45)", display: "grid",
                  placeItems: "center", zIndex: 200 }} onClick={onClose}>
      <div className="card" style={{ width: 460, maxWidth: "92vw", boxShadow: "var(--shadow-pop)" }}
           onClick={e => e.stopPropagation()}>
        <div className="card__header">
          <div>
            <h3 className="card__title">{sent ? "เพิ่มผู้ใช้และส่ง Magic Link สำเร็จ ✓" : "เกิดข้อผิดพลาด"}</h3>
            <p className="card__sub" style={{ margin: 0 }}>ผู้ใช้จะได้รับ email พร้อมลิงก์ตั้งรหัสผ่าน</p>
          </div>
          <button className="btn btn--ghost btn--sm" onClick={onClose}><Icon name="x" size={14}/></button>
        </div>
        <div className="card__body" style={{ display: "grid", gap: 14 }}>

          {sent && (
            <div style={{ padding: "12px 14px", background: "#f0fdf4", border: "1px solid #86efac",
                          borderRadius: 8, color: "#15803d", fontSize: 14, lineHeight: 1.6 }}>
              <div style={{ fontWeight: 600, marginBottom: 4 }}>📧 ส่ง Magic Link ไปที่ <strong>{email}</strong> แล้ว</div>
              <div style={{ fontSize: 13 }}>
                ผู้ใช้คลิกลิงก์ในอีเมล → ตั้งรหัสผ่าน → เข้าสู่ระบบ
              </div>
            </div>
          )}

          {error && (
            <div style={{ padding: "10px 14px", background: "#fef2f2", border: "1px solid #fecaca",
                          borderRadius: 8, color: "#dc2626", fontSize: 13 }}>
              <strong>ส่งไม่สำเร็จ:</strong> {error}
            </div>
          )}

          <div style={{ padding: "10px 14px", background: "var(--jt-navy-50,#f0f4ff)",
                        border: "1px solid var(--jt-navy-200,#c7d2fe)", borderRadius: 8, fontSize: 13, color: "var(--text-muted)" }}>
            💡 หาก link หมดอายุ (ภายใน 1 ชั่วโมง) ผู้ใช้กด <strong>"ลืมรหัสผ่าน"</strong> ที่หน้า Login เพื่อรับ link ใหม่ได้
          </div>
        </div>
        <div style={{ padding: "14px 18px", borderTop: "1px solid var(--border)", display: "flex",
                      justifyContent: "flex-end", gap: 8 }}>
          {error && (
            <button className="btn btn--primary" disabled={resending}
                    onClick={async () => {
                      setResending(true);
                      await onResend();
                      setResending(false);
                    }}>
              {resending ? "กำลังส่ง…" : <><Icon name="bell" size={14}/> ส่งใหม่อีกครั้ง</>}
            </button>
          )}
          <button className="btn" onClick={onClose}>ปิด</button>
        </div>
      </div>
    </div>
  );
}

window.UsersAndGroups = UsersAndGroups;
window.Settings = Settings;
