function tt_ = fetchEurostat(url, variableName)
%FETCHEUROSTAT Download and parse Eurostat time series (monthly or quarterly).
%   Author      :  Mahmut S. Ipek (Bilkent University)
%   E-mail      :  mahmuts@bilkent.edu.tr
%   Webpage     :  http://www.bilkent.edu.tr/~mahmuts
%   
% tt_ = fetchEurostat(url, variableName) retrieves data from the Eurostat
%   JSON API endpoint and returns a MATLAB timetable.
%
%   INPUTS:
%     url           - (char or string) A full Eurostat JSON API URL
%                     (see https://jsonstat.com/eurostat/)
%
%     variableName  - (char or string) The desired name of the output variable
%
%   OUTPUT:
%     tt_           - A timetable with two columns:
%                     - time_ : datetime (monthly or quarterly)
%                     - variableName : numeric data
%
%   This function automatically detects whether the data is monthly or quarterly.

    % Fetch JSON
    jsonData = webread(url);

    % Get time labels and detect their format
    timeLabelsStruct = jsonData.dimension.time.category.label;
    timeLabels = struct2cell(timeLabelsStruct);
    sampleLabel = timeLabels{1};

    % Detect frequency and set format
    if contains(sampleLabel, 'Q')
        timeFormat = 'yyyy-QQQ';
    elseif contains(sampleLabel, '-')
        timeFormat = 'yyyy-MM';
    else
        error('Unrecognized time format: %s', sampleLabel);
    end

    % Convert to datetime
    timeVecFull = datetime(timeLabels, 'InputFormat', timeFormat);

    % Extract data values and their indices
    valueStruct = jsonData.value;
    valueFields = fieldnames(valueStruct);
    N = numel(valueFields);
    timeVecFull = timeVecFull(end-N+1:end);

    data_ = zeros(N,1);
    time_ = NaT(N,1);
    
    for i = 1:N
        data_(i) = valueStruct.(valueFields{i});
        time_(i) = timeVecFull(i);
    end

    % Output timetable
    tt_ = timetable(time_, data_, 'VariableNames', variableName);
end
