function plotSpectralAverages(scan_parameter_values, results_full, varargin)
%% plotSpectralAverages
% Author:       Karthik
% Date:         2025-09-12
% Version:      1.0
%
% Description:
%   Plot averaged power, radial, and angular spectra for a scan
%
% Inputs:
%   scan_parameter_values      - array of scan parameter values
%   spectral_analysis_results  - struct with fields:
%       kx, ky, PS_all, k_rho_vals, S_k_all, theta_vals, S_theta_all
%
% Name-Value Pair Arguments:
%   'FigNum', 'ColormapPS', 'Font', 
%   'SaveFileName', 'SaveDirectory', 'SkipSaveFigures'
%
% Notes:
%   Dataset 1 = Solid line
%   Dataset 2 = Dashed line
%   Marker shape encodes θ value (consistent across datasets)
%   Dataset colors are distinct

    % --- Extract data from struct ---
    kx           = results_full.kx;
    ky           = results_full.ky;
    ps_list      = results_full.PS_all;
    k_rho_vals   = results_full.k_rho_vals;
    s_k_list     = results_full.S_k_all;
    theta_vals   = results_full.theta_vals;
    s_theta_list = results_full.S_theta_all;

    % --- Parse optional parameters ---
    p = inputParser;
    addParameter(p, 'Title', 'Average Curves', @(x) ischar(x) || isstring(x));
    addParameter(p, 'AnnotationSuffix', '%.1f^\\circ', @(x) ischar(x) || isstring(x));
    addParameter(p, 'ColormapPS', [], @(x) isnumeric(x) || ismatrix(x));
    addParameter(p, 'FontName', 'Arial', @ischar);
    addParameter(p, 'FontSize', 14, @isnumeric);
    addParameter(p, 'FigNum', 1, @(x) isnumeric(x) && isscalar(x));
    addParameter(p, 'SaveFileName', 'avgspectra.fig', @ischar);
    addParameter(p, 'SaveDirectory', pwd, @ischar);
    addParameter(p, 'SkipSaveFigures', false, @islogical);
    parse(p, varargin{:});
    opts = p.Results;
    
    axisFontSize  = opts.FontSize;
    titleFontSize = opts.FontSize+2;

    % --- Compute averaged data using shared helper ---
    PS_data      = Analyzer.computeSpectralAverages(ps_list,      scan_parameter_values);
    S_k_data     = Analyzer.computeSpectralAverages(s_k_list,     scan_parameter_values);
    S_theta_data = Analyzer.computeSpectralAverages(s_theta_list, scan_parameter_values);

    % --- Unique scan parameters ---
    uniqueParams = S_k_data.scan_parameters;
    nParams = numel(uniqueParams);

    % --- Loop over each unique parameter ---
    for pIdx = 1:nParams
        currentParam = uniqueParams(pIdx);

        avgPS      = PS_data.curves_mean{pIdx};
        avgS_k     = S_k_data.curves_mean{pIdx};
        avgS_theta = S_theta_data.curves_mean{pIdx};

        % ==== Plot ====
        fig = figure(opts.FigNum); clf;
        set(fig, 'Color', 'w', 'Position', [400 200 1200 400]);
        tLayout = tiledlayout(1,3,'TileSpacing','compact','Padding','compact');

        % --- 1. Power Spectrum ---
        nexttile;
        imagesc(kx, ky, log(1 + avgPS));
        axis image;
        set(gca, 'FontSize', axisFontSize, 'YDir', 'normal');
        xlabel('k_x [\mum^{-1}]','Interpreter','tex','FontSize',axisFontSize,'FontName',opts.FontName);
        ylabel('k_y [\mum^{-1}]','Interpreter','tex','FontSize',axisFontSize,'FontName',opts.FontName);
        title('Average Power Spectrum','FontSize',titleFontSize,'FontWeight','bold');
        if isempty(opts.ColormapPS)
            opts.ColormapPS = Colormaps.coolwarm();
        end
        colormap(opts.ColormapPS);
        colorbar;

        % --- Annotate scan parameter ---
        txt = sprintf(opts.AnnotationSuffix, currentParam);
        text(0.975,0.975,txt,'Color','white','FontWeight','bold','FontSize',axisFontSize, ...
            'Interpreter','tex','Units','normalized','HorizontalAlignment','right','VerticalAlignment','top');

        % --- 2. Radial Spectrum ---
        nexttile;
        plot(k_rho_vals, avgS_k, 'LineWidth', 2);
        xlabel('k_\rho [\mum^{-1}]','Interpreter','tex','FontSize',axisFontSize);
        ylabel('Magnitude (a.u.)','Interpreter','tex','FontSize',axisFontSize);
        title('Average S(k_\rho)','FontSize',titleFontSize,'FontWeight','bold');
        set(gca,'FontSize',axisFontSize,'YScale','log','XLim',[min(k_rho_vals), max(k_rho_vals)]);
        grid on;

        % --- 3. Angular Spectrum ---
        nexttile;
        plot(theta_vals/pi, avgS_theta, 'LineWidth', 2);
        xlabel('\theta/\pi [rad]','Interpreter','tex','FontSize',axisFontSize);
        ylabel('Magnitude (a.u.)','Interpreter','tex','FontSize',axisFontSize);
        title('Average S(\theta)','FontSize',titleFontSize,'FontWeight','bold');
        set(gca,'FontSize',axisFontSize,'YScale','log','YLim',[1e4, 1e7]);
        ax = gca;
        ax.XMinorGrid = 'on';
        ax.YMinorGrid = 'on';
        grid on;
        
        sgtitle(opts.Title, 'FontName', opts.FontName, 'FontSize', titleFontSize+2);

        drawnow;

        % --- Save figure ---
        Plotter.saveFigure(fig, ...
            'SaveFileName', opts.SaveFileName, ...
            'SaveDirectory', opts.SaveDirectory, ...
            'SkipSaveFigures', opts.SkipSaveFigures);
    end
end
