/**
 * Template Name: Inspinia - Admin & Dashboard Template
 * By (Author): WebAppLayers
 * Module/App (File Name): Plugins SweetAlerts
 */

const defaultButtonClasses = {
    confirmButton: "btn bg-primary text-white hover:bg-primary-hover mt-2",
    cancelButton: "btn bg-danger text-white hover:bg-danger-hover mt-2",
}

const successToastConfig = {
    icon: "success",
    text: "Saved successfully!",
    showConfirmButton: false,
    timer: 1500,
    buttonsStyling: false,
    customClass: { confirmButton: defaultButtonClasses.confirmButton },
}

// Show a basic alert
const showAlert = (options) => {
    Swal.fire({
        buttonsStyling: false,
        customClass: { confirmButton: defaultButtonClasses.confirmButton },
        ...options,
    })
}

const bindAlert = (id, options) => {
    const element = document.getElementById(id)
    if (element) {
        element.addEventListener("click", () => showAlert(options))
    }
}

const bindPositionalAlert = (id, position) => {
    const element = document.getElementById(id)
    if (element) {
        element.addEventListener("click", () => {
            Swal.fire({
                position,
                ...successToastConfig,
            })
        })
    }
}

// Basic Alert
bindAlert("sweetalert-basic", {
    title: "Simple Alert",
    text: "This is a basic SweetAlert dialog.",
})

// Title Alert
bindAlert("sweetalert-title", {
    title: "Notice",
    text: "This is a titled alert with additional details.",
    icon: "question",
    showCloseButton: true,
})

// Long Content Alert
bindAlert("sweetalert-longcontent", {
    imageUrl: "https://placehold.co/300x1000/1ab394/white",
    imageHeight: 1000,
    imageAlt: "Very tall content image",
    showCloseButton: true,
    customClass: {
        confirmButton: "btn bg-secondary text-white hover:bg-secondary-hover mt-2",
    },
})

// Confirm Button Alert
const confirmBtn = document.getElementById("sweetalert-confirm-button")
if (confirmBtn) {
    confirmBtn.addEventListener("click", () => {
        Swal.fire({
            title: "Confirm Deletion",
            text: "Are you sure you want to delete this item?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes, delete it!",
            showCloseButton: true,
            buttonsStyling: false,
            customClass: {
                confirmButton: "btn bg-primary text-white hover:bg-primary-hover me-2 mt-2",
                cancelButton: "btn bg-danger text-white hover:bg-danger-hover mt-2",
            },
        }).then((result) => {
            if (result.isConfirmed) {
                showAlert({
                    title: "Deleted!",
                    text: "Your item has been successfully removed.",
                    icon: "success",
                })
            }
        })
    })
}

// Cancel Button Alert with Params
const paramsBtn = document.getElementById("sweetalert-params")
if (paramsBtn) {
    paramsBtn.addEventListener("click", () => {
        Swal.fire({
            title: "Delete File?",
            text: "This action cannot be undone!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Delete",
            cancelButtonText: "Cancel",
            showCloseButton: true,
            buttonsStyling: false,
            customClass: {
                confirmButton: defaultButtonClasses.confirmButton + " me-2",
                cancelButton: defaultButtonClasses.cancelButton,
            },
        }).then((result) => {
            if (result.isConfirmed) {
                showAlert({
                    title: "Deleted!",
                    text: "The file has been deleted.",
                    icon: "success",
                })
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                showAlert({
                    title: "Action Cancelled",
                    text: "Your file is safe.",
                    icon: "error",
                })
            }
        })
    })
}

// Image Alert
bindAlert("sweetalert-image", {
    title: "Custom Branding",
    text: "This alert includes a logo.",
    imageUrl: "/images/logo-sm.png",
    imageHeight: 40,
    showCloseButton: true,
})

// Auto-Close Alert
const closeButton = document.getElementById("sweetalert-close")
if (closeButton) {
    closeButton.addEventListener("click", () => {
        let timerInterval
        Swal.fire({
            title: "Auto Dismiss",
            html: "Closing in <b></b> seconds...",
            timer: 2000,
            timerProgressBar: true,
            showCloseButton: true,
            didOpen: () => {
                Swal.showLoading()
                timerInterval = setInterval(() => {
                    const b = Swal.getHtmlContainer()?.querySelector("b")
                    if (b) {
                        b.textContent = Math.ceil(Swal.getTimerLeft() / 1000)
                    }
                }, 100)
            },
            willClose: () => clearInterval(timerInterval),
        }).then((result) => {
            if (result.dismiss === Swal.DismissReason.timer) {
                console.log("Alert closed by timer")
            }
        })
    })
}

// Position Alerts
bindPositionalAlert("position-top-start", "top-start")
bindPositionalAlert("position-top-end", "top-end")
bindPositionalAlert("position-bottom-start", "bottom-start")
bindPositionalAlert("position-bottom-end", "bottom-end")

