@foreach($items as $customer)
@php
    $hasChildren = count($customer->children_tree) > 0;
    $isJob = (bool) $customer->is_job;
@endphp
<tr class="cust-row"
    data-id="{{ $customer->id }}"
    data-parent="{{ $customer->parent_id ?? 'null' }}"
    data-level="{{ $level }}"
    style="{{ $level > 0 && !($expandAll ?? false) ? 'display:none' : '' }}">
    <td style="padding-left:{{ $level * 20 + 12 }}px">
        <div class="d-flex align-items-center gap-1">
            @if($hasChildren)
            <button type="button" class="cust-toggle btn btn-link p-0 border-0 lh-1 flex-shrink-0"
                    data-id="{{ $customer->id }}" style="width:20px;color:#6c757d">
                <i class="bi bi-chevron-{{ ($expandAll ?? false) ? 'down' : 'right' }} cust-icon" style="font-size:11px"></i>
            </button>
            @else
            <span style="display:inline-block;width:20px"></span>
            @endif
            <i class="bi bi-{{ $isJob ? 'briefcase text-secondary' : ($hasChildren ? 'building text-primary' : 'person text-primary') }} flex-shrink-0"
               style="font-size:14px"></i>
            <div class="ms-1 min-width-0">
                <div class="{{ $hasChildren ? 'fw-semibold' : '' }}" style="font-size:13.5px;line-height:1.3">
                    {{ $customer->name }}
                </div>
                @if($customer->code)
                    <code style="font-size:11.5px">{{ $customer->code }}</code>
                @endif
                @if($customer->phone)
                <div class="d-md-none text-muted" style="font-size:12px">
                    <i class="bi bi-telephone me-1"></i>{{ $customer->phone }}
                </div>
                @endif
            </div>
        </div>
    </td>
    <td class="d-none d-md-table-cell">
        @if($customer->email)
            <div style="font-size:13px">{{ $customer->email }}</div>
        @endif
        @if($customer->phone)
            <div class="text-muted" style="font-size:12px">{{ $customer->phone }}</div>
        @endif
        @if(!$customer->email && !$customer->phone)
            <span class="text-muted">—</span>
        @endif
    </td>
    <td class="d-none d-lg-table-cell" style="font-size:13px">
        {{ $customer->currency?->code ?? '—' }}
    </td>
    <td class="d-none d-lg-table-cell" style="font-size:13px">
        {{ $customer->payment_terms_days }} days
    </td>
    <td>
        <span class="badge" style="background:{{ $isJob ? '#e9ecef' : '#EBF3FB' }};color:{{ $isJob ? '#495057' : '#1B4F8A' }};font-size:11px">
            {{ $isJob ? 'Job' : 'Customer' }}
        </span>
    </td>
    <td>
        <span class="badge" style="background:{{ $customer->is_active ? '#d1e7dd':'#f8d7da' }};color:{{ $customer->is_active ? '#0a3622':'#842029' }};font-size:11px">
            {{ $customer->is_active ? 'Active' : 'Inactive' }}
        </span>
    </td>
    <td class="text-end pe-2">
        <div class="d-flex justify-content-end gap-1">
            @if(auth()->user()->hasPermission('ar','edit'))
            <a href="{{ route('masters.customers.edit', $customer) }}"
               class="btn btn-outline-primary btn-sm" title="Edit">
                <i class="bi bi-pencil"></i>
            </a>
            <form method="POST" action="{{ route('masters.customers.toggle', $customer) }}" id="tc-{{ $customer->id }}">
                @csrf @method('PATCH')
                <button type="button"
                    class="btn btn-sm {{ $customer->is_active ? 'btn-outline-warning':'btn-outline-success' }}"
                    data-confirm data-form="#tc-{{ $customer->id }}"
                    data-confirm-title="{{ $customer->is_active ? 'Deactivate?':'Activate?' }}"
                    data-confirm-text="{{ $customer->name }}"
                    data-confirm-icon="question"
                    data-confirm-color="{{ $customer->is_active ? '#E67E22':'#27AE60' }}"
                    data-confirm-btn="{{ $customer->is_active ? 'Deactivate':'Activate' }}"
                    title="{{ $customer->is_active ? 'Deactivate':'Activate' }}">
                    <i class="bi bi-{{ $customer->is_active ? 'pause-circle':'play-circle' }}"></i>
                </button>
            </form>
            <form method="POST" action="{{ route('masters.customers.destroy', $customer) }}" id="dc-{{ $customer->id }}">
                @csrf @method('DELETE')
                <button type="button" class="btn btn-outline-danger btn-sm"
                    data-confirm data-form="#dc-{{ $customer->id }}"
                    data-confirm-title="Delete permanently?"
                    data-confirm-text="{{ $customer->name }} can only be deleted if it has never been used in transactions. Used customers should be deactivated instead."
                    data-confirm-icon="warning"
                    data-confirm-color="#DC2626"
                    data-confirm-btn="Delete permanently"
                    title="Delete permanently">
                    <i class="bi bi-trash"></i>
                </button>
            </form>
            @endif
        </div>
    </td>
</tr>
@if($hasChildren)
    @include('masters.customers._tree', ['items' => $customer->children_tree, 'level' => $level + 1, 'expandAll' => $expandAll ?? false])
@endif
@endforeach

@once
@push('scripts')
<script>
const custState = {};

function custToggle(id) {
    const isOpen = !!custState[id];
    custState[id] = !isOpen;
    const icon = document.querySelector(`.cust-toggle[data-id="${id}"] .cust-icon`);
    document.querySelectorAll(`.cust-row[data-parent="${id}"]`).forEach((row) => {
        if (isOpen) {
            row.style.display = 'none';
            custCollapse(row.dataset.id);
        } else {
            row.style.display = '';
        }
    });
    if (icon) {
        icon.classList.toggle('bi-chevron-down', !isOpen);
        icon.classList.toggle('bi-chevron-right', isOpen);
    }
}

function custCollapse(id) {
    if (!id || id === 'null') {
        return;
    }
    custState[id] = false;
    const icon = document.querySelector(`.cust-toggle[data-id="${id}"] .cust-icon`);
    if (icon) {
        icon.classList.remove('bi-chevron-down');
        icon.classList.add('bi-chevron-right');
    }
    document.querySelectorAll(`.cust-row[data-parent="${id}"]`).forEach((row) => {
        row.style.display = 'none';
        custCollapse(row.dataset.id);
    });
}

function custExpandAll() {
    document.querySelectorAll('.cust-row').forEach((row) => {
        row.style.display = '';
        if (row.dataset.id) {
            custState[row.dataset.id] = true;
        }
    });
    document.querySelectorAll('.cust-toggle .cust-icon').forEach((icon) => {
        icon.classList.remove('bi-chevron-right');
        icon.classList.add('bi-chevron-down');
    });
}

function custCollapseAll() {
    document.querySelectorAll('.cust-row').forEach((row) => {
        const level = Number(row.dataset.level || 0);
        row.style.display = level === 0 ? '' : 'none';
        if (row.dataset.id) {
            custState[row.dataset.id] = false;
        }
    });
    document.querySelectorAll('.cust-toggle .cust-icon').forEach((icon) => {
        icon.classList.remove('bi-chevron-down');
        icon.classList.add('bi-chevron-right');
    });
}

document.addEventListener('click', (event) => {
    const button = event.target.closest('.cust-toggle');
    if (button) {
        custToggle(button.dataset.id);
    }
});
</script>
@endpush
@endonce
