// ───────────────────────────────────────────────────────────────
// Busco Ops — Users & roles screen
// Admin-only management of people + the role → access matrix that
// defines what each team ranking can see.
// ───────────────────────────────────────────────────────────────

const ROLE_TONE = {
  warehouse:  { dot: "var(--muted-2)",  bg: "var(--canvas)",   fg: "var(--text-2)",  bd: "var(--border)" },
  dispatch:   { dot: "var(--info-600)", bg: "var(--info-50)",  fg: "var(--info-700)", bd: "var(--info-100)" },
  supervisor: { dot: "var(--good-600)", bg: "var(--good-50)",  fg: "var(--good-700)", bd: "var(--good-100)" },
  accountant: { dot: "var(--warn-600)", bg: "var(--warn-50)",  fg: "var(--warn-700)", bd: "var(--warn-100)" },
  manager:    { dot: "var(--b500)",     bg: "var(--b50)",      fg: "var(--b700)",    bd: "var(--b100)" },
  owner:      { dot: "#EAB308",         bg: "#FEF3C7",         fg: "#854D0E",        bd: "#FDE68A" },
};

function RoleChip({ roleKey }) {
  const r = roleOf(roleKey);
  const t = ROLE_TONE[roleKey] || ROLE_TONE.dispatch;
  return (
    <span className="tier" style={{ background: t.bg, color: t.fg, border: `1px solid ${t.bd}` }}>
      <span className="tdot" style={{ background: t.dot }} />
      {window.t(r.label)}
    </span>
  );
}

