function visualize_time_grid(M, scale_by_lambda, link_axes)
% Visualizza SOLO i profili temporali U{2} in una griglia 2x4 (fino a 8 componenti).
% Nessun smoothing.
%
% Usage:
%   visualize_time_grid(M);                % no scaling, link y-axes
%   visualize_time_grid(M, true);          % scale by lambda
%   visualize_time_grid(M, false, false);  % no scaling, no link axes

    if nargin < 2 || isempty(scale_by_lambda), scale_by_lambda = false; end
    if nargin < 3 || isempty(link_axes),       link_axes       = true;  end

    % Normalizza, riordina e fissa i segni (λ in M.lambda)
    M = fixsigns(arrange(normalize(M,0)));
    U = M.U;
    lam = M.lambda(:);

    R  = size(U{1}, 2);
    Rshow = min(R, 8);

    % Figura e layout 2x4
    figure('Color','w','Name','Time profiles (2x4)');
    tl = tiledlayout(2, 4, 'Padding','compact','TileSpacing','compact');

    axs = gobjects(Rshow,1);
    for r = 1:Rshow
        y = U{2}(:, r);
        if scale_by_lambda
            y = lam(r) * y;
        end

        axs(r) = nexttile; hold on;
        plot(y, 'LineWidth', 1.5, 'Color', [0 0.45 0.74]);
        xlabel('Time');
        if scale_by_lambda
            ylabel('\lambda \cdot Weight','Interpreter','tex');
        else
            ylabel('Weight');
        end
        title(sprintf('Component %d – Time (\\lambda=%.3g)', r, lam(r)));
        grid on; box on; hold off;
    end

    % Link y-axes (opzionale)
    if link_axes && numel(axs) > 1
        linkaxes(axs, 'y');
    end

    % Titolo globale
    title(tl, sprintf('Time profiles – first %d components%s', ...
        Rshow, ternary(scale_by_lambda, ' (scaled by \\lambda)', '')));
end

% Helper "ternary" per stringhe
function out = ternary(cond, a, b)
    if cond, out = a; else, out = b; end
end
