(function() {
    let config;

    $(document).ready(function() {
        console.log("Initialization of cleaner.js finished.");
        config = JSON.parse(window.localStorage.getItem("config"));
        console.log(config);
        init();
    });

    function init() {
        $(document).keydown(function(event) {
            if (event.altKey) {
                if (event.keyCode === 13) {
                    event.preventDefault();
                    clean();
                }
            }
        });
        $("#cleaner-clean-btn").click(function() {
            console.log("Clean button clicked");
            clean();
        });

        initQuickSettings();
    }

    function initQuickSettings() {
        const filterList = $("#filter-list");
        filterList.empty(); // Clear any existing list items

        config.rules.forEach(rule => {
            const listItem = $(`
                <li class="list-group-item">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="" id="${rule.strToReplace}" ${rule.enabled ? 'checked' : ''}>
                        <label class="form-check-label" for="${rule.strToReplace}">
                            ${rule.strToReplace}
                        </label>
                    </div>
                </li>
            `);
            filterList.append(listItem);
        });

        $(".form-check-input").change(function() {
            const rule = config.rules.find(r => r.strToReplace === $(this).attr("id"));
            if (rule) {
                rule.enabled = $(this).is(":checked");
                //window.localStorage.setItem("config", JSON.stringify(config));
            }
        });
    }

    async function clean() {
        console.log("Cleaning...");

        let outputText = $("#input-textarea").val();

        config.rules.forEach(rule => {
            if (rule.enabled) {
                const searchValue = rule.ignoreCase ? new RegExp(rule.strToReplace, 'gi') : new RegExp(rule.strToReplace, 'g');
                outputText = outputText.replace(searchValue, rule.replaceStr);
            }
        });

        $("#output-textarea").val(outputText);
        $("#output-container-div").removeClass("visually-hidden");

        if($("#enable-auto-copy").prop("checked")) {
            console.log("Copying result to clipboard...")
            await Neutralino.clipboard.writeText(outputText);
        }
    }
})();