function plot_results1(init_fis, final_fis, trn_error, val_error, y_true, y_pred, model_id)
%PLOT_RESULTS
% Creates and saves:
%   (A) One consolidated figure for membership functions (all inputs):
%       - 2 x Ninputs tiled layout
%       - Top row: BEFORE training (all MFs per input in one subplot)
%       - Bottom row: AFTER training (all MFs per input in one subplot)
%   (B) Learning curves (train & validation)
%   (C) Predicted vs Actual (with y=x reference)
%   (D) Prediction Error (time series + MAE)
%
% All figures are saved to ./figures as both PDF and PNG.
%
% Usage:
%   plot_results(init_fis, final_fis, trn_error, val_error, y_true, y_pred, model_id)

    % Input checks
    if nargin < 7
        error('plot_results: not enough inputs. Expected 7 arguments.');
    end
    if numel(y_true) ~= numel(y_pred)
        error('plot_results: y_true and y_pred must have the same length.');
    end
    y_true = y_true(:);
    y_pred = y_pred(:);

    % Output directory 
    outdir = fullfile('.', 'figures_scn1');
    if ~exist(outdir, 'dir'); mkdir(outdir); end

    % (A) MEMBERSHIP FUNCTIONS — ONE FIGURE, 2 x Ninputs (BEFORE / AFTER)
    % =====================================================================
    nInputs = numel(init_fis.Inputs);

    % Precompute x/y for all inputs to keep consistent axes
    Xb = cell(1, nInputs); Yb = cell(1, nInputs);   % BEFORE
    Xa = cell(1, nInputs); Ya = cell(1, nInputs);   % AFTER
    nMFb = zeros(1, nInputs); nMFa = zeros(1, nInputs);

    for inIdx = 1:nInputs
        [xb, yb] = plotmf(init_fis,  'input', inIdx);
        [xa, ya] = plotmf(final_fis, 'input', inIdx);
        Xb{inIdx} = xb; Yb{inIdx} = yb; nMFb(inIdx) = size(yb,2);
        Xa{inIdx} = xa; Ya{inIdx} = ya; nMFa(inIdx) = size(ya,2);
    end

    % Create consolidated figure
    f = figure('Name', sprintf('MFs — Model %d', model_id), 'Color','w');
    tl = tiledlayout(f, 2, nInputs, 'TileSpacing','compact', 'Padding','compact');

    % Titles for rows
    rowTitles = {'BEFORE training', 'AFTER training'};

    for inIdx = 1:nInputs
        % BEFORE (top row)
        nexttile(tl, inIdx);  % row 1, col inIdx
        hold on; grid on;
        xb = Xb{inIdx}; yb = Yb{inIdx}; kB = size(yb,2);
        for k = 1:kB
            plot(xb, yb(:,k), 'LineWidth', 1.5);
        end
        xlabel(sprintf('Input x%d', inIdx), 'Interpreter','latex');
        ylabel('Membership', 'Interpreter','latex');
        title(sprintf('%s — x%d', rowTitles{1}, inIdx), 'Interpreter','latex');

        % Optional legend only on the first tile to reduce clutter
        if inIdx == 1
            lgdB = arrayfun(@(k) sprintf('MF %d', k), 1:kB, 'UniformOutput', false);
            legend(lgdB, 'Location','best');
        end

        % AFTER (bottom row)
        nexttile(tl, nInputs + inIdx); % row 2, col inIdx
        hold on; grid on;
        xa = Xa{inIdx}; ya = Ya{inIdx}; kA = size(ya,2);
        for k = 1:kA
            plot(xa, ya(:,k), 'LineWidth', 1.5);
        end
        xlabel(sprintf('Input x%d', inIdx), 'Interpreter','latex');
        ylabel('Membership', 'Interpreter','latex');
        title(sprintf('%s — x%d', rowTitles{2}, inIdx), 'Interpreter','latex');

        if inIdx == 1
            lgdA = arrayfun(@(k) sprintf('MF %d', k), 1:kA, 'UniformOutput', false);
            legend(lgdA, 'Location','best');
        end
    end

    % Super-title
    sgtitle(tl, sprintf('Membership Functions — Model %d', model_id), 'Interpreter','latex');

    % Save consolidated MF figure
    save_figure(f, fullfile(outdir, sprintf('model_%d_mfs_all_inputs', model_id)));

    % (B) LEARNING CURVES (train & validation)
    % ============================================
    f = figure('Name', sprintf('Learning Curves - Model %d', model_id), 'Color','w');
    plot(trn_error, 'LineWidth', 1.5); hold on; grid on;
    if ~isempty(val_error)
        plot(val_error, 'LineWidth', 1.5);
        legend('Train','Validation','Location','best');
    else
        legend('Train','Location','best');
    end
    xlabel('Epoch', 'Interpreter','latex');
    ylabel('Error', 'Interpreter','latex');
    title(sprintf('Learning Curves | Model %d', model_id), 'Interpreter','latex');
    save_figure(f, fullfile(outdir, sprintf('model_%d_learning_curves', model_id)));

    % (C) PREDICTED vs ACTUAL
    % ============================================
    f = figure('Name', sprintf('Predicted vs Actual - Model %d', model_id), 'Color','w');
    plot(y_true, y_pred, '.', 'MarkerSize', 10); hold on; grid on;

    mins = min([y_true; y_pred]);
    maxs = max([y_true; y_pred]);
    plot([mins maxs], [mins maxs], 'k-', 'LineWidth', 1);

    xlabel('Actual', 'Interpreter','latex');
    ylabel('Predicted', 'Interpreter','latex');
    title(sprintf('Predicted vs Actual | Model %d', model_id), 'Interpreter','latex');
    save_figure(f, fullfile(outdir, sprintf('model_%d_pred_vs_actual', model_id)));

    % (D) PREDICTION ERROR
    % ============================================
    err = y_true - y_pred;
    f = figure('Name', sprintf('Prediction Error - Model %d', model_id), 'Color','w');
    plot(err, 'k'); grid on;
    xlabel('Iteration', 'Interpreter','latex');
    ylabel('Prediction Error', 'Interpreter','latex');
    title('Prediction Error', 'Interpreter','latex');
    mae = mean(abs(err));
    try
        subtitle(sprintf('Mean absolute error: %f', mae), 'Interpreter','latex');
    catch
        title(sprintf('Prediction Error (MAE=%.6f)', mae), 'Interpreter','latex');
    end
    save_figure(f, fullfile(outdir, sprintf('model_%d_error', model_id)));
end

% Helper: consistent saving (PDF + PNG, landscape)
function save_figure(fig_handle, basepath)
    set(fig_handle, 'PaperUnits','normalized');
    set(fig_handle, 'PaperPosition', [0 0 1 1]);
    set(fig_handle, 'PaperOrientation', 'landscape');
    % print(fig_handle, '-dpdf',  [basepath '.pdf']);
    print(fig_handle, '-dpng',  [basepath '.png']);
end
