@props([
    'id',
    'class' => '',
    'ajaxUrl' => null,
    'columns' => [],
    'order' => null,
    'columnDefs' => null,
    'pageLength' => 25,
    'responsive' => true,
    'serverSide' => null,
    'searchId' => null,
    'filterFormId' => null,
    'clearFiltersId' => null,
    'selectAllId' => null,
    'rowCheckboxClass' => 'row-checkbox',
    'dom' => null,
    'drawCallback' => null,
    'title' => null,         // Title for card header (matches sales report)
    'padding' => true,      // Padding p-6 around table (matches sales report)
])

<!-- DataTable Card Container -->
<div class="overflow-visible rounded-2xl border border-slate-200/80 bg-white shadow-soft dark:border-slate-800 dark:bg-slate-900">
    @if($title)
        <div class="flex items-center justify-between border-b border-slate-100 px-5 py-4 dark:border-slate-800">
            <h3 class="text-sm font-bold text-slate-900 dark:text-white">{{ $title }}</h3>
        </div>
    @endif
    
    <div class="{{ $padding ? 'p-6' : '' }}">
        <div class="{{ $responsive ? 'overflow-visible' : 'overflow-x-auto' }} rounded-2xl">
            <table id="{{ $id }}" class="dataTable {{ $class }} w-full">
                <thead>
                    <tr>
                        {{ $thead }}
                    </tr>
                </thead>
                <tbody>
                    {{ $slot }}
                </tbody>
            </table>
        </div>
    </div>
</div>


@once
    <!-- Core dependencies (loaded once per page) -->
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    @include('admin.partials.datatables-styles')
@endonce



<script>
// Shared action-menu behavior for responsive child rows and regular table rows.
window.toggleDropdown = window.toggleDropdown || function (id) {
    const target = document.getElementById('dropdown-' + id);
    if (!target) return;

    document.querySelectorAll('[id^="dropdown-"]').forEach(function (menu) {
        if (menu !== target) menu.classList.add('hidden');
    });
    target.classList.toggle('hidden');
};

if (!window.adminDataTableDropdownDismissBound) {
    document.addEventListener('click', function (event) {
        if (!event.target.closest('[onclick*="toggleDropdown"]') && !event.target.closest('[id^="dropdown-"]')) {
            document.querySelectorAll('[id^="dropdown-"]').forEach(function (menu) {
                menu.classList.add('hidden');
            });
        }
    });
    window.adminDataTableDropdownDismissBound = true;
}

