{{--
    Permission matrix partial — tree view with collapsible tabs.
    Variables:
      $groupedPermissions  — tree from RoleManagementController::groupPermissions()
      $idPrefix            — 'add' | 'edit'
      $rolePermIds         — array of pre-selected permission IDs (empty for add)
--}}
@foreach ($groupedPermissions as $category => $perms)
    @php
        $catSlug   = Str::slug($category);
        $allInCat  = collect($perms)->flatMap(function ($m) {
            $ids = [];
            if ($m['manage']) $ids[] = $m['manage']->id;
            if ($m['view'])   $ids[] = $m['view']->id;
            foreach ($m['tabs'] as $t) {
                if ($t['manage']) $ids[] = $t['manage']->id;
                if ($t['view'])   $ids[] = $t['view']->id;
            }
            return $ids;
        })->values();
        $totalInCat = $allInCat->count();
    @endphp

    <div class="perm-category-group mb-2"
         data-total="{{ $totalInCat }}"
         data-cat="{{ $catSlug }}">

        {{-- ── Category header ── --}}
        <div class="d-flex justify-content-between align-items-center px-2 py-1 rounded-2 mb-1"
             style="background:#f1f5f9; border-left:3px solid #64748b;">
            <div class="d-flex align-items-center gap-2">
                <span class="fw-bold small text-dark">{{ $category }}</span>
                <span class="perm-badge badge rounded-pill text-bg-secondary" style="font-size:0.6rem;">
                    0 / {{ $totalInCat }}
                </span>
            </div>
            <div class="d-flex align-items-center gap-2">
                <div class="form-check form-check-inline mb-0">
                    <input class="form-check-input select-all-category" type="checkbox"
                        id="{{ $idPrefix }}-all-{{ $catSlug }}"
                        title="{{ __('Select all in this category') }}">
                    <label class="form-check-label small text-muted cursor-pointer"
                        for="{{ $idPrefix }}-all-{{ $catSlug }}">
                        {{ __('All') }}
                    </label>
                </div>
            </div>
        </div>

        {{-- ── Column headers ── --}}
        <div class="row g-0 px-1 mb-1 text-uppercase text-secondary"
             style="font-size:0.6rem;font-weight:800;letter-spacing:0.4px;">
            <div class="col-6 ps-1">{{ __('Manage') }}</div>
            <div class="col-6 ps-3">{{ __('View') }}</div>
        </div>

        <div class="ms-1">
            @foreach ($perms as $menuName => $menuData)
                @php
                    $hasTabs    = ! empty($menuData['tabs']);
                    $menuSlug   = Str::slug($menuName);
                    $collapseId = $idPrefix . '-tabs-' . $catSlug . '-' . $menuSlug;
                    $tabCount   = count($menuData['tabs']);
                @endphp

                <div class="perm-menu-row mb-1" data-base="{{ strtolower($menuName) }}">

                    {{-- ── Menu-level row ── --}}
                    <div class="row g-0 align-items-center permission-pair-row"
                         data-base="{{ strtolower($menuName) }}">

                        {{-- Manage column --}}
                        <div class="col-6 text-break pe-2">
                            @if($menuData['manage'])
                                @php $p = $menuData['manage']; @endphp
                                <div class="permission-item d-flex align-items-center gap-1"
                                     data-name="{{ strtolower($p->name) }}">
                                    @if($hasTabs)
                                        <button type="button"
                                            class="btn btn-link btn-sm p-0 lh-1 text-secondary tab-collapse-toggle flex-shrink-0"
                                            data-bs-toggle="collapse"
                                            data-bs-target="#{{ $collapseId }}"
                                            aria-expanded="false"
                                            title="{{ $tabCount }} tab permissions">
                                            <i class="bi bi-chevron-right perm-chevron" style="font-size:0.65rem;transition:transform .2s;"></i>
                                        </button>
                                    @else
                                        <span style="width:14px;display:inline-block;"></span>
                                    @endif
                                    <div class="form-check mb-0">
                                        <input class="form-check-input perm-checkbox perm-manage"
                                            type="checkbox" name="permissions[]"
                                            value="{{ $p->id }}"
                                            id="{{ $idPrefix }}-perm-{{ $p->id }}"
                                            data-manage-for="{{ $idPrefix }}-perm-{{ $menuData['view']?->id }}"
                                            @if(in_array($p->id, $rolePermIds ?? [])) checked @endif>
                                        <label class="form-check-label small cursor-pointer fw-semibold lh-sm"
                                            for="{{ $idPrefix }}-perm-{{ $p->id }}"
                                            title="{{ $p->name }}">
                                            {{ $p->name }}
                                            @if($hasTabs)
                                                <span class="text-muted fw-normal" style="font-size:0.6rem;">(+{{ $tabCount }} tabs)</span>
                                            @endif
                                        </label>
                                    </div>
                                </div>
                            @endif
                        </div>

                        {{-- View column --}}
                        <div class="col-6 ps-3 text-break">
                            @if($menuData['view'])
                                @php $p = $menuData['view']; @endphp
                                <div class="permission-item" data-name="{{ strtolower($p->name) }}">
                                    <div class="form-check mb-0">
                                        <input class="form-check-input perm-checkbox perm-view"
                                            type="checkbox" name="permissions[]"
                                            value="{{ $p->id }}"
                                            id="{{ $idPrefix }}-perm-{{ $p->id }}"
                                            @if(in_array($p->id, $rolePermIds ?? [])) checked @endif>
                                        <label class="form-check-label small cursor-pointer fw-semibold lh-sm"
                                            for="{{ $idPrefix }}-perm-{{ $p->id }}"
                                            title="{{ $p->name }}">
                                            {{ $p->name }}
                                        </label>
                                    </div>
                                </div>
                            @endif
                        </div>
                    </div>

                    {{-- ── Collapsible tab rows ── --}}
                    @if($hasTabs)
                        <div class="collapse" id="{{ $collapseId }}">
                            <div class="ms-4 mt-1 ps-2 border-start border-2"
                                 style="border-color:#cbd5e1 !important;">
                                <div class="row g-0 mb-1 text-uppercase text-secondary"
                                     style="font-size:0.58rem;font-weight:800;letter-spacing:0.3px;">
                                    <div class="col-6">{{ __('Manage Tab') }}</div>
                                    <div class="col-6 ps-3">{{ __('View Tab') }}</div>
                                </div>
                                @foreach ($menuData['tabs'] as $tabSlug => $tabPerms)
                                    <div class="row g-0 align-items-center mb-1 permission-pair-row"
                                         data-base="{{ strtolower($menuName . ':' . $tabSlug) }}">

                                        {{-- Manage tab --}}
                                        <div class="col-6 text-break pe-2">
                                            @if($tabPerms['manage'])
                                                @php $p = $tabPerms['manage']; @endphp
                                                <div class="permission-item" data-name="{{ strtolower($p->name) }}">
                                                    <div class="form-check mb-0">
                                                        <input class="form-check-input perm-checkbox perm-manage"
                                                            type="checkbox" name="permissions[]"
                                                            value="{{ $p->id }}"
                                                            id="{{ $idPrefix }}-perm-{{ $p->id }}"
                                                            data-manage-for="{{ $idPrefix }}-perm-{{ $tabPerms['view']?->id }}"
                                                            @if(in_array($p->id, $rolePermIds ?? [])) checked @endif>
                                                        <label class="form-check-label small cursor-pointer lh-sm"
                                                            for="{{ $idPrefix }}-perm-{{ $p->id }}"
                                                            title="{{ $p->name }}">
                                                            <span class="badge me-1"
                                                                  style="font-size:0.55rem;background:#e2e8f0;color:#475569;font-weight:600;">
                                                                {{ $tabSlug }}
                                                            </span>
                                                            manage
                                                        </label>
                                                    </div>
                                                </div>
                                            @endif
                                        </div>

                                        {{-- View tab --}}
                                        <div class="col-6 ps-3 text-break">
                                            @if($tabPerms['view'])
                                                @php $p = $tabPerms['view']; @endphp
                                                <div class="permission-item" data-name="{{ strtolower($p->name) }}">
                                                    <div class="form-check mb-0">
                                                        <input class="form-check-input perm-checkbox perm-view"
                                                            type="checkbox" name="permissions[]"
                                                            value="{{ $p->id }}"
                                                            id="{{ $idPrefix }}-perm-{{ $p->id }}"
                                                            @if(in_array($p->id, $rolePermIds ?? [])) checked @endif>
                                                        <label class="form-check-label small cursor-pointer lh-sm"
                                                            for="{{ $idPrefix }}-perm-{{ $p->id }}"
                                                            title="{{ $p->name }}">
                                                            <span class="badge me-1"
                                                                  style="font-size:0.55rem;background:#e2e8f0;color:#475569;font-weight:600;">
                                                                {{ $tabSlug }}
                                                            </span>
                                                            view
                                                        </label>
                                                    </div>
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endif

                </div>
            @endforeach
        </div>
    </div>
@endforeach