function UsersScreen({ user, onToast, onImpersonate }) {
  const users = useStore((s) => s.users);
  const me = roleOf(user?.roleKey);
  const canManage = !!me.manage;
  const [invite, setInvite] = useState(false);
  const [removeTarget, setRemoveTarget] = useState(null);

  const counts = ROLES.reduce((a, r) => { a[r.key] = users.filter((u) => u.roleKey === r.key).length; return a; }, {});
  const active = users.filter((u) => u.status === "active").length;
  const invited = users.filter((u) => u.status === "invited").length;
  const pending = users.filter((u) => u.status === "pending");
  const admins = users.filter((u) => roleOf(u.roleKey).manage).length;

  // sections shown in the access matrix (in nav order)
  const matrixSections = SECTIONS;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {canManage && pending.length > 0 &&
        <div className="banner" style={{ background: "var(--warn-50)", borderColor: "var(--warn-100)", color: "var(--warn-700)" }}>
          <Icon name="alert-circle" size={16} color="var(--warn-700)" />
          <div>
            <b>{pending.length} {pending.length === 1 ? window.t("account is waiting for approval.") : window.t("accounts are waiting for approval.")}</b>{" "}
            <span style={{ color: "var(--muted)" }}>{pending.map((u) => u.name).join(" · ")} — {window.t("approve below to grant access.")}</span>
          </div>
        </div>
      }
      {!canManage &&
        <div className="banner warn">
          <Icon name="lock" size={16} color="var(--warn-700)" />
          <div>
            <b>View-only.</b>{" "}
            <span style={{ color: "var(--muted)" }}>Your role ({me.label}) can see the team roster but cannot change roles or invite people. Ask an Operations Manager or Owner.</span>
          </div>
        </div>
      }

      <div className="kpi-row">
        <KPI label={window.t("Team members")} value={users.length} sub={`${active} ${window.t("active")} · ${pending.length} ${window.t("Pending").toLowerCase()}`} icon="users" tint="var(--b50)" accent="var(--b600)" />
        <KPI label={window.t("Admins")} value={admins} sub={window.t("manager & owner roles")} icon="lock" tint="var(--warn-50)" accent="var(--warn-700)" />
        <KPI label={window.t("Dispatch")} value={counts.dispatch || 0} sub={window.t("ops & alerts access")} icon="truck" tint="var(--info-50)" accent="var(--info-700)" />
        <KPI label={window.t("Warehouse")} value={counts.warehouse || 0} sub={window.t("daily log only")} icon="clipboard" tint="var(--good-50)" accent="var(--good-700)" />
      </div>

      {/* ── Roles & access matrix ── */}
      <div className="card">
        <div className="card-head">
          <div className="ch-l">
            <h3>Roles &amp; access</h3>
            <div className="ch-sub">Team rankings, low to high — each role unlocks more of the centre</div>
          </div>
        </div>
        <div className="card-body" style={{ paddingTop: 4 }}>
          <div className="tbl-wrap" style={{ boxShadow: "none", border: "1px solid var(--border)" }}>
            <table className="data">
              <thead>
                <tr>
                  <th style={{ width: 230 }}>{window.t("Role")}</th>
                  {matrixSections.map((s) => <th key={s.id} style={{ textAlign: "center" }}>{s.label}</th>)}
                </tr>
              </thead>
              <tbody>
                {ROLES.map((r) => (
                  <tr key={r.key}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <span className="mono" style={{ fontSize: 11, color: "var(--muted-2)", width: 18 }}>R{r.rank}</span>
                        <div>
                          <RoleChip roleKey={r.key} />
                          <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>{r.blurb}</div>
                        </div>
                      </div>
                    </td>
                    {matrixSections.map((s) => {
                      const on = r.sections.includes(s.id);
                      return (
                        <td key={s.id} style={{ textAlign: "center" }}>
                          {on
                            ? <Icon name="check" size={14} color="var(--good-700)" strokeWidth={2.5} />
                            : <span style={{ color: "var(--muted-3)" }}>·</span>}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* ── Team directory ── */}
      <div className="sec" data-tour="users">
        <h2>{window.t("Team directory")} <span className="ct">{users.length}</span></h2>
        <div className="sec-right">
          {canManage &&
            <button className="btn primary sm" onClick={() => setInvite(true)}>
              <Icon name="plus" size={12} color="#fff" /> Invite user
            </button>
          }
        </div>
      </div>

      <div className="tbl-wrap">
        <table className="data">
          <thead>
            <tr>
              <th>{window.t("Member")}</th>
              <th>{window.t("Email")}</th>
              <th style={{ width: 220 }}>{window.t("Role")}</th>
              <th>{window.t("Status")}</th>
              <th>{window.t("Last active")}</th>
              <th style={{ width: 150 }}></th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => {
              const isSelf = user && (u.email === user.email);
              const targetRank = roleOf(u.roleKey).rank;
              // can edit this row's role if I manage AND target isn't above me AND not myself
              const editable = canManage && !isSelf && targetRank <= me.rank;
              const t = ROLE_TONE[u.roleKey] || ROLE_TONE.dispatch;
              return (
                <tr key={u.id}>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 28, height: 28, borderRadius: "var(--r-sm)", background: t.bg, border: `1px solid ${t.bd}`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10.5, fontWeight: 700, color: t.fg }}>
                        {u.initials}
                      </div>
                      <div className="strong" style={{ fontSize: 12.5 }}>
                        {u.name}
                        {isSelf && <span className="badge badge-slate" style={{ marginLeft: 7, fontSize: 9.5 }}>{window.t("You")}</span>}
                      </div>
                    </div>
                  </td>
                  <td className="mono" style={{ fontSize: 11.5, color: "var(--muted)" }}>{u.email}</td>
                  <td>
                    {editable ? (
                      <select
                        value={u.roleKey}
                        onChange={(e) => { Store.setUserRole(u.id, e.target.value); onToast(`${u.name} is now ${roleOf(e.target.value).label}`); }}
                        style={{ border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: "5px 9px", fontSize: 12, background: "var(--surface)", color: "var(--text)", maxWidth: 200 }}
                      >
                        {ROLES.filter((r) => r.rank <= me.rank).map((r) => (
                          <option key={r.key} value={r.key}>{r.label}</option>
                        ))}
                      </select>
                    ) : (
                      <RoleChip roleKey={u.roleKey} />
                    )}
                  </td>
                  <td>
                    <span className={"status " + (u.status === "active" ? "paid" : u.status === "pending" ? "overdue" : "pending")}>
                      {u.status === "active" ? window.t("Active") : u.status === "pending" ? window.t("Pending") : window.t("Invited")}
                    </span>
                  </td>
                  <td className="muted" style={{ fontSize: 11.5 }}>{u.last}</td>
                  <td>
                    <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                      {canManage && u.status === "pending" &&
                        <button className="btn primary sm" title="Approve this account" onClick={() => { Store.setUserStatus(u.id, "active"); onToast(`${u.name} approved`); }}>
                          <Icon name="check" size={12} color="#fff" /> {window.t("Approve")}
                        </button>
                      }
                      {!isSelf && u.status === "active" &&
                        <button className="btn ghost sm" title="Preview this person’s access" onClick={() => onImpersonate(u)}>
                          <Icon name="search" size={12} /> View as
                        </button>
                      }
                      {canManage && !isSelf && targetRank <= me.rank &&
                        <button className="btn ghost sm" title="Remove" onClick={() => setRemoveTarget(u)}>
                          <Icon name="trash" size={12} color="var(--crit)" />
                        </button>
                      }
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {invite && <InviteUserDrawer me={me} onClose={() => setInvite(false)} onToast={onToast} />}
      {removeTarget &&
        <ConfirmModal
          title={`Remove ${removeTarget.name}?`}
          body={`${removeTarget.name} will lose access to Busco Ops immediately. This can’t be undone from here.`}
          confirmLabel="Remove user"
          tone="danger"
          onConfirm={() => { Store.removeUser(removeTarget.id); onToast(`${removeTarget.name} removed`, "danger"); }}
          onClose={() => setRemoveTarget(null)}
        />
      }
    </div>
  );
}

function InviteUserDrawer({ me, onClose, onToast }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [roleKey, setRoleKey] = useState("warehouse");
  const assignable = ROLES.filter((r) => r.rank <= me.rank);

  const save = () => {
    Store.inviteUser({ name, email, roleKey });
    onToast(`Invite sent to ${email}`);
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="slide-panel" onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>{window.t("Invite user")}</h3>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{window.t("Send an invite and assign a starting role")}</div>
          </div>
          <button className="close-x" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 14, overflowY: "auto", flex: 1 }}>
          <div className="field"><label>{window.t("Full name")}</label><input value={name} onChange={e => setName(e.target.value)} placeholder={window.t("e.g. Omar Khan")} /></div>
          <div className="field"><label>{window.t("Work email")}</label><input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="name@busco.sa" /></div>
          <div className="field">
            <label>Role</label>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {assignable.map((r) => (
                <button
                  key={r.key}
                  className={"ws-row" + (roleKey === r.key ? " on" : "")}
                  onClick={() => setRoleKey(r.key)}
                >
                  <span className="ws-row-dot" style={{ background: roleKey === r.key ? undefined : (ROLE_TONE[r.key] || {}).dot }} />
                  <span style={{ flex: 1, textAlign: "left" }}>
                    <span style={{ display: "block", fontSize: 13, fontWeight: 600 }}>{r.label}</span>
                    <span style={{ display: "block", fontSize: 11, color: "var(--muted)", marginTop: 1 }}>{r.blurb}</span>
                  </span>
                  {roleKey === r.key && <Icon name="check" size={14} color="var(--b600)" />}
                </button>
              ))}
            </div>
          </div>
        </div>
        <div style={{ padding: 18, borderTop: "1px solid var(--border)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn" onClick={onClose}>{window.t("Cancel")}</button>
          <button className="btn primary" disabled={!name || !email} onClick={save}><Icon name="send" size={12} color="#fff" /> Send invite</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { UsersScreen, RoleChip });