$(document).ready(function() {
    let searchDelay;

    // Determine server side setting
    let isServerSide = @json($serverSide ?? ($ajaxUrl ? true : false));

    // Determine DOM layout (hide default search 'f' if custom search input is used)
    let domSetting = @json($dom);
    if (!domSetting) {
        @if($searchId)
            domSetting = '<"flex flex-wrap justify-between items-center"<"flex flex-wrap items-center gap-2"l>>rt<"flex flex-wrap justify-between items-center"ip>';
        @else
            domSetting = '<"flex flex-wrap justify-between items-center"<"flex flex-wrap items-center gap-2"l><"flex items-center"f>>rt<"flex flex-wrap justify-between items-center"ip>';
        @endif
    }

    // DataTable initialization config
    let config = {
        responsive: @json($responsive),
        processing: isServerSide,
        serverSide: isServerSide,
        pageLength: @json($pageLength),
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        pagingType: "simple_numbers",
        dom: domSetting,
        language: {
            lengthMenu: '_MENU_ per page',
            search: '',
            searchPlaceholder: 'Search records…',
            info: 'Showing _START_–_END_ of _TOTAL_',
            infoEmpty: 'No records',
            infoFiltered: ' · filtered from _MAX_',
            emptyTable: 'No records found',
            zeroRecords: 'No matching records found',
            processing: '<i class="fa-solid fa-circle-notch fa-spin mr-2"></i> Loading',
            paginate: { next: '›', previous: '‹' }
        }
    };

    // Add AJAX source if set
    @if($ajaxUrl)
        config.ajax = {
            url: "{{ $ajaxUrl }}",
            type: 'GET',
            dataSrc: function(data) {
                return data.data || [];
            },
            error: function(xhr) {
                console.error('Unable to load table data', xhr.status, xhr.responseText);
                const body = $('#{{ $id }} tbody');
                const columns = @json(max(1, count($columns)));
                body.html('<tr><td colspan="' + columns + '" class="py-12 text-center text-sm text-rose-600"><i class="fa-solid fa-triangle-exclamation mr-2"></i>Unable to load records. Please refresh and try again.</td></tr>');
            },
            @if($filterFormId)
            data: function(d) {
                let formData = $('#{{ $filterFormId }}').find('input, select').serializeArray();
                $.each(formData, function(i, field) {
                    d[field.name] = field.value;
                });
            }
            @endif
        };
    @endif

    // Add Columns mapping if provided
    @if(!empty($columns))
        config.columns = @json($columns);
        config.columns.forEach(col => {
            if (col.defaultContent === undefined) {
                col.defaultContent = '';
            }
        });
    @endif

    // Add Order configuration if provided
    @if($order)
        config.order = @json($order);
    @endif

    // Add custom columnDefs if provided
    @if($columnDefs)
        config.columnDefs = @json($columnDefs);
    @endif

    // Custom drawCallback for closing dropdowns and custom actions
    config.drawCallback = function(settings) {
        // Re-initialize/hide dropdowns after table redraw
        $('[id^="dropdown-"]').addClass('hidden');
        
        // Sync select-all checkbox state
        @if($selectAllId)
            let total = $('.{{ $rowCheckboxClass }}').length;
            let checked = $('.{{ $rowCheckboxClass }}:checked').length;
            $('#{{ $selectAllId }}').prop('checked', total > 0 && total === checked);
        @endif

        // Optional custom callback
        @if($drawCallback)
            {!! $drawCallback !!}(settings);
        @endif
    };

    // Initialize DataTable
    let table = $('#{{ $id }}').DataTable(config);

    // External search with 200ms debounce
    @if($searchId)
        $('#{{ $searchId }}').on('keyup change input', function() {
            clearTimeout(searchDelay);
            let searchTerm = this.value;
            searchDelay = setTimeout(function() {
                table.search(searchTerm).draw();
            }, 200);
        });
    @endif

    // External filter form change
    @if($filterFormId)
        $('#{{ $filterFormId }}').on('change', 'select, input', function() {
            table.ajax.reload();
        });

        $('#{{ $filterFormId }}').on('reset', function() {
            setTimeout(function() {
                table.search('').ajax.reload();
            }, 10);
        });
    @endif

    // Clear filters action
    @if($clearFiltersId)
        $('#{{ $clearFiltersId }}').on('click', function() {
            @if($filterFormId)
                let form = $('#{{ $filterFormId }}');
                if (form.is('form')) {
                    form[0].reset();
                } else {
                    form.find('input, select').val('');
                }
            @endif
            @if($searchId)
                $('#{{ $searchId }}').val('');
            @endif
            table.search('').ajax.reload();
        });
    @endif

    // Select-all checkbox logic
    @if($selectAllId)
        $('#{{ $selectAllId }}').on('click', function() {
            $('.{{ $rowCheckboxClass }}').prop('checked', this.checked);
        });

        $(document).on('change', '.{{ $rowCheckboxClass }}', function() {
            let total = $('.{{ $rowCheckboxClass }}').length;
            let checked = $('.{{ $rowCheckboxClass }}:checked').length;
            $('#{{ $selectAllId }}').prop('checked', total > 0 && total === checked);
        });
    @endif

    // Store table reference in global jQuery data for easy page-specific overrides
    $('#{{ $id }}').data('dataTable', table);
});
</script>
