/* ════════════════════════════════════════════════════════════
   THE CLUB ERP — Core JavaScript (Vanilla ES6+)
   Premium UI interactions, animations, and utilities.
   ════════════════════════════════════════════════════════════ */

// ── CSRF Token ──
function getCsrfToken() {
    const meta = document.querySelector('meta[name="csrf-token"]');
    return meta ? meta.getAttribute('content') : '';
}

// ── AJAX Helper ──
async function ajax(method, url, data = null, options = {}) {
    const headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': getCsrfToken(),
    };

    const config = { method: method.toUpperCase(), headers };

    if (data) {
        if (data instanceof FormData) {
            config.body = data;
        } else {
            headers['Content-Type'] = 'application/json';
            config.body = JSON.stringify(data);
        }
    }

    config.headers = headers;

    try {
        const response = await fetch(url, config);
        const contentType = response.headers.get('Content-Type') || '';

        let result;
        if (contentType.includes('json')) {
            result = await response.json();
        } else {
            result = await response.text();
        }

        if (!response.ok) {
            if (response.status === 419) {
                toast('انتهت صلاحية الجلسة. يرجى إعادة تحميل الصفحة.', 'error');
                return null;
            }
            if (response.status === 422 && result.errors) {
                showFormErrors(result.errors);
            }
            if (!options.silent) {
                toast(result.message || result.error || 'حدث خطأ', 'error');
            }
            return null;
        }

        return result;
    } catch (err) {
        if (!options.silent) {
            toast('خطأ في الاتصال بالخادم', 'error');
        }
        console.error('AJAX Error:', err);
        return null;
    }
}

// ── Toast Notifications (Upgraded with icons & animations) ──
function toast(message, type = 'info', duration = 5000) {
    const container = document.getElementById('toast-container');
    if (!container) return;

    const iconSvg = {
        info: '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>',
        success: '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
        error: '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
        warning: '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
    };

    const el = document.createElement('div');
    el.className = `toast toast-${type}`;
    el.innerHTML = `
        <span class="toast-icon">${iconSvg[type] || iconSvg.info}</span>
        <span>${escapeHtml(message)}</span>
        <button class="toast-close" onclick="dismissToast(this.parentElement)">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>`;
    container.appendChild(el);

    if (duration > 0) {
        setTimeout(() => dismissToast(el), duration);
    }
}

function dismissToast(el) {
    if (!el || !el.parentElement) return;
    el.classList.add('removing');
    el.addEventListener('animationend', () => el.remove(), { once: true });
}

// ── Modal System (Upgraded with animations) ──
function openModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        // Re-init icons inside modal
        if (window.lucide) lucide.createIcons({ nodes: [modal] });
    }
}

function closeModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.style.animation = 'overlayFadeIn 200ms ease reverse forwards';
        const inner = modal.querySelector('.modal');
        if (inner) {
            inner.style.animation = 'modalScaleIn 250ms cubic-bezier(0.16, 1, 0.3, 1) reverse forwards';
        }
        setTimeout(() => {
            modal.style.display = 'none';
            modal.style.animation = '';
            if (inner) inner.style.animation = '';
            document.body.style.overflow = '';
        }, 250);
    }
}

function confirmModal(title, message, onConfirm) {
    const id = 'confirm-modal-' + Date.now();
    const html = `
        <div class="modal-overlay" id="${id}" style="display:flex;">
            <div class="modal modal-small">
                <div class="modal-header">
                    <h3 class="modal-title">${escapeHtml(title)}</h3>
                    <button class="modal-close" onclick="closeModal('${id}');setTimeout(function(){var e=document.getElementById('${id}');if(e)e.remove();},300);">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    </button>
                </div>
                <div class="modal-body"><p style="color:var(--text-secondary);line-height:1.8;">${escapeHtml(message)}</p></div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal('${id}');setTimeout(function(){var e=document.getElementById('${id}');if(e)e.remove();},300);">إلغاء</button>
                    <button class="btn btn-danger" id="${id}-confirm">تأكيد</button>
                </div>
            </div>
        </div>`;
    document.body.insertAdjacentHTML('beforeend', html);
    document.body.style.overflow = 'hidden';

    document.getElementById(`${id}-confirm`).addEventListener('click', function() {
        closeModal(id);
        setTimeout(function() {
            var e = document.getElementById(id);
            if (e) e.remove();
        }, 300);
        onConfirm();
    });
}

// ── Sidebar Toggle ──
// Note: toggleSidebar() and toggleSubmenu() are defined in main.php layout
// so they have access to sidebar-specific DOM elements and run after the sidebar renders.

