// RBAC UI helpers — render based on user role/permissions

/**
 * <HasPermission permission="boq:create"> ... </HasPermission>
 * <HasPermission role={['admin', 'owner']}> ... </HasPermission>
 * <HasPermission permission="boq:create" fallback={<DisabledButton />}> ... </HasPermission>
 */
function HasPermission({ permission, role, anyOf, allOf, children, fallback = null }) {
  const user = (window.api?.getCurrentUser?.()) || (typeof window.SYK_USER !== 'undefined' ? window.SYK_USER : null);

  // Electron mode (no auth): allow everything (backward compat)
  if (!user && window.SYK_MODE === 'electron') return children;
  if (!user) return fallback;

  // Owner / admin bypass: see everything
  if (user.role === 'owner') return children;

  // Role check
  if (role) {
    const roles = Array.isArray(role) ? role : [role];
    if (!roles.includes(user.role)) return fallback;
  }

  // Permissions (single)
  if (permission) {
    const ok = (user.permissions || []).includes(permission);
    if (!ok) return fallback;
  }

  // anyOf (OR)
  if (anyOf) {
    const ok = anyOf.some(p => (user.permissions || []).includes(p));
    if (!ok) return fallback;
  }

  // allOf (AND)
  if (allOf) {
    const ok = allOf.every(p => (user.permissions || []).includes(p));
    if (!ok) return fallback;
  }

  return children;
}

/**
 * Hook for programmatic checks (e.g., in handlers)
 * Usage: const canDelete = usePermission('boq:delete');
 */
function usePermission(permission) {
  const user = window.api?.getCurrentUser?.() || null;
  if (!user) return window.SYK_MODE === 'electron'; // Electron: allow
  if (user.role === 'owner') return true;
  return (user.permissions || []).includes(permission);
}

/**
 * Hook for role checks
 */
function useRole(role) {
  const user = window.api?.getCurrentUser?.() || null;
  if (!user) return window.SYK_MODE === 'electron';
  const roles = Array.isArray(role) ? role : [role];
  return roles.includes(user.role);
}

/**
 * Get current user shorthand
 */
function useCurrentUser() {
  return window.api?.getCurrentUser?.() || null;
}

window.HasPermission = HasPermission;
window.usePermission = usePermission;
window.useRole = useRole;
window.useCurrentUser = useCurrentUser;
