{% assign content_type = content_type | default: 'body' %} 

{% if content_type == 'body' %}

{% comment %}

<div id="shx-3d-render-input-container">
    <style>.custom.form__label{margin-bottom: 0.6rem}.field.custom{margin-top:0}.custom .field__input{padding-top:0.8rem}</style>  
    <label class="form__label custom" for="your-label">Dein Text</label>
    <div class="field custom">
        <input class="field__input" form="{{ 'product-form-' | append: section.id }}" type="text" id="your-label" name="properties[Your label]">
    </div>
</div>

{% endcomment %}

<shx-input-forms section_id="{{ section.id }}">
</shx-input-forms>

{% elsif content_type == 'init' %}


{% liquid
    capture shx_get_environment
      render "shx-get-environment"
    endcapture %}

<style>
    .shx-input-forms-container {
        overflow: hidden;        
    }

    .shx_ifc_renderButton, .shx-ifc-form_label {
        margin-top: 1rem;
    }

    .shx-threejs-renderer-container {
        margin-top: 1rem;
        border-radius: 10px;
        border: 0;
        width: 100%;

        position: relative;
        overflow: hidden;
        display: flex;
    }

    .shx-threejs-renderer {
        border: 0;
        width: 100%;

        background-color: ##bfb8b5;
    }

    .shx-ifc-colorselect, .shx-ifc-watchselect {
        display: flex;
        flex-wrap: wrap;
    }

    .shx-ifc-colorselect label {
        cursor: pointer;

        width: 40px;
        height: 40px;
        margin: 8px;
        border-radius: 2px;

        position: relative;
    }

    .shx-ifc-watchselect label {
        cursor: pointer;

        width: 80px;
        height: 80px;
        margin: 8px;
        border-radius: 2px;

        position: relative;
    }

    .shx-ifc-colorselect label::after, .shx-ifc-watchselect label::after {
        content: '';
        display: block;
        position: absolute;

        top: -4px;
        left: -4px;

        width: calc(100% + 8px);
        height: calc(100% + 8px);
        border-radius: 4px;

        border: 1px solid #0003;
    }

    .shx-ifc-colorselect input[type="radio"]:checked + label::after, .shx-ifc-watchselect input[type="radio"]:checked + label::after{
        border: 1px solid #111;
    }

    .shx-ifc-colorselect input[type="radio"], .shx-ifc-watchselect input[type="radio"]{
        height: 1px;
        width: 1px;
        position: absolute;
        clip: rect(0, 0, 0, 0);
        overflow: hidden;
    } 

    .shx-mat-container {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;

        overflow: hidden;
    }

    .shx-mat-matte, .shx-mat-silk {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;

        transition: all 0.5s;
    }

    .shx-mat-matte {         
        background: linear-gradient(60deg, #fff -20%, transparent 60%);
        opacity: 0.5;
    }

    .shx-mat-silk {        
        background: linear-gradient(60deg, #fff 35%, transparent 35%);
        opacity: 0.5;
    } 
    
    .shx-ifc-colorselect input[type="radio"]:checked + label .shx-mat-matte,
    .shx-ifc-colorselect input[type="radio"]:checked + label .shx-mat-silk {
        transform: scale(1.8);
        transform-origin: center; /* Ensure scaling is centered */
        opacity: 0.35;
    } 

    .invisibleInput {
        position: absolute;
        pointer-events: none;

        left: 50%;
        top: 90%;

        width: 1px;
        height: 1px;
        opacity: 0;
    }

</style>

<script type="text/javascript"> 

    const FilamentList = {
        "10": {
            "name": "Schwarz (Matt)",
            "hex": "#000000",
            "matte": true
        },
        "20": {
            "name": "Schwarz (Glänzend)",
            "hex": "#000000",
            "silk": true
        },
        "11": {
            "name": "Weiß (Matt)",
            "hex": "#FFFFFF",
            "matte": true
        },
        "12": {
            "name": "Gold (Glänzend)",
            "hex": "#ba7e14",
            "silk": true,
            "metallic": true
        },
        "13": {
            "name": "Rot (Glänzend)",
            "hex": "#BB0000",
            "silk": true
        },
        "14": {
            "name": "Holz (Matt)",
            "hex": "#78583e",
            "matte": true
        },
        "17": {
            "name": "Blau (Fluoreszierend)",
            "hex": "#1166FF",
            "matte": true
        },
        "18": {
            "name": "Orange (Fluoreszierend)",
            "hex": "#ff5638",
            "matte": true
        },
        "19": {
            "name": "Diamant-Smaragdgrün (Glitzernd)",
            "hex": "#1C2F1C",
            "silk": true
        },
        "21": {
            "name": "Rosa (Matt)",
            "hex": "#FFC0CB",
            "matte": true
        },
        "22": {
            "name": "Hellblau (Matt)",
            "hex": "#384145",
            "matte": true
        },
        "23": {
            "name": "Schokolade (Matt)",
            "hex": "#401d03",
            "matte": true
        },
        "26": {
            "name": "Beige (Matt)",
            "hex": "#ffdba6",
            "matte": true
        },
        "27": {
            "name": "Marineblau (Matt)",
            "hex": "#101060",
            "matte": true
        },
        "28": {
            "name": "Gelb (Matt)",
            "hex": "#ffd54d",
            "matte": true
        }
    }

    

    // Helper function to convert Hex to RGB
    function hexToRgb(hex) {
        let r = 0, g = 0, b = 0;
        // 3 digits
        if (hex.length === 4) {
            r = parseInt(hex[1] + hex[1], 16);
            g = parseInt(hex[2] + hex[2], 16);
            b = parseInt(hex[3] + hex[3], 16);
        }
        // 6 digits
        else if (hex.length === 7) {
            r = parseInt(hex[1] + hex[2], 16);
            g = parseInt(hex[3] + hex[4], 16);
            b = parseInt(hex[5] + hex[6], 16);
        }
        return [r, g, b];
    }

    // Helper function to convert RGB to HSL
    function rgbToHsl(r, g, b) {
        r /= 255, g /= 255, b /= 255;
        let max = Math.max(r, g, b), min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;

        if (max === min) {
            h = s = 0; // achromatic
        } else {
            let d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }

        return [h, s, l];
    }

    // Sort FilamentList by HSL
    const sortedFilementIDs = Object.keys(FilamentList).sort((a, b) => {
        let rgbA = hexToRgb(FilamentList[a].hex);
        let hslA = rgbToHsl(...rgbA);
        let rgbB = hexToRgb(FilamentList[b].hex);
        let hslB = rgbToHsl(...rgbB);

        // Compare by Hue, then Saturation, then Lightness
        for (let i = 0; i < 3; i++) {
            if (hslA[i] !== hslB[i]) {
                return hslA[i] - hslB[i];
            }
        }
        return 0; // identical colors
    });

    function SHX_getFilamentById(id) {
        let filament = FilamentList[id];
        if(filament) {
            return {...filament, "id": id};
        } else {
            console.error("Filament not found in FilamentList", id);
            return {
                
                "name": "undefined",
                "hex": "#000000"
            };
        }        
    }


    let globalInputFormsObjValues = {
        "test1": {
            "text1": "test",
            "font": "LT Beverage"
        },
        "test2": {
            "text1": "test1",
            "text2": "test2"
        }, 
        "84712": {
            "text1": "Paula",
            "font": "LT Beverage",
            "surface_finish": "silk",
            "color": SHX_getFilamentById("10")
        
        }
    };

    function SHX_IFC_genTextInput(inputID, labelText, inputName, inputVal, section_id, maxLength = 24) {
        setTimeout(() => {
            document.querySelector(`#${inputID}`).addEventListener('input',(e)=>{
                if(!document.querySelector(`label[for="${inputID}-label"] span`)){
                    const span = document.createElement("span");
                    span.style.marginLeft = `10px`
                    document.querySelector(`label[for="${inputID}-label"]`).appendChild(span)
                }
                document.querySelector(`label[for="${inputID}-label"] span`).style.display  = `inline`
                document.querySelector(`label[for="${inputID}-label"] span`).style.color = null;
                document.querySelector(`label[for="${inputID}-label"] span`).textContent = e.target.value.length + ' von ' + maxLength + ' Zeichen verwendet';
                if(e.target.value.length==0){
                    document.querySelector(`label[for="${inputID}-label"] span`).textContent = 'Bitte gib deinen Text ein';
                    document.querySelector(`label[for="${inputID}-label"] span`).style.color = 'red';
                }});
        }, 1000);

        return `
            <label class="form__label custom shx-ifc-form_label" for="${inputID}-label">${labelText}</label>
            <div class="field custom">
                <input class="field__input" form="product-form-${section_id}" type="text" id="${inputID}" name="properties[${inputName}]" value="${inputVal}" oninput="document.querySelector('shx-input-forms').renderView()" required maxlength="${maxLength}" normalMaxLength="${maxLength}">
                 
            </div>
        `;
    } 

    function  SHX_IFC_genDropdownSelect(inputID, labelText, inputName, inputVal, options, section_id) {
        let html = `
            <label class="form__label custom shx-ifc-form_label" for="${inputID}-label">${labelText}</label>
            <div class="field custom">
                <select id="${inputID}" form="product-form-${section_id}" name="properties[${inputName}]" class="field__input" style="height: 40px" onchange="document.querySelector('shx-input-forms').renderView(500)">
        `;

        for(let i = 0; i < options.length; i++) {
            html += `<option value="${options[i]}" ${inputVal === options[i] ? 'selected' : ''}>${options[i]}</option>`;
        }
        html += `</select></div>`;

        return html;
    }

    function  SHX_IFC_genColorSelect(inputID, labelText, inputName, _inputVal, colorWhiteList, section_id) {

        let options = [];

        let inputVal = _inputVal;

        if(typeof _inputVal === 'object') {
            inputVal = _inputVal.id;
        }

        if(!colorWhiteList || colorWhiteList.length === 0) {
            options = [...sortedFilementIDs];
        } else for(let i = 0; i < colorWhiteList.length; i++) {
            if(FilamentList[colorWhiteList[i]]) {
                options.push(colorWhiteList[i]);
            } else {
                console.error("Color not found in FilamentList", colorWhiteList[i]);
            }
        }


        let html = `
            <label class="form__label custom shx-ifc-form_label" for="${inputID}-label">${labelText}: <span class="shx-ifc-form_label_selected shx-ifc-form_label_selected_${inputID}">${SHX_getFilamentById(inputVal).name}</span></label>
                <div id="${inputID}" class="shx-ifc-colorselect">
        `; 


        // Iterate over the Map
        for (let i = 0; i < options.length; i++) {
            let color = options[i]; 

            html += `
                <input type="radio" id="${inputID}-${color}" class="shx-ifc-colorselect-input" form="product-form-${section_id}" name="properties[${inputName}]" value="${FilamentList[color].name} #${color}" ${inputVal === color ? 'checked' : ''}>
                <label for="${inputID}-${color}" style="background-color: ${FilamentList[color].hex};">
            `;
            
            
            html += `<div class="shx-mat-container">`;
            if(FilamentList[color].matte) {
                html += `<span class="shx-mat-matte"></span>`;
            }

            if(FilamentList[color].silk) {
                html += `<span class="shx-mat-silk"></span>`;
            }
            html += `</div>`;

            html += `</label>`;
        }

        html += `</div>`;

        return html;
    }

    function  SHX_IFC_genSwatchSelect(inputID, labelText, inputName, inputVal, options, section_id) {

        console.log("inputVal", inputVal);
        console.log("options", options);

        let html = `
            <label class="form__label custom shx-ifc-form_label" for="${inputID}-label">${labelText}: <span class="shx-ifc-form_label_selected shx-ifc-form_label_selected_${inputID}">${options[inputVal].name}</span></label>
                <div id="${inputID}" class="shx-ifc-watchselect">
        `; 

        // Iterate over the Map
        for (let swatch in options) {

            setTimeout(() => {
                document.querySelector(`#${inputID}-${swatch}`).addEventListener('change', (event) => {
                    document.querySelector('shx-input-forms').updateSelectSwatch(event, inputID, swatch, options);
                });
            }, 500);

            let swatchObj = options[swatch];

            console.log("swatch",swatch);

            html += `
                <input type="radio" id="${inputID}-${swatch}" class="shx-ifc-swatchselect-input" form="product-form-${section_id}" name="properties[${inputName}]" value="${swatchObj.name}" ${inputVal === swatch ? 'checked' : ''}>
                <label for="${inputID}-${swatch}" style="background-color: #eee; background: url('${swatchObj.imgUrl}'); background-size: cover;">
            `; 

            html += `</label>`;
        }

        html += `</div>`;

        return html;
    }
 

    const defaultStyle = `<style>.custom.form__label{margin-bottom: 0.6rem}.field.custom{margin-top: 0.6rem}.custom .field__input{padding-top:0.8rem}</style>`;

    let globalInputFormsObj = {
        "test1": {
            "renderHTML": (section_id) => {
                let html = defaultStyle;
                
                //                            elementID,   labeltext,     shopping cart name,              initial value, section_id
                html += SHX_IFC_genTextInput('shx-text1', 'Custom Text 1', 'Text', globalInputFormsObjValues['test1']['text1'], section_id);
                html += SHX_IFC_genDropdownSelect('shx-font', 'Schriftart', 'Schriftart', globalInputFormsObjValues['test1']['font'], ['LT Beverage', "Rose", 'Arial'], section_id);

                return html;
            }
        },"test2": {
            "renderHTML": (section_id) => { 
                let html = defaultStyle;

                html += SHX_IFC_genTextInput('custom-text-1', 'Custom Text 1', 'Custom Text 1', globalInputFormsObjValues['test2']['text1'], section_id);
                html += SHX_IFC_genTextInput('custom-text-2', 'Custom Text 2', 'Custom Text 2', globalInputFormsObjValues['test2']['text2'], section_id);

                return html;
            }
        }, "84712": {
            "renderHTML": (section_id) => {
                let html = defaultStyle;
                const id = "84712";

                
                html += SHX_IFC_genTextInput('shx-text1', 'Text', 'Text', globalInputFormsObjValues[id]['text1'], section_id);
                html += SHX_IFC_genDropdownSelect('shx-font', 'Schriftart', 'Schriftart', globalInputFormsObjValues[id]['font'], ['LT Beverage',  "Rose"], section_id);
                html += SHX_IFC_genSwatchSelect('shx-surface_finish', 'Vordere Oberfläche', 'Vordere Oberfläche', globalInputFormsObjValues[id]['surface_finish'], {"matte": {name: "Matt", imgUrl: "{{ "SHX-OberflaecheMatte.gif" | asset_url }}"}, "silk": {name: "Spiegelnd", imgUrl: "{{ "SHX-OberflaecheSilk.gif" | asset_url }}"}}, section_id);
                html += SHX_IFC_genColorSelect('shx-color', 'Farbe', 'Farbe', globalInputFormsObjValues[id]['color'], [], section_id);

                return html;
            }
        }
    };

    document.addEventListener("DOMContentLoaded", ()=>{
        const forms = document.querySelector("form[novalidate]");
        if(forms){
            forms.removeAttribute("novalidate");
        }
    });

    // create new html tag called "shx-input-forms"
    class InputFormsElement extends HTMLElement {
        constructor() {
            super();
            // element functionality written in here
            this.currentVariant = null;
            this.container = null;

            this.uuid = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);

            this.section_id = null;
        }

        enableBuyButton() {
            let buyButton = document.querySelector('.shopify-payment-button__button');
            if(buyButton) {
                buyButton.disabled = false;
                buyButton.style.cursor = 'pointer';
                buyButton.style.opacity = 1;
                buyButton.style.pointerEvents = 'auto';
            }

            buyButton = document.querySelector('.shopify-payment-button__more-options');
            if(buyButton) {
                buyButton.disabled = false;
            }

            this.requiredPlaceholder.value = '';
            this.requiredPlaceholder.required = false;
        }

        disableBuyButton() {
            let buyButton = document.querySelector('.shopify-payment-button__button');
            if(buyButton) {
                buyButton.disabled = true;
                buyButton.style.cursor = 'not-allowed';
                buyButton.style.opacity = 0.5;
                buyButton.style.pointerEvents = 'none';                
            }

            buyButton = document.querySelector('.shopify-payment-button__more-options');
            if(buyButton) {
                buyButton.disabled = true;
            }

            this.requiredPlaceholder.value = '';
            this.requiredPlaceholder.required = true;
        }

        showLoadingSpinner() {
            this.loadingSpinner.show();
            this.disableBuyButton();
        }

        showLoadingSpinnerError() {
            this.loadingSpinner.showError("Hoppla, da ist etwas schief gelaufen. Bitte versuche es später erneut.");
            this.disableBuyButton();
        }

        showLoadingSpinnerErrorChar() {
            this.loadingSpinner.showErrorCharLottie("Hoppla, der von dir eingegebene Text ist zu lang. Bitte kürze ihn oder wende dich an uns für eine individuelle Lösung.");
            this.disableBuyButton();
        }

        hideLoadingSpinner() {
            this.loadingSpinner.hide();
            this.enableBuyButton();
        }

        iFrameListener(event) {
            
            //console.log("event.origin||", "'"+event.origin+"'", event.origin !== "https://3d-viewer.shinnex.de")
            if(event.origin !==  {% if shx_get_environment contains "development" %}"https://3dview.wasgehtsiedasan.shinnex.de"{% else %}"https://3d-viewer.shinnex.de"{% endif %}) return;
            console.log("event.data||",event.data)

            if(event.data === undefined) return;

            let data;
            try {
                data = JSON.parse(event.data)["shx-3d-viewer"];
            } catch(e) {
                return;
            }

            let uuid =this.uuid;
            console.log("uuid", uuid);
            if(data.id !== this.uuid) {
                if(data.status === "init" ) {
                    const initData = JSON.stringify({"init":{"uuid":uuid}});
                    console.log("initData", initData    );
                    this.Viewer3D.contentWindow.postMessage(initData, "*");
                    
                    this.showLoadingSpinner();
                    this.renderView();
                }
                return;
            };

            if(data.status === "error") {
                if(data.errorMessage === "TooLong") {
                    this.showLoadingSpinnerErrorChar();
                    return;
                }

                this.showLoadingSpinnerError();
                return;
            }

            console.log("Message received from the child: ", data); // Message received from child

            if(data.loaded === true) {
                this.hideLoadingSpinner();
            } else {
                this.showLoadingSpinner();
            }
            
        }

        connectedCallback() {

            let iFrameListener = this.iFrameListener.bind(this);
            
            window.addEventListener('message', function(event) {
                iFrameListener(event);
            });

            this.section_id = this.getAttribute('section_id'); 

            this.innerHTML = '<div class="shx-input-forms-container"><div class="shx-input-forms-content"></div></div>';
            this.container = this.querySelector('.shx-input-forms-container');
            this.container.style.height = '0px';

            this.content = this.container.querySelector('.shx-input-forms-content');

            this.Viewer3DContainer = document.createElement('div');
            this.Viewer3DContainer.classList.add('shx-threejs-renderer-container');
            this.Viewer3DContainer.innerHTML = `{% render 'shx-loading-spinner', content_type:"body" %}`;
            this.loadingSpinner = this.Viewer3DContainer.querySelector('shx-loading-spinner');
            this.container.appendChild(this.Viewer3DContainer);


            function createIFrame() {
                this.Viewer3D = document.createElement('iframe');

                const Viewer3D = this.Viewer3D; 

                this.Viewer3D.src = {% if shx_get_environment contains "development" %}"https://3dview.wasgehtsiedasan.shinnex.de/"{% else %}"https://3d-viewer.shinnex.de/"{% endif %};
                this.Viewer3D.classList.add('shx-threejs-renderer');
                this.Viewer3D.style.width = this.container.offsetWidth + 'px';
                this.Viewer3D.style.height = this.container.offsetWidth + 'px';

                this.Viewer3DContainer.appendChild(this.Viewer3D);

                this.requiredPlaceholder = document.createElement('input');
                this.requiredPlaceholder.type = 'checkbox';
                this.requiredPlaceholder.classList.add('invisibleInput');
                this.requiredPlaceholder.setAttribute('form', 'product-form-' + this.section_id);
                this.requiredPlaceholder.name = 'properties[Checkbox]';
                this.requiredPlaceholder.required = true;
                this.requiredPlaceholder.checked = false; // Default unchecked
                this.requiredPlaceholder.addEventListener('input', (event) => {
                    event.target.checked = false;
                    return false;
                });

                this.Viewer3DContainer.appendChild(this.requiredPlaceholder);

                this.invisibleProductID = document.createElement('input');
                this.invisibleProductID.type = 'input';
                this.invisibleProductID.classList.add('invisibleInput');
                this.invisibleProductID.setAttribute('form', 'product-form-' + this.section_id);
                this.invisibleProductID.name = 'properties[ID]';
                this.invisibleProductID.required = false;
                this.invisibleProductID.value = this.currentVariant;
                this.invisibleProductID.addEventListener('input', (event) => {
                    event.target.checked = false;
                    return false;
                });

                this.Viewer3DContainer.appendChild(this.invisibleProductID);

            }

            setTimeout(createIFrame.bind(this), 1000);
        }

        initCurrentVariant(id) {
            this.currentVariant = id;

            // edit inner html
            this.reloadCurrentVariant(id, true);
        }

        disconnectedCallback() {
            // Clean up the element when it is removed from the DOM.
        }

        renderView(debounteTime = 1500) {
            let currentTimeout = this.renderViewDebounce;
            if(currentTimeout) {
                clearTimeout(currentTimeout);
            }

            this.renderViewDebounce = setTimeout(this._renderView.bind(this), debounteTime);
        }

        _renderView() {
            // request data from server
            let tJS = this.tJS;

            // update globalInputFormsObjValues from input fields
            for(let key in globalInputFormsObj) {
                if(key === this.currentVariant) {
                    let inputs = this.content.querySelectorAll('input');                    

                    for(let i = 0; i < inputs.length; i++) {
                        let input = inputs[i];

                        if(input.type === 'radio') {
                            if(input.checked) {

                                if(input.classList.contains('shx-ifc-colorselect-input')) {                                    
                                    let _name = input.id.replace('shx-', '');
                                    let name = _name.slice(0, _name.indexOf('-'));

                                    let filamentID = _name.slice(_name.indexOf('-') + 1);

                                    console.log('filamentID', filamentID);

                                    let filament = SHX_getFilamentById(filamentID);

                                    globalInputFormsObjValues[key][name] = JSON.stringify(filament);
                                } else  if(input.classList.contains('shx-ifc-swatchselect-input')) {
                                    let name = input.id.replace('shx-', '');

                                    let swatchID = name.slice(0, name.indexOf('-'));
                                    let swatchValue = name.slice(name.indexOf('-') + 1);

                                    globalInputFormsObjValues[key][swatchID] = swatchValue;

                                    

                                    console.log("swatch selected", key, swatchID, swatchValue );
                                }
                            }
                        }
                        else {
                            let name = input.id.replace('shx-', '');
                            globalInputFormsObjValues[key][name] = input.value;
                        }
                    }

                    let selects = this.content.querySelectorAll('select');
                    for(let i = 0; i < selects.length; i++) {
                        let name = selects[i].id.replace('shx-', '');
                        let options = selects[i].querySelectorAll('option');
                        for(let j = 0; j < options.length; j++) {
                            if(options[j].selected) {
                                globalInputFormsObjValues[key][name] = options[j].value;
                                break;
                            }
                        }
                    }
                }
            }

            // check if some values are empty ""
            for(let key in globalInputFormsObjValues[this.currentVariant]) {
                if(globalInputFormsObjValues[this.currentVariant][key].replaceAll(" ", "") === "") {
                    console.log("Empty value found", key);
                    this.disableBuyButton();
                    return;
                }
            }

            if(this.Viewer3D)
                this.Viewer3D.contentWindow.postMessage(JSON.stringify({"changeView":{"currentVariant": this.currentVariant, values: globalInputFormsObjValues[this.currentVariant]}}), "*");
                
                this.showLoadingSpinner(); 

        }

        updateSelectColorSwatch(event) {
            let target = event.target; 

            let inputID = target.id.slice(0, target.id.lastIndexOf('-'));
            let filamentID = target.id.slice(target.id.lastIndexOf('-') + 1);


            let filament = SHX_getFilamentById(filamentID);
            document.querySelector('.shx-ifc-form_label_selected_' + inputID).innerHTML = filament.name;


            this.renderView(200);
        }

        updateSelectSwatch(event, inputID, swatch, options) {
            let target = event.target;
            
            document.querySelector('.shx-ifc-form_label_selected_' + inputID).innerHTML = options[swatch].name;


            this.renderView(200);
        }

        reloadCurrentVariant(id, openAnimation = false) {
            this.currentVariant = id;
            let content = this.content;
            let container = this.container;

           

            // edit inner html
            content.innerHTML = "";
            this.renderView();

            for(let key in globalInputFormsObj) {
                if(key === this.currentVariant) {
                    content.innerHTML = globalInputFormsObj[key].renderHTML(this.section_id);
                }
            }

            const inputs = content.querySelectorAll('input');

            for(let i = 0; i < inputs.length; i++) {
                if(inputs[i].type === 'radio' && inputs[i].classList.contains('shx-ifc-colorselect-input')) {
                    inputs[i].addEventListener('change', this.updateSelectColorSwatch.bind(this));
                }
            }

            console.log('reloadCurrentVariant', id, openAnimation);


            if(openAnimation) {
                // calculate of this height
                container.style.height = 'auto';
                let height = container.offsetHeight;
                container.style.height = '0px';

                function animate() {
                    anime({
                        targets: container,
                        height: height,
                        duration: 500,
                        easing: 'cubicBezier(0.590, 0.190, 0.050, 0.990)',
                        complete: function() {
                            container.style.height = 'auto';
                            container.style.overflow = 'visible';
                        }
                    });
                }

                //animejs fade in
                //dom ready
                
                if (document.getElementById('animejs-script').readyState === 'complete' || document.getElementById('animejs-script').readyState === 'loaded'){
                    animate();                                    
                } else { 
                    document.getElementById('animejs-script').addEventListener('load', function() {
                        animate();
                    });
                }   
            } else {
                container.style.opacity = 0;
                anime({
                        targets: container,
                        opacity: 1,
                        duration: 500,
                        easing: 'cubicBezier(0.590, 0.190, 0.050, 0.990)'
                    });
            }
        }
    }

    customElements.define('shx-input-forms', InputFormsElement);


</script>

{% endif %}

