
function visualize_trials_grid_with_trends(M, labels, scale_by_lambda, fit_method)
% Trials-only grid with pagination (4x2 per page), λ-scaled option,
% and per-class trend lines. Legend is attached to the layout (no extra tile).

    if nargin < 3 || isempty(scale_by_lambda), scale_by_lambda = false; end
    if nargin < 4 || isempty(fit_method), fit_method = 'robust'; end

    % Normalize & fix signs
    M = fixsigns(arrange(normalize(M,0)));
    U = M.U;
    lam = M.lambda(:);
    R  = size(U{1}, 2);
    Rshow = R;

    % Colors (assumes labels ∈ {1,2})
    cmap = [1 0 0; 0 0 1];            % scatter colors
    line_shade = [0.7 0 0; 0 0 0.7];  % line colors

    % Trials axis & color per trial
    T = numel(labels);
    x_all = (1:T)'; 
    trialColors = cmap(labels, :);

    % Pagination: 8 tiles per page (4x2)
    per_page = 8;
    tot_figures = ceil(Rshow / per_page);

    for n_figure = 1:tot_figures
        figure('Color','w', 'Name', sprintf('Trials with trends – page %d/%d', n_figure, tot_figures));
        tl = tiledlayout(4, 2, 'Padding','compact','TileSpacing','compact');

        idx_start = (n_figure - 1) * per_page + 1;
        idx_end   = min(n_figure * per_page, Rshow);
        comp_ids  = idx_start:idx_end;

        for r = comp_ids
            y = U{3}(:, r);
            if scale_by_lambda
                y = lam(r) * y;
            end

            nexttile; hold on;
            scatter(x_all, y, 40, trialColors, 'filled', 'MarkerFaceAlpha', 0.9);

            % Per-class trend lines
            for cls = [1 2]
                idx = find(labels == cls);
                if numel(idx) >= 2
                    x = x_all(idx);
                    y_cls = y(idx);

                    switch lower(fit_method)
                        case 'robust'
                            % Try robustfit; fallback to polyfit if unavailable
                            try
                                b = robustfit(x, y_cls);            % [intercept; slope]
                                yhat = b(1) + b(2) * x_all;
                            catch
                                p = polyfit(x, y_cls, 1);           % [slope intercept]
                                yhat = polyval(p, x_all);
                            end
                        case 'polyfit'
                            p = polyfit(x, y_cls, 1);               % [slope intercept]
                            yhat = polyval(p, x_all);
                        otherwise
                            error('fit_method must be ''robust'' or ''polyfit''.');
                    end

                    plot(x_all, yhat, 'LineWidth', 2, 'Color', line_shade(cls, :));
                end
            end

            xlabel('Trial');
            if scale_by_lambda
                ylabel('\lambda \cdot Weight','Interpreter','tex');
            else
                ylabel('Weight');
            end
            title(sprintf('Component %d — Trials (\\lambda=%.3g)', r, lam(r)));
            grid on; box on; hold off;
        end

        % Page title
        if scale_by_lambda
            supertxt = sprintf('Trials — components %d–%d of %d (scaled by \\lambda); fit=%s', ...
                               idx_start, idx_end, Rshow, fit_method);
        else
            supertxt = sprintf('Trials — components %d–%d of %d; fit=%s', ...
                               idx_start, idx_end, Rshow, fit_method);
        end
        title(tl, supertxt);

        % Global legend ATTACHED TO LAYOUT (does not consume a tile)
        hold on; % create dummy handles once per page
        hR  = plot(nan, nan, 'o', 'MarkerFaceColor', cmap(1,:), 'MarkerEdgeColor','none', 'DisplayName','Type 1 (red)');
        hB  = plot(nan, nan, 'o', 'MarkerFaceColor', cmap(2,:), 'MarkerEdgeColor','none', 'DisplayName','Type 2 (blue)');
        hRL = plot(nan, nan, '-', 'Color', line_shade(1,:), 'LineWidth', 2, 'DisplayName','Trend 1');
        hBL = plot(nan, nan, '-', 'Color', line_shade(2,:), 'LineWidth', 2, 'DisplayName','Trend 2');
        % New (works broadly)
        lgd = legend([hR hB hRL hBL], 'Orientation','horizontal', 'NumColumns', 4, ...
                     'AutoUpdate','off');
        lgd.Layout.Tile = 'south';

    end
end