// Info Alert
bindAlert("sweetalert-info", {
    text: "This is an informational message to keep you updated.",
    icon: "info",
    confirmButtonText: "Understood",
    customClass: {
        confirmButton: "btn bg-info text-white hover:bg-info-hover",
    },
})

// Warning Alert
bindAlert("sweetalert-warning", {
    text: "Heads up! Something might require your attention.",
    icon: "warning",
    confirmButtonText: "Got it",
    customClass: {
        confirmButton: "btn bg-warning text-white hover:bg-warning-hover",
    },
})

// Error Alert
bindAlert("sweetalert-error", {
    text: "An unexpected error occurred. Please try again.",
    icon: "error",
    confirmButtonText: "Dismiss",
    customClass: {
        confirmButton: "btn bg-danger text-white hover:bg-danger-hover",
    },
})

// Success Alert
bindAlert("sweetalert-success", {
    text: "Action completed successfully!",
    icon: "success",
    confirmButtonText: "Great!",
    customClass: {
        confirmButton: "btn bg-success text-white hover:bg-success-hover",
    },
})

// Question Alert
bindAlert("sweetalert-question", {
    text: "Do you need more information about this feature?",
    icon: "question",
    confirmButtonText: "Yes, please",
})

// HTML Alert
bindAlert("custom-html-alert", {
    title: "<i>HTML</i> <u>Alert</u>",
    html: 'Use <b>bold</b>, <a href="#">links</a>, and other HTML here.',
    icon: "info",
    showCloseButton: true,
    showCancelButton: true,
    confirmButtonText: '<svg  xmlns="http://www.w3.org/2000/svg"  width="18"  height="18"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="me-1 align-middle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 11v8a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1v-7a1 1 0 0 1 1 -1h3a4 4 0 0 0 4 -4v-1a2 2 0 0 1 4 0v5h3a2 2 0 0 1 2 2l-1 5a2 3 0 0 1 -2 2h-7a3 3 0 0 1 -3 -3" /></svg> Like it!',
    cancelButtonText: '<svg  xmlns="http://www.w3.org/2000/svg"  width="18"  height="18"  viewBox="0 0 24 24"  fill="currentColor"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M13 21.008a3 3 0 0 0 2.995 -2.823l.005 -.177v-4h2a3 3 0 0 0 2.98 -2.65l.015 -.173l.005 -.177l-.02 -.196l-1.006 -5.032c-.381 -1.625 -1.502 -2.796 -2.81 -2.78l-.164 .008h-8a1 1 0 0 0 -.993 .884l-.007 .116l.001 9.536a1 1 0 0 0 .5 .866a2.998 2.998 0 0 1 1.492 2.396l.007 .202v1a3 3 0 0 0 3 3z" /><path d="M5 14.008a1 1 0 0 0 .993 -.883l.007 -.117v-9a1 1 0 0 0 -.883 -.993l-.117 -.007h-1a2 2 0 0 0 -1.995 1.852l-.005 .15v7a2 2 0 0 0 1.85 1.994l.15 .005h1z" /></svg>',
    customClass: {
        confirmButton: "btn bg-success text-white hover:bg-success-hover me-2 flex! items-center",
        cancelButton: "btn bg-danger text-white hover:bg-danger-hover",
    },
})

// Custom Styling Alert
bindAlert("custom-padding-width-alert", {
    title: '<h2 class="text-white">Custom Design.</h2>',
    html: '<p class="text-white">This alert has custom size, padding, and background.</p>',
    width: 600,
    padding: "100px",
    color: "#fff",
    background: "url(/images/stock/small-2.jpg) no-repeat center",
    customClass: {
        confirmButton: "btn bg-primary text-white hover:bg-primary-hover",
    },
})

// Ajax Request Alert
const ajaxBtn = document.getElementById("ajax-alert")
if (ajaxBtn) {
    ajaxBtn.addEventListener("click", () => {
        Swal.fire({
            title: "<h4>Enter Your Email</h4>",
            input: "email",
            inputPlaceholder: "Enter your email address",
            showCancelButton: true,
            confirmButtonText: "Submit",
            showLoaderOnConfirm: true,
            showCloseButton: true,
            buttonsStyling: false,
            customClass: {
                confirmButton: "btn bg-primary text-white hover:bg-primary-hover me-2",
                cancelButton: "btn bg-danger text-white hover:bg-danger-hover",
            },
            preConfirm: (email) => {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        if (email === "taken@example.com") {
                            reject("This email is already registered.")
                        } else {
                            resolve(email)
                        }
                    }, 1500)
                })
            },
            allowOutsideClick: false,
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    icon: "success",
                    title: "Submitted!",
                    html: `Your email: ${result.value}`,
                    buttonsStyling: false,
                    customClass: {
                        confirmButton: "btn bg-primary text-white hover:bg-primary-hover",
                    },
                })
            }
        })
    })
}