// ── National ID Parser ──
function initNationalIdParser(inputId, config = {}) {
    const input = document.getElementById(inputId);
    if (!input) return;

    input.addEventListener('input', function() {
        this.value = this.value.replace(/\D/g, '').substring(0, 14);
        if (this.value.length === 14) {
            parseNid(this.value, config);
        }
    });
}

async function parseNid(nid, config = {}) {
    const result = await ajax('POST', '/api/members/parse-nid', { national_id: nid }, { silent: true });
    if (result && result.success) {
        const data = result.data;
        const map = config.fieldMap || {
            date_of_birth: 'field_date_of_birth',
            age_years: 'field_age_years',
            gender: 'field_gender',
            governorate_code: 'field_governorate_code',
        };
        for (const [key, fieldId] of Object.entries(map)) {
            const el = document.getElementById(fieldId);
            if (el && data[key] !== undefined) {
                el.value = data[key];
                el.setAttribute('readonly', 'readonly');
                el.style.backgroundColor = 'var(--surface-bg)';
                // Brief highlight animation
                el.style.borderColor = 'var(--success)';
                el.style.boxShadow = '0 0 0 3px rgba(5, 150, 105, 0.1)';
                setTimeout(() => {
                    el.style.borderColor = '';
                    el.style.boxShadow = '';
                }, 2000);
            }
        }
    }
}

