document.addEventListener('alpine:init', () => {
    let $screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    Alpine.store('alert', {
        type: false,
        message: '',
    });

    Alpine.store('navigation', true);
    if ($screenWidth <= 1024) {
        Alpine.store('navigation', false);
    }
    Alpine.store('loading', false);
    Alpine.store('confirm', {
        show: false,
        subject: '',
        callback: ''
    });

    Alpine.store('modal', {
        show: false,
        title: '',
        content: ''
    });

    Alpine.store('alert', {
        show: false,
        type: '',
        message: '',
        info(message) {
            this.show = true;
            this.type = 'info';
            this.message = message;
        },
        success(message) {
            this.show = true;
            this.type = 'success';
            this.message = message;
        },
        warning(message) {
            this.show = true;
            this.type = 'warning';
            this.message = message;
        },
        danger(message) {
            this.show = true;
            this.type = 'danger';
            this.message = message;
        },
        hide() {
            this.show = false;
            this.message = '';
            this.type = '';
            console.log('spadadad');
        }
    });

    Alpine.effect(() => {
        const alert = Alpine.store('alert').show;
        if (alert) {
            setTimeout(function() {
                Alpine.store('alert').show = false;
            }, 5000);
        }
    })

    Alpine.magic('modal', () => {
        return (title, content) => {
            Alpine.store('modal', {
                show: true,
                title: title,
                content: content
            });
        }
    });


    Alpine.magic('copy', () => subject => {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(subject);
        } else {
            let textArea = document.createElement("textarea");
            textArea.value = subject;
            textArea.style.position = "fixed";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            document.execCommand('copy');
            textArea.remove();
        }

        Alpine.store('alert').success('<span class="font-light italic inline">"' + subject + '"</span> <span class="inline ml-2">has copied</span>');
    });

    Alpine.magic('confirm', (el) => {
        return (subject, callback) => {
            Alpine.store('confirm', {
                show: true,
                subject: subject,
                callback: callback
            });
        }
    });

    Alpine.magic('post', () => {
        return function(url, body) {
            return fetch(url, {
                    method: 'post',
                    body: JSON.stringify(body),
                    headers: {
                        'Content-Type': 'application/json'
                    },
                })
                .then(response => {
                    if (response.status >= 200 && response.status <= 299) {
                        return response.json();
                    } else {
                        return response.json().then(error => {
                            throw error;
                        });
                    }
                })
                .then(response => {
                    if ('message' in response) {
                        Alpine.store('alert').success(response.message);
                    }
                    return response
                })
                .catch((error) => {
                    if ('message' in error) {
                        Alpine.store('alert').warning(error.message);
                    }
                    throw error;
                });
        };
    });

    Alpine.magic('upload', () => {
        return function(url, body) {

            console.log(body);

            const formData = new FormData()
            formData.append('file', body.file);
            formData.append('nonce', body.nonce);
            formData.append('action', body.action);

            return fetch(url, {
                    method: 'post',
                    body: formData,
                    // headers: {
                    //     'Content-Type': 'multipart/form-data'
                    // },
                })
                .then(response => {
                    if (response.status >= 200 && response.status <= 299) {
                        return response.json();
                    } else {
                        return response.json().then(error => {
                            throw error;
                        });
                    }
                })
                .then(response => {
                    if ('message' in response) {
                        Alpine.store('alert').success(response.message);
                    }
                    return response
                })
                .catch((error) => {
                    if ('message' in error) {
                        Alpine.store('alert').warning(error.message);
                    }
                    throw error;
                });
        };
    });

    Alpine.magic('get', () => {
        return (url, data) => {
            return fetch(url, {
                    method: 'get',
                    data: data
                })
                .then(response => {
                    if (response.status >= 200 && response.status <= 299) {
                        return response.text();
                    } else {
                        return response.json().then(error => {
                            throw error;
                        });
                    }
                })
                .then(response => {
                    return response
                })
                .catch((error) => {
                    if ('message' in error) {
                        Alpine.store('alert').success(response.message);
                    }
                    throw error;
                });
        };
    });

    Alpine.directive('countdown', (el, { expression }, { evaluate }) => {
        let countDownDate = new Date(evaluate(expression)).getTime();

        // Update the count down every 1 second
        let x = setInterval(function() {

            // Get today's date and time
            let now = new Date().getTime();

            // Find the distance between now and the count down date
            let distance = countDownDate - now;

            // Time calculations for days, hours, minutes and seconds
            let days = Math.floor(distance / (1000 * 60 * 60 * 24));
            let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            let seconds = Math.floor((distance % (1000 * 60)) / 1000);

            days = ('0' + parseInt(days)).slice(-2);
            hours = ('0' + parseInt(hours)).slice(-2);
            minutes = ('0' + parseInt(minutes)).slice(-2);
            seconds = ('0' + parseInt(seconds)).slice(-2);

            // Output the result in an element with id="demo"
            el.textContent = days + ' : ' + hours + ' : ' + minutes + ' : ' + seconds;

            // If the count down is over, write some text 
            if (distance < 0) {
                clearInterval(x);
                el.textContent = '0';
            }
        }, 1000);

    });

    Alpine.magic('chartline', () => {
        return (id, label, datasets) => {

            try {

                if (!window.Chart) {
                    throw new Error('[Salesloo Magic Helpers] Chart js is required for the salesloo magic helpers chartline to function correctly.');
                }

                new Chart(id, {
                    type: "line",
                    data: {
                        labels: label,
                        datasets: datasets,
                    },
                    layout: {
                        padding: {
                            right: 10
                        }
                    },
                    options: {
                        legend: {
                            display: true,
                            labels: {
                                fontColor: '#ffffff'
                            }
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    fontColor: "rgba(255, 255, 255, 1)",
                                },
                                gridLines: {
                                    display: false,
                                },
                            }],
                            xAxes: [{
                                ticks: {
                                    fontColor: "rgba(255, 255, 255, 1)",
                                },
                                gridLines: {
                                    color: "rgba(255, 255, 255, .2)",
                                    borderDash: [5, 5],
                                    zeroLineColor: "rgba(255, 255, 255, .2)",
                                    zeroLineBorderDash: [5, 5]
                                },
                            }]
                        }
                    }
                });
            } catch (error) {
                console.warn(error);
            }

        }
    });

    Alpine.magic('date', () => {
        return (element, options) => {

            try {
                if (!window.flatpickr) {
                    throw new Error('[Salesloo Magic Helpers] flatpickr js is required for the salesloo magic helpers date picker to function correctly.');
                }
                flatpickr(element, options);
            } catch (error) {
                console.warn(error);
            }
        }
    });

    Alpine.magic('chartdoughnut', () => {
        return (id, label, datasets) => {

            try {

                if (!window.Chart) {
                    throw new Error('[Salesloo Magic Helpers] Chart js is required for the salesloo magic helpers chartpie to function correctly.');
                }

                new Chart(id, {
                    type: "doughnut",
                    data: {
                        labels: label,
                        datasets: datasets,
                    },
                    options: {
                        legend: {
                            display: true,
                            position: 'bottom',
                            labels: {
                                boxWidth: 20,
                                textAlign: 'left'
                            }
                        },
                    }
                });
            } catch (error) {
                console.warn(error);
            }

        }
    })
})