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


    function setStepOne(){
            $(".config-inputs").each(function () {
                if (!$(this).hasClass("d-none")) {
                    $(this).addClass("d-none");
                }

                if($("#service_provider").val() === "google" && $(this).hasClass("google-inputs")) {
                    $(this).removeClass("d-none");
                }

                if(($("#service_provider").val() === "aws" || $("#service_provider").val() === "digitalocean" || $("#service_provider").val() === "cloudflare" ) && $(this).hasClass("aws-sdk-inputs")) {
                    $(this).removeClass("d-none");
                }

                if($("#service_provider").val() === "cloudflare" && $(this).hasClass("cloudflare-inputs")) {
                    $(this).removeClass("d-none");

                }

            });

    }
    setStepOne()


    jQuery("#service_provider").change(function () {
        setStepOne()
    });

    // Localized strings from PHP
    const strings = ajax_object.strings;

    // AWS Regions
    const aws_regions = [
        { "name": strings.aws_region_us_east_1, "code": "us-east-1" },
        { "name": strings.aws_region_us_east_2, "code": "us-east-2" },
        { "name": strings.aws_region_us_west_1, "code": "us-west-1" },
        { "name": strings.aws_region_us_west_2, "code": "us-west-2" },
        { "name": strings.aws_region_ca_central_1, "code": "ca-central-1" },
        { "name": strings.aws_region_eu_west_1, "code": "eu-west-1" },
        { "name": strings.aws_region_eu_west_2, "code": "eu-west-2" },
        { "name": strings.aws_region_eu_west_3, "code": "eu-west-3" },
        { "name": strings.aws_region_eu_central_1, "code": "eu-central-1" },
        { "name": strings.aws_region_eu_south_1, "code": "eu-south-1" },
        { "name": strings.aws_region_eu_south_2, "code": "eu-south-2" },
        { "name": strings.aws_region_me_south_1, "code": "me-south-1" },
        { "name": strings.aws_region_me_central_1, "code": "me-central-1" },
        { "name": strings.aws_region_af_south_1, "code": "af-south-1" },
        { "name": strings.aws_region_ap_northeast_1, "code": "ap-northeast-1" },
        { "name": strings.aws_region_ap_northeast_2, "code": "ap-northeast-2" },
        { "name": strings.aws_region_ap_northeast_3, "code": "ap-northeast-3" },
        { "name": strings.aws_region_ap_southeast_1, "code": "ap-southeast-1" },
        { "name": strings.aws_region_ap_southeast_2, "code": "ap-southeast-2" },
        { "name": strings.aws_region_ap_southeast_3, "code": "ap-southeast-3" },
        { "name": strings.aws_region_ap_south_1, "code": "ap-south-1" },
        { "name": strings.aws_region_ap_south_2, "code": "ap-south-2" },
        { "name": strings.aws_region_sa_east_1, "code": "sa-east-1" },
        { "name": strings.aws_region_cn_north_1, "code": "cn-north-1" },
        { "name": strings.aws_region_cn_northwest_1, "code": "cn-northwest-1" },
        { "name": strings.aws_region_us_gov_east_1, "code": "us-gov-east-1" },
        { "name": strings.aws_region_us_gov_west_1, "code": "us-gov-west-1" }
    ];

    // DigitalOcean Regions
    const digitalocean_region = [
        { "name": strings.digitalocean_region_nyc1, "slug": "nyc1" },
        { "name": strings.digitalocean_region_nyc2, "slug": "nyc2" },
        { "name": strings.digitalocean_region_nyc3, "slug": "nyc3" },
        { "name": strings.digitalocean_region_ams3, "slug": "ams3" },
        { "name": strings.digitalocean_region_sfo2, "slug": "sfo2" },
        { "name": strings.digitalocean_region_sfo3, "slug": "sfo3" },
        { "name": strings.digitalocean_region_sgp1, "slug": "sgp1" },
        { "name": strings.digitalocean_region_lon1, "slug": "lon1" },
        { "name": strings.digitalocean_region_fra1, "slug": "fra1" },
        { "name": strings.digitalocean_region_tor1, "slug": "tor1" }
    ];

    $("#generate-certificate").on("click", function () {
        const domain = $("#custom-domain").val();
        toggleAttachUrlButton(false);

        if (interval !== undefined) {
            clearInterval(interval);
        }

        if (!domain) {
            alert(strings.enter_domain); // Localized string
            return;
        }

        $("#records").html("");

        $.post(ajax_object.ajax_url, {
            action: 'generate_ssl_certificate',
            domain: domain,
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                const certificateArn = response.data.certificateArn;
                const records = response.data.records;

                alert(strings.certificate_generated); // Localized string

                if (records && records.length > 0) {
                    create_records({ records, certificateArn });
                } else {
                    $("#records").html(`<p>${strings.no_dns_records}</p>`); // Localized string
                }
            } else {
                alert(strings.certificate_generation_failed + ': ' + response.data); // Localized string
                console.error(strings.certificate_generation_failed, response.data);
            }
        }).fail(function () {
            alert(strings.certificate_generation_error); // Localized string
        });
    });

    let interval;
    let certificate = document.getElementById("initial_certificates");
    if (certificate) {
        let data = JSON.parse(document.getElementById("initial_certificates").innerHTML);
        if (data["certificate_arn"] === "") {
            return;
        }
        create_records({ records: data["records"], certificateArn: data["certificate_arn"] });
    }

    function create_records({ records, certificateArn }) {
        let html = `<h3>${strings.dns_validation_records}</h3><ul>`;
        records.forEach((record, index) => {
            let status = "";
            if (!record.systemGenerated) {
                status = `<span id="status-${index}" style="color: orange;">${strings.checking}</span>`;
            }
            html += `<li id="record-${index}">
                                <strong>${strings.domain}</strong>: ${record.DomainName}<br>
                                <strong>${strings.type}</strong>: ${record.Type}<br>
                                <strong>${strings.name}</strong>: ${record.Name}<br>
                                <strong>${strings.value}</strong>: ${record.Value}<br>
                                ${status}
                             </li>`;
        });
        html += "</ul>";
        $("#records").html(html);
        if (certificateArn !== "") {
            checkDNSRecord(certificateArn);
        }
    }

    function checkDNSRecord(certificateArn) {
        interval = setInterval(function () {
            toggleAttachUrlButton(false);
            $.post(ajax_object.ajax_url, {
                action: 'check_dns_record',
                certificateArn: certificateArn,
            }, function (response) {
                if (response.success) {
                    const records = response.data.records;

                    records.forEach((record, index) => {
                        const status = record.ValidationStatus === "SUCCESS"
                            ? `<span style="color: green;">${strings.verified}</span>`
                            : `<span style="color: orange;">${strings.pending_validation}</span>`;

                        $(`#status-${index}`).html(status);
                    });

                    if (response.data.verified) {
                        alert(strings.all_dns_verified); // Localized string
                        toggleAttachUrlButton(true);
                        clearInterval(interval);
                    }
                } else {
                    if (response.data.error) {
                        $("#records").html("");
                        alert(strings.error + ': ' + response.data.message);
                        return;
                    }
                    alert(strings.error + ': ' + response.data);
                    clearInterval(interval);
                }
            }).fail(function () {
                alert(strings.dns_check_error); // Localized string
                clearInterval(interval);
            });
        }, 5000);
    }

    function toggleAttachUrlButton(enable) {
        $("#cloudfront-attachment-button").attr('disabled', !enable);
    }

    $("#cloudfront-attachment-button").on("click", function () {
        $.post(ajax_object.ajax_url, {
            action: 'attach_to_cloudfront',
            nonce: ajax_object.nonce,
        }, function (response) {
            if (response.success) {
                alert(strings.certificate_attached); // Localized string
            } else {
                alert(strings.attachment_failed + ': ' + response.data); // Localized string
            }
        }).fail(function () {
            alert(strings.attachment_error); // Localized string
        });
    });

    $('input[name="bucket_type"]').on('change', function () {
        const bucketType = $(this).val();
        if (bucketType === 'existing') {
            $('#existing-bucket-options').show();
            $('#new-bucket-options').hide();
        } else {
            $('#existing-bucket-options').hide();
            $('#new-bucket-options').show();
        }
    });

    function goToStep(step) {
        $('.wizard-step').hide();
        $('#wizard-step-' + step).fadeIn();

        $('.stepper li').removeClass('active');
        $('#step-' + step + '-indicator').addClass('active');
    }



    $('#step-1-next').on('click', function () {
        const serviceProvider = $('#service_provider').val();
        const iamKey = $('#aws_iam_key').val();
        const iamSecret = $('#aws_iam_secret').val();
        $("#new_bucket_region").html("");
        let html = "";


        if(serviceProvider === "google" || serviceProvider === "cloudflare"){
            $("#region-selector").hide()
        }else{
            $("#region-selector").show()
        }


        let regions = (serviceProvider.trim() === "aws") ? aws_regions : digitalocean_region;

        regions.forEach((value) => {
            html += `<option value="${value.slug || value.code}">${value.name}</option>`;
        });

        $("#new_bucket_region").append(html);

        if (!iamKey || !iamSecret) {
            alert(strings.iam_required); // Localized string
            return;
        }

        goToStep(2);

        if(serviceProvider === "cloudflare"){
            $("#new-bucket-radio").hide()
        }else {
            $("#new-bucket-radio").show()
        }
        loadBuckets(iamKey, iamSecret, serviceProvider);
    });

    // Step 2: Validate bucket selection/creation and move to the next step
    $('#step-2-next').on('click', function () {
        const bucketType = $('input[name="bucket_type"]:checked').val();
        const bucketName = bucketType === 'existing' ? $('#aws_bucket_list').val() : $('#new_bucket_name').val();

        if (!bucketName) {
            alert(strings.bucket_required); // Localized string
            return;
        }


        goToStep(3);
        if($(".service_provider").val() !== "aws") {
            $("#use-cloudfront-no").click();
        }
    });

    // Back button for Step 2
    $('#step-2-back').on('click', function () {
        goToStep(1);
    });

    // Back button for Step 3
    $('#step-3-back').on('click', function () {
        goToStep(2);
    });

    // Step 3: Save the configuration based on CloudFront selection
    $('#use-cloudfront-yes, #use-cloudfront-no').on('click', function () {
        const useCloudFront = $(this).attr('id') === 'use-cloudfront-yes';
        saveConfiguration(useCloudFront);
    });

    // Load existing buckets from AWS
    function loadBuckets(iamKey, iamSecret, serviceProvider) {
        $('#aws_bucket_list').empty().append(`<option>${strings.loading_buckets}</option>`); // Localized string


        function resHandle (response) {
            if (response.success) {
                const bucketList = $('#aws_bucket_list');
                bucketList.empty();

                response.data.buckets.forEach(bucket => {
                    bucketList.append(`<option value="${bucket}">${bucket}</option>`);
                });
            } else {
                alert(strings.load_buckets_failed); // Localized string
                console.error(strings.load_buckets_failed, response.data);
            }
        }

        var formData = new FormData();
        formData.append('action', 'list_s3_buckets');
        formData.append('service_provider', serviceProvider);


        formData.append('nonce', ajax_object.nonce);


        if( serviceProvider === "google"){
            formData.append('service_json', $('#service-json')[0].files[0]);
            formData.append('service_json', $('#service-json')[0].files[0]);
            formData.append('service_json', $('#service-json')[0].files[0]);
        }


        if( serviceProvider === "cloudflare"){
            let endpoint =  $("#cloudflare-endpoint").val();
            formData.append('cloudflare_endpoint',endpoint);
            formData.append('iam_key',iamKey);
            formData.append('iam_secret',iamSecret);
        }

        if(serviceProvider === "google" || serviceProvider === "cloudflare"){
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: resHandle,
                error: function(response) {
                    $('#upload-message').html('<p style="color:red;">' + response.responseJSON.data.message + '</p>');
                }
            });
            return;
        }
        console.log('here')


        $.post(ajax_object.ajax_url, {
            action: 'list_s3_buckets',
            nonce: ajax_object.nonce,
            iam_key: iamKey,
            iam_secret: iamSecret,
            service_provider: serviceProvider
        }, resHandle).fail(function () {
            alert(strings.load_buckets_error); // Localized string
        });
    }

    // Save configuration to the server
    function saveConfiguration(useCloudFront) {
        const bucketType = $('input[name="bucket_type"]:checked').val();
        const iamKey = $('#aws_iam_key').val();
        const iamSecret = $('#aws_iam_secret').val();
        const bucketName = bucketType === 'existing' ? $('#aws_bucket_list').val().split("|")[0] : $('#new_bucket_name').val();
        const bucketRegion = bucketType === 'existing' ? $('#aws_bucket_list').val().split("|")[1] : $('#new_bucket_region').val();
        const serviceProvider = $('#service_provider').val();
        const cloudflareEndpoint =  $("#cloudflare-endpoint").val();
        const cloudflareUrl =  $("#cloudflare-url").val();

        if (!bucketName) {
            alert(strings.bucket_required); // Localized string
            return;
        }

        const data = {
            action: 'configure_aws',
            nonce: ajax_object.nonce,
            iam_key: iamKey,
            iam_secret: iamSecret,
            bucket_type: bucketType,
            bucket_name: bucketName,
            bucket_region: bucketRegion,
            use_cloudfront: useCloudFront,
            service_provider: serviceProvider,
            cloudflare_endpoint: cloudflareEndpoint,
            cloudflare_url: cloudflareUrl
        };

        $.post(ajax_object.ajax_url, data, function (response) {
            if (response.success) {
                alert(strings.configuration_saved); // Localized string
                goToStep('final');
            } else {
                alert(strings.configuration_failed + ': ' + response.data); // Localized string
                console.error(strings.configuration_failed, response.data);
            }
        }).fail(function () {
            alert(strings.load_buckets_error); // Localized string
        });
    }

    // Hide new bucket options by default
    $('#new-bucket-options').hide();

    // Tabs navigation
    const tabs = document.querySelectorAll('.tab-button');
    const panels = document.querySelectorAll('.tab-panel');

    tabs.forEach(tab => {
        tab.addEventListener('click', function () {
            // Remove active class from all tabs
            tabs.forEach(t => t.classList.remove('active'));
            // Add active class to the clicked tab
            this.classList.add('active');

            // Hide all tab panels
            panels.forEach(panel => panel.classList.remove('active'));
            // Show the corresponding tab panel
            const targetPanel = document.querySelector(`#tab-${this.dataset.tab}`);
            if (targetPanel) {
                targetPanel.classList.add('active');
            }
        });
    });
});