/**
 * QR Profile Admin CMS — Core JS
 * Requires: Bootstrap 5, jQuery 3.x, SweetAlert2
 */

'use strict';

// ================================================================
// SIDEBAR TOGGLE
// ================================================================
const sidebar      = document.getElementById('sidebar');
const mainWrapper  = document.getElementById('mainWrapper');
const toggleBtn    = document.getElementById('sidebarToggle');
const closeBtn     = document.getElementById('sidebarCloseBtn');
const SIDEBAR_KEY  = 'qr_sidebar_collapsed';

function isMobile() {
    return window.innerWidth < 992;
}

// Restore desktop sidebar state
if (! isMobile() && localStorage.getItem(SIDEBAR_KEY) === '1') {
    sidebar && sidebar.classList.add('collapsed');
}

if (toggleBtn) {
    toggleBtn.addEventListener('click', function () {
        if (isMobile()) {
            sidebar && sidebar.classList.toggle('show');
            toggleBackdrop(sidebar.classList.contains('show'));
        } else {
            sidebar && sidebar.classList.toggle('collapsed');
            const isCollapsed = sidebar.classList.contains('collapsed');
            localStorage.setItem(SIDEBAR_KEY, isCollapsed ? '1' : '0');
        }
    });
}

if (closeBtn) {
    closeBtn.addEventListener('click', function () {
        sidebar && sidebar.classList.remove('show');
        toggleBackdrop(false);
    });
}

function toggleBackdrop(show) {
    let bd = document.querySelector('.sidebar-backdrop');
    if (show) {
        if (! bd) {
            bd = document.createElement('div');
            bd.className = 'sidebar-backdrop';
            document.body.appendChild(bd);
            bd.addEventListener('click', () => {
                sidebar.classList.remove('show');
                toggleBackdrop(false);
            });
        }
    } else {
        bd && bd.remove();
    }
}

// Close sidebar on resize to desktop
window.addEventListener('resize', function () {
    if (! isMobile()) {
        sidebar && sidebar.classList.remove('show');
        toggleBackdrop(false);
    }
});

// ================================================================
// AUTO-DISMISS ALERTS
// ================================================================
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.alert.alert-success, .alert.alert-info').forEach(function (el) {
        setTimeout(function () {
            const bsAlert = bootstrap.Alert.getOrCreateInstance(el);
            bsAlert && bsAlert.close();
        }, 5000);
    });
});

// ================================================================
// CSRF — jQuery AJAX setup (for future AJAX calls)
// ================================================================
$(document).ready(function () {
    const csrfToken = $('meta[name="csrf-token"]').attr('content');
    const csrfName  = $('meta[name="csrf-name"]').attr('content');

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                const data = {};
                data[csrfName] = csrfToken;
                settings.data = $.param(data) + (settings.data ? '&' + settings.data : '');
            }
        }
    });

    // ================================================================
    // CONFIRM DELETE — generic (for forms with data-confirm)
    // ================================================================
    $('[data-confirm]').on('click', function (e) {
        e.preventDefault();
        const msg  = $(this).data('confirm') || 'Are you sure?';
        const form = $(this).closest('form') || $($(this).data('form'));
        Swal.fire({
            title: msg,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            confirmButtonText: 'Yes, delete',
            cancelButtonText: 'Cancel',
        }).then(function (result) {
            if (result.isConfirmed) {
                form[0] && form[0].submit();
            }
        });
    });

    // ================================================================
    // TOGGLE STATUS badge click feedback
    // ================================================================
    $('form [name="is_active"]').on('change', function () {
        // Visual cue — handled by form submit
    });

    // ================================================================
    // File input — show filename
    // ================================================================
    $('input[type=file]').on('change', function () {
        const files  = this.files;
        const parent = $(this).closest('.input-file-wrap');
        if (parent.length && files.length) {
            const names = Array.from(files).map(f => f.name).join(', ');
            parent.find('.file-name-display').text(names);
        }
    });

    // ================================================================
    // Tooltip init
    // ================================================================
    const tooltipEls = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltipEls.forEach(el => new bootstrap.Tooltip(el, { trigger: 'hover' }));

    // ================================================================
    // Colour pickers sync hex display
    // ================================================================
    $('input[type=color]').on('input', function () {
        const label = $(this).closest('.col-6').find('.color-hex-display');
        label.length && label.text(this.value.toUpperCase());
    });
});

// ================================================================
// HELPER — log icon/badge classes used in dashboard
// ================================================================
window.logIconClass = function (action) {
    const map = {
        create: 'bg-success-subtle text-success',
        update: 'bg-primary-subtle text-primary',
        delete: 'bg-danger-subtle text-danger',
        login:  'bg-info-subtle text-info',
        logout: 'bg-secondary-subtle text-secondary',
    };
    return map[action] || 'bg-light text-muted';
};

window.logIcon = function (action) {
    const map = {
        create: 'bi-plus-circle',
        update: 'bi-pencil',
        delete: 'bi-trash',
        login:  'bi-box-arrow-in-right',
        logout: 'bi-box-arrow-right',
    };
    return map[action] || 'bi-activity';
};

window.time_ago = function (dateStr) {
    if (! dateStr) return '';
    const d    = new Date(dateStr);
    const now  = new Date();
    const diff = Math.floor((now - d) / 1000);
    if (diff < 60)    return diff + 's ago';
    if (diff < 3600)  return Math.floor(diff / 60) + 'm ago';
    if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
    return Math.floor(diff / 86400) + 'd ago';
};