// ── Form Utilities ──
function showFormErrors(errors) {
    document.querySelectorAll('.form-error').forEach(el => el.remove());
    document.querySelectorAll('.has-error').forEach(el => el.classList.remove('has-error'));

    for (const [field, messages] of Object.entries(errors)) {
        const input = document.querySelector(`[name="${field}"]`);
        if (input) {
            const group = input.closest('.form-group');
            if (group) group.classList.add('has-error');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'form-error';
            errorDiv.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg> ` + escapeHtml(Array.isArray(messages) ? messages[0] : messages);
            input.parentNode.insertBefore(errorDiv, input.nextSibling);
        }
    }
}

function initMoneyFormat(inputId) {
    const input = document.getElementById(inputId);
    if (!input) return;
    input.addEventListener('blur', function() {
        const num = parseFloat(this.value.replace(/,/g, ''));
        if (!isNaN(num)) {
            this.value = num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
    });
}

function initPhoneFormat(inputId) {
    const input = document.getElementById(inputId);
    if (!input) return;
    input.addEventListener('input', function() {
        this.value = this.value.replace(/\D/g, '').substring(0, 11);
    });
}

function disableFields(selector) {
    document.querySelectorAll(selector).forEach(el => {
        el.setAttribute('disabled', 'disabled');
        el.style.backgroundColor = 'var(--surface-bg)';
    });
}

function enableFields(selector) {
    document.querySelectorAll(selector).forEach(el => {
        el.removeAttribute('disabled');
        el.style.backgroundColor = '';
    });
}

function initConditionalVisibility(config) {
    for (const rule of config) {
        const trigger = document.querySelector(`[name="${rule.field}"]`);
        if (!trigger) continue;

        const check = () => {
            const val = trigger.value;
            const target = document.getElementById(rule.targetId) || document.querySelector(rule.targetSelector);
            if (!target) return;

            let show = false;
            if (rule.operator === 'eq') show = val === rule.value;
            else if (rule.operator === 'neq') show = val !== rule.value;
            else if (rule.operator === 'in') show = rule.value.includes(val);

            target.style.display = show ? '' : 'none';
        };

        trigger.addEventListener('change', check);
        trigger.addEventListener('input', check);
        check();
    }
}

// ── Print Helper ──
function printElement(elementId) {
    const el = document.getElementById(elementId);
    if (!el) return;
    const win = window.open('', '_blank');
    win.document.write('<html dir="rtl" lang="ar"><head><meta charset="utf-8">');
    win.document.write('<style>body{font-family:Cairo,sans-serif;padding:20px;}table{width:100%;border-collapse:collapse;}th,td{border:1px solid #ddd;padding:8px;text-align:right;}</style>');
    win.document.write('</head><body>');
    win.document.write(el.innerHTML);
    win.document.write('</body></html>');
    win.document.close();
    win.print();
}

// ── Tabs ──
function initTabs(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const links = container.querySelectorAll('.tab-link');
    const contents = container.querySelectorAll('.tab-content');

    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const target = this.dataset.tab;

            links.forEach(l => l.classList.remove('active'));
            contents.forEach(c => c.classList.remove('active'));

            this.classList.add('active');
            const panel = document.getElementById(target);
            if (panel) panel.classList.add('active');
        });
    });
}

// ── Button Ripple Effect ──
function addRipple(e) {
    const btn = e.currentTarget;
    const rect = btn.getBoundingClientRect();
    const ripple = document.createElement('span');
    ripple.className = 'btn-ripple';
    const size = Math.max(rect.width, rect.height);
    ripple.style.width = ripple.style.height = size + 'px';
    ripple.style.left = (e.clientX - rect.left - size / 2) + 'px';
    ripple.style.top = (e.clientY - rect.top - size / 2) + 'px';
    btn.appendChild(ripple);
    ripple.addEventListener('animationend', () => ripple.remove());
}

// ── Animated Counter ──
function animateCounter(element, target, duration = 800) {
    const start = parseInt(element.textContent) || 0;
    const startTime = performance.now();

    function update(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        // Ease out cubic
        const eased = 1 - Math.pow(1 - progress, 3);
        const current = Math.round(start + (target - start) * eased);
        element.textContent = current.toLocaleString('en-US');
        if (progress < 1) requestAnimationFrame(update);
    }

    requestAnimationFrame(update);
}

// ── DOMContentLoaded ──
document.addEventListener('DOMContentLoaded', function() {

    // Auto-dismiss alerts with slide-out
    document.querySelectorAll('[data-auto-dismiss]').forEach(el => {
        const ms = parseInt(el.dataset.autoDismiss) || 5000;
        setTimeout(() => {
            el.classList.add('dismissing');
            el.addEventListener('animationend', () => el.remove(), { once: true });
        }, ms);
    });

    // Close modals on overlay click
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal-overlay')) {
            const id = e.target.id;
            if (id) closeModal(id);
            else {
                e.target.style.display = 'none';
                document.body.style.overflow = '';
            }
        }
    });

    // Escape closes modals
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            document.querySelectorAll('.modal-overlay[style*="display: flex"], .modal-overlay[style*="display:flex"]').forEach(m => {
                if (m.id) closeModal(m.id);
                else {
                    m.style.display = 'none';
                    document.body.style.overflow = '';
                }
            });
        }
    });

    // Ctrl+S submit forms
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            const form = document.querySelector('form');
            if (form) form.submit();
        }
    });

    // Init NID parsers
    document.querySelectorAll('[data-nid-parser]').forEach(input => {
        initNationalIdParser(input.id);
    });

    // Add ripple effect to all buttons
    document.querySelectorAll('.btn').forEach(btn => {
        btn.addEventListener('click', addRipple);
    });

    // Animate stat values on page load
    document.querySelectorAll('.stats-card-value[data-count]').forEach(el => {
        const target = parseInt(el.dataset.count);
        if (!isNaN(target)) {
            el.textContent = '0';
            // Use IntersectionObserver for scroll-triggered animation
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        animateCounter(el, target);
                        observer.disconnect();
                    }
                });
            }, { threshold: 0.5 });
            observer.observe(el);
        }
    });

    // Initialize Lucide icons (for dynamically added content)
    if (window.lucide) {
        lucide.createIcons();
    }

    // Loading state for forms
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function() {
            const submitBtn = form.querySelector('button[type="submit"], input[type="submit"]');
            if (submitBtn && !submitBtn.classList.contains('loading')) {
                submitBtn.classList.add('loading');
                submitBtn.disabled = true;
            }
        });
    });

    // Smooth scroll reveal for cards
    const revealObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                revealObserver.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1, rootMargin: '0px 0px -40px 0px' });

    document.querySelectorAll('.card, .stats-card').forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(16px)';
        card.style.transition = 'opacity 0.5s cubic-bezier(0.16, 1, 0.3, 1), transform 0.5s cubic-bezier(0.16, 1, 0.3, 1)';
        revealObserver.observe(card);
    });
});

// ── Helpers ──
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Session timeout warning
(function() {
    const timeout = 30 * 60 * 1000;
    const warningBefore = 5 * 60 * 1000;
    let timer;

    function resetTimer() {
        clearTimeout(timer);
        timer = setTimeout(function() {
            toast('ستنتهي جلستك خلال 5 دقائق. يرجى حفظ عملك.', 'warning', 10000);
        }, timeout - warningBefore);
    }

    ['click', 'keydown', 'mousemove', 'scroll'].forEach(evt => {
        document.addEventListener(evt, resetTimer, { passive: true });
    });

    resetTimer();
})();
