/**
 * SMS Logic V4 — Enhanced AJAX + AI + Toast Notifications
 */
(function () {
    'use strict';

    // ─── Toast Notification System ───
    window.showToast = function (message, type, duration) {
        type = type || 'info';
        duration = duration || 4000;

        var existing = document.querySelector('.toast-modern');
        if (existing) existing.remove();

        var toast = document.createElement('div');
        toast.className = 'toast-modern toast-' + type;
        toast.innerHTML = '<div style="display:flex;align-items:center;gap:10px;">' +
            '<i class="fe fe-' + (type === 'success' ? 'check-circle' : type === 'error' ? 'x-circle' : 'info') + '"></i>' +
            '<span>' + message + '</span>' +
            '<button onclick="this.parentElement.parentElement.remove()" style="background:none;border:none;color:#fff;font-size:1.2rem;cursor:pointer;margin-left:auto;">×</button>' +
            '</div>';
        document.body.appendChild(toast);

        setTimeout(function () {
            toast.style.animation = 'slideOutRight 0.3s ease forwards';
            setTimeout(function () { toast.remove(); }, 300);
        }, duration);
    };

    // ─── AJAX Form Submission ───
    document.addEventListener('DOMContentLoaded', function () {
        var forms = document.querySelectorAll('#sendSmsForm');

        forms.forEach(function (form) {
            form.addEventListener('submit', function (e) {
                e.preventDefault();

                var formData = new FormData(form);
                var submitBtn = form.querySelector('button[type="submit"]');
                var originalText = submitBtn.innerHTML;

                // Show loading
                submitBtn.innerHTML = '<span class="spinner-modern" style="width:16px;height:16px;border-width:2px;display:inline-block;vertical-align:middle;margin-right:8px;"></span>Sending...';
                submitBtn.disabled = true;

                fetch(form.action, {
                    method: 'POST',
                    body: formData
                })
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        if (data.status === 'success') {
                            showToast(data.message, 'success');
                            // Reset form
                            form.querySelector('#msgBody').value = '';
                            var templateSel = form.querySelector('#templateSelect');
                            if (templateSel) templateSel.selectedIndex = 0;
                            // Reset Select2
                            if (window.jQuery) {
                                jQuery('.select2-show-search').val(null).trigger('change');
                            }
                        } else {
                            showToast(data.message || 'Failed to send SMS', 'error', 6000);
                        }
                    })
                    .catch(function (err) {
                        showToast('Network error. Please try again.', 'error');
                    })
                    .finally(function () {
                        submitBtn.innerHTML = originalText;
                        submitBtn.disabled = false;
                    });
            });
        });

        // ─── SMS Character Counter ───
        var msgBody = document.getElementById('msgBody');
        if (msgBody) {
            msgBody.addEventListener('input', function () {
                updateSmsInfo(this.value);
            });
        }
    });

    function updateSmsInfo(text) {
        var len = text.length;
        var encoding = /[^\x00-\x7F]/.test(text) ? 'UTF-16' : 'GSM_7BIT';
        var singleLimit = encoding === 'UTF-16' ? 70 : 160;
        var multiLimit = encoding === 'UTF-16' ? 67 : 153;

        var parts = 1;
        if (len > singleLimit) {
            parts = Math.ceil(len / multiLimit);
        }
        var remaining = parts === 1 ? (singleLimit - len) : (parts * multiLimit - len);

        var el = function (id) { return document.getElementById(id); };
        if (el('sms-encoding')) el('sms-encoding').textContent = encoding;
        if (el('sms-count')) el('sms-count').textContent = len;
        if (el('sms-parts')) el('sms-parts').textContent = parts;
        if (el('sms-remaining')) el('sms-remaining').textContent = Math.max(0, remaining);
    }

    // ─── Animated Number Counter ───
    window.animateCounter = function (element, target, duration) {
        duration = duration || 1500;
        var start = 0;
        var startTime = null;

        function step(timestamp) {
            if (!startTime) startTime = timestamp;
            var progress = Math.min((timestamp - startTime) / duration, 1);
            var eased = 1 - Math.pow(1 - progress, 3); // easeOutCubic
            var current = Math.floor(eased * target);
            element.textContent = current.toLocaleString();
            if (progress < 1) requestAnimationFrame(step);
            else element.textContent = target.toLocaleString();
        }

        requestAnimationFrame(step);
    };

    // slideOutRight animation
    var style = document.createElement('style');
    style.textContent = '@keyframes slideOutRight{to{transform:translateX(120%);opacity:0;}}';
    document.head.appendChild(style);
})();
