jQuery(document).ready(function ($) {
    "use strict";
    let currentSyncState = "";

    const _locale = ajaxObject.settings_strings

    $(document).ready(function () {
        $('.sync-button').each(function () {
            const originalText = $(this).text(); // Get the original innerText
            $(this).attr('data-original-text', originalText); // Save it as a custom attribute
            $(this).attr('disabled', true);
        });
    });

    function restoreSyncButtonState() {
        $('.sync-button').each(function () {
            const originalText = $(this).attr('data-original-text'); // Get the original text from the attribute
            if (originalText) {
                $(this).text(originalText); // Restore the original text
                $(this).attr('disabled', false);
            }
            currentSyncState = "";
        });
        $("#current-sync-state").val("");
    }

    function engageSync(type, direction) {
        $('.sync-button').each(function () {
            const originalText = $(this).attr('data-original-text');
            const elementText = $(this).attr('data-original-text');
            const elementType = $(this).attr('data-type');
            const elementDirection = $(this).attr('data-direction');
            if (originalText) {
                if (elementText !== originalText) {
                    $(this).text(originalText); // Restore the original text
                }
                if (elementType === type && direction === elementDirection) {
                    $(this).text(_locale.syncing);
                    $("#current-sync-state").val(type);
                }
            }
        });
    }

    function appendLog(message, isError = false) {
        const logContainer = $('#sync-log-container');
        const logItem = `<p style="${isError ? 'color: red;' : ''}">${message}</p>`;
        logContainer.append(logItem);
        if(logContainer[0]){
            logContainer.scrollTop(logContainer[0].scrollHeight);
        }

    }

    function setButtonState(button, state) {
        if (state === 'syncing') {
            button.prop('disabled', true).text(_locale.syncing);
        } else {
            button.prop('disabled', false).text(button.data('original-text') || _locale.sync);
        }
    }

    let updateButtonsState = function (running) {
        if (running) {
            appendLog(_locale.running);
        } else {
            appendLog(_locale.not_running);
        }
    };

    function checkSyncStatus() {
        $.post(ajax_object.ajax_url, {
            action: 'check_sync_status',
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                const data = response.data;
                const progress = ((data.processed_files / data.total_files) * 100).toFixed(1);

                if (data.status === 'processing') {
                    updateButtonsState(true);
                    const direction = data.direction === 'upload' ? _locale.to_aws : _locale.from_aws;
                    appendLog(`${_locale.progress}: ${progress}% (${data.processed_files}/${data.total_files} ${_locale.files} ${direction})`);
                    setTimeout(checkSyncStatus, 5000);
                    engageSync(data.type, data.direction);
                } else if (data.status === 'completed') {
                    appendLog(_locale.sync_completed);
                    updateButtonsState(false);
                    data.successes.forEach((file) => {
                        appendLog(`${data.direction === 'upload' ? _locale.uploaded : _locale.downloaded}: ${file}`);
                    });
                    restoreSyncButtonState();
                    data.errors.forEach((error) => {
                        appendLog(error, true);
                    });
                    setButtonState($('#sync-local-to-aws'), 'default');
                } else if (data.status === 'failed') {
                    restoreSyncButtonState();
                    updateButtonsState(false);
                    appendLog(_locale.sync_failed, true);
                    data.errors.forEach((error) => {
                        appendLog(error, true);
                    });
                    setButtonState($('#sync-local-to-aws'), 'default');
                } else {
                    updateButtonsState(false);
                    restoreSyncButtonState();
                }
            }
        });
    }

    $('#sync-local-to-aws').each(function () {
        $(this).data('original-text', $(this).text());
    });

    function sync_local_to_aws(type, button) {
        currentSyncState = type;
        if (!confirm(_locale.confirm_sync_local_to_aws)) return;

        setButtonState(button, 'syncing');
        appendLog(_locale.starting_sync);
        $.post(ajax_object.ajax_url, {
            action: 'sync_local_to_aws',
            type: type,
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                appendLog(`${_locale.starting_sync_of}: ${response.data.total_files} ${_locale.files}`);
                checkSyncStatus();
            } else {
                appendLog(`${_locale.failed_to_start_sync}: ${response.data}`, true);
                setButtonState(button, 'default');
            }
        }).fail(function (xhr) {
            appendLog(_locale.failed_to_start_sync, true);
            console.error('XHR:', xhr);
            setButtonState(button, 'default');
        });
    }
    $('#stop-all-processes').on('click', function (e) {
        e.preventDefault();
        const button = $(this);
        const originalText = button.text();

        if (!confirm(_locale.confirm_stop_processes)) return;

        button.text(_locale.stopping);
        appendLog(_locale.stopping_processes);
        $.post(ajax_object.ajax_url, {
            action: 'stop_all_processes',
            nonce: ajax_object.nonce,
        }, function (response) {
            button.text(originalText);
            restoreSyncButtonState();
            if (response.success) {
                appendLog(response.data.message);
            } else {
                appendLog(`${_locale.failed_to_stop_processes}: ${response.data}`, true);
            }
        }).fail(function (xhr) {
            appendLog(_locale.failed_to_stop_processes, true);
            console.error('XHR:', xhr);
            button.text(originalText);
        });
    });

    $('#sync-local-to-aws').on('click', function (e) {
        e.preventDefault();
        const message = getMessageforSyncing();
        if (message !== "") {
            return alert(message);
        }
        $("#current-sync-state").val("media");
        const button = $(this);
        sync_local_to_aws("media", button);
    });

    function getMessageforSyncing() {
        if ($("#current-sync-state").val() !== "") {
            return `${$("#current-sync-state").val()} ${_locale.sync_in_process}`;
        }
        return "";
    }

    $("#clear-cloudfront-cache-button").on("click", function () {
        if (!confirm(_locale.confirm_clear_cache)) return;
        appendLog(_locale.clearing_cache);
        $.post(ajax_object.ajax_url, {
            action: 'clear_cloudfront_cache',
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                appendLog(_locale.cache_cleared);
            } else {
                appendLog(_locale.failed_to_clear_cache, true);
            }
        });
    });

    
    $(".use-cloudfront-button").on("click", function () {
        const type = $(this).data("type");
        let useCdn = false;
        const element = $(this);

        if ($(this)[0].checked) {
            appendLog(_locale.setting_up_cdn);
            useCdn = true;
        } else {
            appendLog(_locale.removing_cdn);
            useCdn = false;
        }

        $.post(ajax_object.ajax_url, {
            action: 'toggle_cdn',
            useCdn: useCdn,
            type: type,
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                appendLog(_locale.cdn_setup_success);
            } else {
                element.prop('checked', false);
                appendLog(`${_locale.cdn_setup_failed}: ${response.data}`, true);
            }
        });
    });

    $("#auto-delete-media").on("click", function () {
        const element = $(this);
        let state = false;

        if ($(this)[0].checked) {
            appendLog(_locale.enabling_auto_delete);
            state = true;
        } else {
            appendLog(_locale.disabling_auto_delete);
            state = false;
        }

        $.post(ajax_object.ajax_url, {
            action: 'toggle_media_auto_delete',
            state: state,
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                if (state) {
                    appendLog(_locale.auto_delete_enabled);
                } else {
                    appendLog(_locale.auto_delete_disabled);
                }
            } else {
                element.prop('checked', false);
                appendLog(`${_locale.auto_delete_failed}: ${response.data}`, true);
            }
        });
    });

    $('#sync-local-to-aws-plugin').on('click', function (e) {
        e.preventDefault();
        const message = getMessageforSyncing();
        if (message !== "") {
            return alert(message);
        }
        $("#current-sync-state").val("assets");
        const button = $(this);
        sync_local_to_aws("assets", button);
    });

    $("#fetch-analytics-button").on("click", function () {
        fetchAnalytics();
    });

    $('#sync-aws-to-local').on('click', function (e) {
        e.preventDefault();
        const button = $(this);

        if (!confirm(_locale.confirm_sync_aws_to_local)) return;

        const message = getMessageforSyncing();
        if (message !== "") {
            return alert(message);
        }
        $("#current-sync-state").val("media");

        setButtonState(button, 'syncing');
        appendLog(_locale.starting_sync);

        $.post(ajax_object.ajax_url, {
            action: 'sync_aws_to_local',
            type: "media",
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                appendLog(`${_locale.starting_sync_of}: ${response.data.total_files} ${_locale.files}`);
                checkSyncStatus();
            } else {
                appendLog(`${_locale.failed_to_start_sync}: ${response.data}`, true);
                setButtonState(button, 'default');
            }
        }).fail(function () {
            appendLog(_locale.failed_to_start_sync, true);
            setButtonState(button, 'default');
        });
    });

    function fetchAnalytics() {
        $('#total-files').text(_locale.loading);
        $('#total-storage').text(_locale.loading);
        $('#total-price').text(_locale.loading);

        $.post(ajax_object.ajax_url, {
            action: 'fetch_aws_analytics',
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                $('#total-files').text(response.data.total_files);
                $('#total-storage').text(response.data.total_storage);
                $('#total-price').text(`~ ${response.data.price_in_dollars} USD`);
            } else {
                $('#total-files').text(_locale.error);
                $('#total-storage').text(_locale.error);
                appendLog(_locale.failed_to_fetch_analytics, true);
            }
        }).fail(function () {
            $('#total-files').text(_locale.error);
            $('#total-storage').text(_locale.error);
            appendLog(_locale.failed_to_fetch_analytics, true);
        });
    }

    $('#reconfigure-aws').on('click', function (e) {
        e.preventDefault();
        window.location.href = ajax_object.wizard_url;
    });

    function init() {
        // Fetch AWS Analytics
        checkSyncStatus();
    }

    init();

    const tabs = document.querySelectorAll('.nav-tab');
    const panels = document.querySelectorAll('.tab-panel');

    tabs.forEach(tab => {
        tab.addEventListener('click', function () {
            tabs.forEach(t => t.classList.remove('nav-tab-active'));
            this.classList.add('nav-tab-active');

            panels.forEach(panel => panel.classList.remove('active'));
            document.getElementById('tab-' + this.dataset.tab).classList.add('active');
        });
    });
});
