function createRadioButton(item, container, name, isChecked) {
    const wrapper = document.createElement('div');
    
    const input = document.createElement('input');
    input.type = 'radio';
    input.id = item.key;
    input.name = name;
    input.value = item.key;
    if (isChecked) input.checked = true;

    const label = document.createElement('label');
    label.htmlFor = item.key;
    label.innerHTML = item.label;

    wrapper.appendChild(input);
    wrapper.appendChild(label);

    container.appendChild(wrapper);
    // container.appendChild(document.createElement('br'));
}


function generateConfigDir(model, algorithm, k) {
    // This function should generate the new image URL based on the inputs
    // For example, you might concatenate the values to form a URL
    // This is a placeholder function; replace it with your actual logic
    method_dir = "";
    if (algorithm == "QP")
    {
        method_dir = "cvxproj";
    }
    else if (algorithm == "KL")
    {
        method_dir = "ad";
    }

    config_dir = `supp_perturbations/${model}/${method_dir}/k${k}`;
    return config_dir;
}

document.addEventListener('DOMContentLoaded', function () {
    // addModelRadioButtons();

    // const singleModels = [
    //     { key: 'resnet50', label: 'ResNet-50' },
    //     { key: 'densenet121', label: 'DenseNet-121' },
    //     { key: 'deit_small', label: 'DeiT_S' },
    //     { key: 'vit_base', label: 'ViT_B' },
    //     // Add more models as needed
    // ];

    const singleModels = Object.entries(MODEL_DATA).map((entry)=>{
       return {key:entry[0], label:entry[1]["mathml"].replace("-", "\\text{-}")};
    });

    const modelCombos = [
        [0],
        [3],
        [1],
        [2],
        [0, 3],
        [2, 1],
        [0, 3, 2, 1],
        [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],
        [18],
        [19],
        [20],
        [21],
        [22],
        [23],
        [24],
        [25],
        [26],
        [27]
    ];

    const models = modelCombos.map((modelIdxs)=>{
        modelKeys = [];
        modelLabels = [];
        modelIdxs.forEach((modelIdx, i) => {
            modelKeys.push(singleModels[modelIdx]["key"]);
            modelLabels.push(singleModels[modelIdx]["label"]);
        });

        comboKey = modelKeys.join("_");
        comboLabel = modelLabels.join(" + ");

        if (modelIdxs.length == 18)
        {
            comboLabel = "18-Model Ensemble";
            comboKey = "medensemble";
        }
        
        return {
            "key": comboKey,
            "label": comboLabel
        }
    });

    modelKeyToIdxs = {};
    modelCombos.forEach((modelIdxs)=>{
        modelKeys = [];
        modelIdxs.forEach((modelIdx, i) => {
            modelKeys.push(singleModels[modelIdx]["key"]);
        });

        comboKey = modelKeys.join("_");

        if (modelIdxs.length == 18)
        {
            comboKey = "medensemble";
        }

        modelKeyToIdxs[comboKey] = modelIdxs;
    });

    const algorithms = [
        { key: 'QP', label: 'QP' },
        { key: 'KL', label: 'KL' },
    ];

    const modelSelectionDiv = document.getElementById('modelSelection');
    const algorithmSelectionDiv = document.getElementById('algorithmSelection');
    const kValueInput = document.getElementById('kValue');
    const seedValueInput = document.getElementById('seedValue');
    const imageDescriptionDiv = document.getElementById('imageDescription');
    const attackTargetsDiv = document.getElementById('attackTargets');
    const selectionDiv = document.getElementById("selectionDisplay");
    const noDataDiv = document.getElementById("noDataDisplay");
    noDataDiv.style.display = "none";
    selectionDiv.style.display = "block";

    // Dynamically create radio buttons for models and algorithms
    models.forEach((model, index) => createRadioButton(model, modelSelectionDiv, 'model', index === 0));
    // algorithms.forEach((algorithm, index) => createRadioButton(algorithm, algorithmSelectionDiv, 'algorithm', index === 0));

    algorithms.forEach((algorithm, index) => {
        container = document.createElement("div");
        const input = document.createElement('input');
        input.type = 'checkbox';
        input.id = algorithm.key;
        input.name = 'algorithm';
        input.value = algorithm.key;
        input.checked = index == 0;

        const label = document.createElement('label');
        label.htmlFor = algorithm.key;
        label.textContent = algorithm.label;

        container.appendChild(input);
        container.appendChild(label);
        algorithmSelectionDiv.appendChild(container);
    });


    // Add event listeners
    document.querySelectorAll('input[name="model"], input[name="algorithm"]').forEach(input => {
        input.addEventListener('change', updateImages);
    });

    kValueInput.addEventListener('input', updateImages);
    seedValueInput.addEventListener('input', updateImages);

    function updateImages() {
        const selectedModelKey = document.querySelector('input[name="model"]:checked')?.value;
        const imagesContainer = document.getElementById('imagesContainer');
        imagesContainer.innerHTML = ''; // Clear existing images

        const kValue = kValueInput.value;
        const seedValue = seedValueInput.value * 10;
        const selectedModelIdxs = modelKeyToIdxs[selectedModelKey];
        const selectedModelLabels = selectedModelIdxs.map((modelIdx)=>singleModels[modelIdx]["label"]);
        algorithmCheckboxes = document.querySelectorAll('input[name="algorithm"]:checked');

        algorithmCheckboxes.forEach((algorithmInput, index) => {
            selectedMethod = algorithmInput.value;

            if (selectedMethod == "QP")
            {
                selectedMethod = "cvxproj";
            }
            else if (selectedMethod == "KL")
            {
                selectedMethod = "ad";
            }

            try{
                if (PRED_DATA[kValue][seedValue][selectedModelKey][selectedMethod]["pred_names"] == null)
                {
                    throw Error();
                }
                noDataDiv.style.display = "none";
                selectionDiv.style.display = "block";
            }
            catch{
                noDataDiv.style.display = "block";
                selectionDiv.style.display = "none";
                return;
            }
        });

        if (algorithmCheckboxes.length == 1){
            selectedMethod = algorithmCheckboxes[0].value;

            if (selectedMethod == "QP")
            {
                selectedMethod = "cvxproj";
            }
            else if (selectedMethod == "KL")
            {
                selectedMethod = "ad";
            }

            description = "<b>Predicted labels for perturbations generated with " + algorithmCheckboxes[0].value + "</b><br/>";
            predNames = PRED_DATA[kValue][seedValue][selectedModelKey][selectedMethod]["pred_names"]
            predNames.forEach((preds, i)=>{
                // preds = preds.replace(",", "-");
                description += selectedModelLabels[i] + " predicted "
                    + preds.join(", ") + "<br/>";
            });
            imageDescriptionDiv.innerHTML = description;
        }
        else{
            imageDescriptionDiv.innerHTML = "";
        }

        attackTargetsDescription = "Attack targets are ";
        attackTargetsDescription += ATTACK_LABELS_DATA[kValue][seedValue];
        attackTargetsDiv.innerHTML = attackTargetsDescription;

        algorithmCheckboxes.forEach((algorithmInput, index) => {

            algorithmContainer = document.createElement('div');
            algorithmContainer.className = "image-row";

            algLabel = document.createElement('div');
            algLabel.innerHTML = algorithmInput.value;

            algorithmContainer.appendChild(algLabel);

            for (let iterK = 1; iterK <= kValue; iterK++) {

                    const algorithmKey = algorithmInput.value;
                    const configDir = generateConfigDir(selectedModelKey, algorithmKey, iterK, seedValue);

                    imageUrl = `${configDir}/${seedValue}.png`;

                    const img = document.createElement('img');
                    img.src = imageUrl;
                    img.display = "block";
                    img.width = 250;
                    img.title = algorithmInput.value + " - K=" + iterK;
                    img.alt = `Image ${algorithmKey}`;
                    algorithmContainer.appendChild(img);
                
            }

            imagesContainer.appendChild(algorithmContainer);
        });

        MathJax.typesetPromise().then(() => {
            console.log('MathJax has finished processing.');
          }).catch((err) => console.log('MathJax processing error:', err));
    }

    updateImages();
});
