function X = f_KDArray2ThreeD(X, k)
% f_KDArray2ThreeD  Reshape a K-mode tensor into a 3D tensor by unfolding along mode-k
%
%   This function permutes and reshapes a K-way tensor so that:
%       - Mode-k is moved to the 3rd dimension
%       - Mode-k's complement (all other modes) are collapsed into the 2nd dimension
%       - One of the remaining modes is placed in the 1st dimension
%
%   Input:
%       X - Input K-way tensor
%       k - Target mode to unfold (1-based indexing)
%
%   Output:
%       X - 3D tensor of size [sz(R), prod(sz(vC)), sz(k)], where:
%           - R  = the last mode (originally mode-K)
%           - vC = all modes excluding k and R
%
%   This transformation is useful for applying mode-k TNN, SVD, or proximal operators.

sz = size(X);         % Original size of tensor
K = length(sz);       % Number of modes

% Construct mode index for permutation
% idx_aug = [K, 1:K, 1:K] is a cyclic padding of mode indices
idx_aug = [K, 1:K, 1:K];

R = idx_aug(k);                       % R: reference mode (used as new 1st dim)
vC = idx_aug((k+2):(K-3+k+2));        % vC: complement modes excluding R and k

% New permutation order: [R, vC, k] maps tensor to [1st, 2nd, 3rd] dimensions
idx_p = [R, vC, k];

% Permute tensor into the new mode order
X = permute(X, idx_p);

% Reshape to 3D: size = [sz(R), product of vC, sz(k)]
C = prod(sz(vC));
X = reshape(X, [sz(R), C, sz(k)]);
end
