@php
use Illuminate\Support\Facades\Route;

// ── User & role ──────────────────────────────────────────────────────────────
$user        = auth()->user();
$role        = $user ? $user->roles->first() : null;
$roleName    = $role ? $role->name : 'User'; // still used for permission checks below

// ── Helper: safe route URL (returns '#' when route is not registered) ────────
$r = function (string $name, array $params = []): string {
    return Route::has($name) ? route($name, $params) : '#';
};

// ── GROUP 1: CORE ────────────────────────────────────────────────────────────
$coreLinks = [];
if (Route::has('dashboard')) {
    // Use getDashboardUrl() so Partners (and all roles) go directly to their
    // role dashboard without an intermediate redirect through /dashboard
    // which would be intercepted by the partner-management module route.
    $dashboardUrl    = $user->getDashboardUrl();
    // Mark Dashboard active only on the user's own role dashboard route,
    // NOT on all dashboard.* sub-routes (which would incorrectly highlight
    // Dashboard when on unrelated pages like partners.index).
    $roleDashRoute   = $user->getRoleDashboardRoute(); // e.g. 'dashboard.partners'
    $dashboardActive = request()->routeIs($roleDashRoute) || request()->routeIs('dashboard');
    $coreLinks[] = ['label' => 'Dashboard', 'url' => $dashboardUrl, 'icon' => 'fa-gauge-high', 'active' => $dashboardActive];
}
if (Route::has('profile.edit')) {
    $coreLinks[] = ['label' => 'My Profile',      'url' => route('profile.edit'),      'icon' => 'fa-user-circle',   'active' => request()->routeIs('profile.edit')];
}
if (Route::has('settings.sessions')) {
    $coreLinks[] = ['label' => 'Active Sessions', 'url' => route('settings.sessions'), 'icon' => 'fa-laptop',        'active' => request()->routeIs('settings.sessions')];
}
if (Route::has('settings.security')) {
    $coreLinks[] = ['label' => 'Security',        'url' => route('settings.security'), 'icon' => 'fa-shield-halved', 'active' => request()->routeIs('settings.security')];
}

// ── GROUP 10: KNOWLEDGE SHARING ──────────────────────────────────────────────
$knowledgeLinks = [];
if ($user->can('view discussion topics') && Route::has('knowledge-sharing.discussions.topics.index')) {
    $knowledgeLinks[] = ['label' => 'Discussion Topics',  'url' => route('knowledge-sharing.discussions.topics.index'),       'icon' => 'fa-list-ul',          'active' => request()->routeIs('knowledge-sharing.discussions.topics.*')];
}
if ($user->can('view discussions') && Route::has('knowledge-sharing.discussions.index')) {
    $knowledgeLinks[] = ['label' => 'Discussions',        'url' => route('knowledge-sharing.discussions.index'),              'icon' => 'fa-comments',         'active' => request()->routeIs('knowledge-sharing.discussions.index') || (request()->routeIs('knowledge-sharing.discussions.*') && !request()->routeIs('knowledge-sharing.discussions.topics.*'))];
}
if ($user->can('view discussions') && Route::has('knowledge-sharing.discussions.replies.index')) {
    $knowledgeLinks[] = [
        'label'  => 'All Replies',
        'url'    => route('knowledge-sharing.discussions.replies.index'),
        'icon'   => 'fa-reply-all',
        'active' => request()->routeIs('knowledge-sharing.discussions.replies.*'),
    ];
}
if ($user->can('manage knowledge base categories') && Route::has('knowledge-sharing.knowledge-base.categories.index')) {
    $knowledgeLinks[] = ['label' => 'KB Categories',      'url' => route('knowledge-sharing.knowledge-base.categories.index'),'icon' => 'fa-folder-tree',      'active' => request()->routeIs('knowledge-sharing.knowledge-base.categories.*')];
}
if ($user->can('view knowledge base questions') && Route::has('knowledge-sharing.knowledge-base.index')) {
    $knowledgeLinks[] = ['label' => 'Knowledge Base Q&A', 'url' => route('knowledge-sharing.knowledge-base.index'),           'icon' => 'fa-circle-question',  'active' => request()->routeIs('knowledge-sharing.knowledge-base.index') || (request()->routeIs('knowledge-sharing.knowledge-base.*') && !request()->routeIs('knowledge-sharing.knowledge-base.categories.*'))];
}
if ($user->can('view knowledge base questions') && Route::has('knowledge-sharing.knowledge-base.answers.index')) {
    $knowledgeLinks[] = [
        'label'  => 'All Answers',
        'url'    => route('knowledge-sharing.knowledge-base.answers.index'),
        'icon'   => 'fa-circle-check',
        'active' => request()->routeIs('knowledge-sharing.knowledge-base.answers.*'),
    ];
}
if ($user->hasRole('Contributor') && Route::has('contributor.dashboard')) {
    $knowledgeLinks[] = ['label' => 'Contributor Dashboard', 'url' => route('contributor.dashboard'),  'icon' => 'fa-gauge',         'active' => request()->routeIs('contributor.dashboard')];
}
if ($user->hasRole('Contributor') && Route::has('contributor.discussions')) {
    $knowledgeLinks[] = ['label' => 'My Discussions',     'url' => route('contributor.discussions'),   'icon' => 'fa-comment-dots',  'active' => request()->routeIs('contributor.discussions')];
}
if ($user->hasRole('Contributor') && Route::has('contributor.replies')) {
    $knowledgeLinks[] = ['label' => 'My Replies',         'url' => route('contributor.replies'),       'icon' => 'fa-reply',         'active' => request()->routeIs('contributor.replies')];
}

// ── GROUP 11: COMMUNICATION ──────────────────────────────────────────────────
$communicationLinks = [];
if ($user->can('view tickets') && Route::has('tickets.index')) {
    $communicationLinks[] = ['label' => 'Support Tickets',  'url' => route('tickets.index'),        'icon' => 'fa-ticket',                'active' => request()->routeIs('tickets.*')];
}
if ($user->can('view chats') && Route::has('chat.index')) {
    $communicationLinks[] = ['label' => 'Live Chat',        'url' => route('chat.index'),           'icon' => 'fa-comments',              'active' => request()->routeIs('chat.index')];
}
if ($user->can('manage chat categories') && Route::has('chat.categories')) {
    $communicationLinks[] = ['label' => 'Chat Categories',  'url' => route('chat.categories'),      'icon' => 'fa-tags',                  'active' => request()->routeIs('chat.categories')];
}
if ($user->can('appoint chat agents') && Route::has('chat.agents')) {
    $communicationLinks[] = ['label' => 'Chat Agents',      'url' => route('chat.agents'),          'icon' => 'fa-headset',               'active' => request()->routeIs('chat.agents')];
}
if ($user->can('handle chats') && Route::has('chat.conversations')) {
    $communicationLinks[] = ['label' => 'Chat Conversations','url' => route('chat.conversations'),  'icon' => 'fa-comment-dots',          'active' => request()->routeIs('chat.conversations') || request()->routeIs('chat.conversation.*')];
}
if (($user->hasAnyRole(['Super Manager', 'Manager']) || $user->can('appoint chat agents')) && Route::has('chat.agent-dashboard')) {
    $communicationLinks[] = ['label' => 'Agent Dashboard',  'url' => route('chat.agent-dashboard'), 'icon' => 'fa-gauge-high',            'active' => request()->routeIs('chat.agent-dashboard')];
}

// ── GROUP 12: ORGANIZATION & GOVERNANCE ──────────────────────────────────────
$orgLinks = [];
if ($user->can('view organizations') && Route::has('organization.details.index')) {
    $orgLinks[] = ['label' => 'Organization Details',  'url' => route('organization.details.index'),           'icon' => 'fa-building',          'active' => request()->routeIs('organization.details.*')];
}
if ($user->can('view leadership positions') && Route::has('organization.leadership-positions.index')) {
    $orgLinks[] = ['label' => 'Leadership Positions',  'url' => route('organization.leadership-positions.index'),'icon' => 'fa-sitemap',          'active' => request()->routeIs('organization.leadership-positions.*')];
}
if ($user->can('view leadership history') && Route::has('organization.leadership-history.index')) {
    $orgLinks[] = ['label' => 'Leadership History',    'url' => route('organization.leadership-history.index'), 'icon' => 'fa-clock-rotate-left', 'active' => request()->routeIs('organization.leadership-history.*')];
}
if ($user->can('view staff history') && Route::has('organization.staff-history.index')) {
    $orgLinks[] = ['label' => 'Staff History',         'url' => route('organization.staff-history.index'),      'icon' => 'fa-users-gear',        'active' => request()->routeIs('organization.staff-history.*')];
}
if ($user->can('view election cycles') && Route::has('organization.election-cycles.index')) {
    $orgLinks[] = ['label' => 'Election Cycles',       'url' => route('organization.election-cycles.index'),    'icon' => 'fa-rotate',            'active' => request()->routeIs('organization.election-cycles.*')];
}
if ($user->can('view voting procedures') && Route::has('organization.voting-procedures.index')) {
    $orgLinks[] = ['label' => 'Voting Procedures',     'url' => route('organization.voting-procedures.index'),  'icon' => 'fa-check-to-slot',     'active' => request()->routeIs('organization.voting-procedures.*')];
}
if ($user->can('view organogram') && Route::has('organization.organogram.show')) {
    $orgLinks[] = ['label' => 'Organogram',            'url' => route('organization.organogram.show'),          'icon' => 'fa-diagram-project',   'active' => request()->routeIs('organization.organogram.*')];
}

// ── GROUP 13: CONTENT MANAGEMENT ─────────────────────────────────────────────
$contentLinks = [];
if ($user->hasAnyRole(['Super Manager', 'Manager'])) {
    if (Route::has('admin.sliders.index')) {
        $contentLinks[] = ['label' => 'Hero Slider',          'url' => route('admin.sliders.index'),           'icon' => 'fa-images',       'active' => request()->routeIs('admin.sliders.*')];
    }
    if ($user->can('view email subscribers') && Route::has('email-subscribers.index')) {
        $contentLinks[] = ['label' => 'Email Subscribers',    'url' => route('email-subscribers.index'),       'icon' => 'fa-envelope',     'active' => request()->routeIs('email-subscribers.*')];
    }
}

// ── GROUP 14: SELF-PACED LEARNING ────────────────────────────────────────────
$selfPacedLinks = [];
if ($user->hasSelfPacedPortalAccess()) {
    $isTraineeOnly = $user->hasRole('Trainees') && !$user->hasAnyRole(['Super Manager', 'Manager', 'Trainers']);
    if ($isTraineeOnly) {
        if (Route::has('self-paced.learn.my-courses')) {
            $selfPacedLinks[] = ['label' => 'My Learning',      'url' => route('self-paced.learn.my-courses'), 'icon' => 'fa-book-reader',    'active' => request()->routeIs('self-paced.learn.my-courses')];
        }
        if (Route::has('self-paced.public.index')) {
            $selfPacedLinks[] = ['label' => 'Course Catalogue', 'url' => route('self-paced.public.index'),     'icon' => 'fa-graduation-cap', 'active' => request()->routeIs('self-paced.public.index') || request()->routeIs('self-paced.public.courses.*')];
        }
    } else {
        if (Route::has('self-paced.dashboard.index')) {
            $selfPacedLinks[] = ['label' => 'Self-Paced Portal','url' => route('self-paced.dashboard.index'),  'icon' => 'fa-chalkboard',     'active' => request()->routeIs('self-paced.dashboard.*')];
        }
        if (Route::has('self-paced.public.index')) {
            $selfPacedLinks[] = ['label' => 'Learner Portal',   'url' => route('self-paced.public.index'),     'icon' => 'fa-graduation-cap', 'active' => request()->routeIs('self-paced.public.*') || request()->routeIs('self-paced.learn.*')];
        }
    }
}

// ── GROUP 15: MEDIA & GALLERIES ──────────────────────────────────────────────
$mediaLinks = [];
if ($user->can('view gallery types') && Route::has('media.gallery-types.index')) {
    $mediaLinks[] = ['label' => 'Gallery Types',  'url' => route('media.gallery-types.index'),  'icon' => 'fa-folder-open',  'active' => request()->routeIs('media.gallery-types.*')];
}
if ($user->can('view galleries') && Route::has('media.galleries.index')) {
    $mediaLinks[] = ['label' => 'Galleries',      'url' => route('media.galleries.index'),      'icon' => 'fa-images',       'active' => request()->routeIs('media.galleries.*') || request()->routeIs('media.images.*')];
}

// ── GROUP 16: SYSTEM CONFIG ──────────────────────────────────────────────────
$systemConfigLinks = [];
if ($user->hasRole('Super Manager')) {
    if (Route::has('config.email.index')) {
        $systemConfigLinks[] = ['label' => 'Email Config',       'url' => route('config.email.index'),       'icon' => 'fa-envelope-open',  'active' => request()->routeIs('config.email.*')];
    }
    if (Route::has('config.payment.index')) {
        $systemConfigLinks[] = ['label' => 'Payment Config',     'url' => route('config.payment.index'),     'icon' => 'fa-credit-card',    'active' => request()->routeIs('config.payment.*')];
    }
}

// ── Build $groups array ──────────────────────────────────────────────────────
$groups = [
    ['key' => 'core',                    'label' => 'Core',                      'icon' => 'fa-house',          'links' => $coreLinks],
    ['key' => 'knowledge-sharing',       'label' => 'Knowledge Sharing',         'icon' => 'fa-comments',       'links' => $knowledgeLinks],
    ['key' => 'communication',           'label' => 'Communication',             'icon' => 'fa-envelope',       'links' => $communicationLinks],
    ['key' => 'organization-governance', 'label' => 'Organization & Governance', 'icon' => 'fa-building',       'links' => $orgLinks],
    ['key' => 'content-management',      'label' => 'Content Management',        'icon' => 'fa-images',         'links' => $contentLinks],
    ['key' => 'media',                   'label' => 'Media & Galleries',         'icon' => 'fa-photo-film',     'links' => $mediaLinks],
    ['key' => 'self-paced-learning',     'label' => 'Self-Paced Learning',       'icon' => 'fa-graduation-cap', 'links' => $selfPacedLinks],
    ['key' => 'system-config',           'label' => 'System Config',             'icon' => 'fa-gear',           'links' => $systemConfigLinks],
];

// Attach isActive flag to each group (true when any link in the group is active)
foreach ($groups as &$group) {
    $group['isActive'] = collect($group['links'])->contains('active', true);
}
unset($group);

// ── Compute $activeGroupKey ──────────────────────────────────────────────────
// Determined by checking request()->routeIs(...) patterns for each group.
// The first matching group wins; falls back to the group whose link is active.
$activeGroupKey = null;

$groupRoutePatterns = [
    'core'                    => ['dashboard', 'dashboard.*', 'profile.edit', 'settings.*'],
    'knowledge-sharing'       => ['knowledge-sharing.*', 'contributor.*'],
    'communication'           => ['emails.*', 'sms.*', 'tickets.*', 'chat.*'],
    'organization-governance' => ['organization.*'],
    'content-management'      => ['admin.sliders.*', 'admin.hero-cards.*', 'admin.what-we-do-images.*', 'admin.pages.*', 'topbar-notifications.*', 'email-subscribers.*'],
    'media'                   => ['media.*'],
    'self-paced-learning'     => ['self-paced.*'],
    'system-config'           => ['config.*'],
];

foreach ($groupRoutePatterns as $key => $patterns) {
    if (request()->routeIs($patterns)) {
        $activeGroupKey = $key;
        break;
    }
}

// Fallback: derive from the groups array if pattern matching didn't catch it
if ($activeGroupKey === null) {
    foreach ($groups as $group) {
        if ($group['isActive']) {
            $activeGroupKey = $group['key'];
            break;
        }
    }
}
@endphp

<style>
/* ── Sidebar scoped styles ─────────────────────────────────────────────────── */

.sidebar-bg {
    background-color: var(--theme-bg-sidebar, #4338ca);
}

.sidebar-group-label {
    background: linear-gradient(90deg, #3730a3 0%, #4338ca 40%, #4f46e5 100%);
    text-transform: uppercase;
    font-size: 0.65rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    color: #ffffff;
    padding: 0.35rem 0.75rem;
    margin: 0.5rem 0 0.25rem;
    border-radius: 0.375rem;
}

.sidebar-nav-link {
    color: rgba(255, 255, 255, 0.82);
}

.sidebar-nav-link:hover {
    background: rgba(255, 255, 255, 0.08);
    color: #ffffff;
}

.sidebar-nav-link.active {
    background: rgba(255, 255, 255, 0.15);
    border-left-color: #818cf8;
    color: #ffffff;
}

.sidebar-profile-border {
    border-bottom: 1px solid rgba(255, 255, 255, 0.12);
}

.sidebar-collapse-btn {
    background-color: rgba(255, 255, 255, 0.08);
    color: rgba(255, 255, 255, 0.7);
}

.sidebar-collapse-btn:hover {
    background-color: rgba(255, 255, 255, 0.15);
    color: #ffffff;
}

.avatar-hint-ring {
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.4), 0 0 0 4px rgba(99, 102, 241, 0.45);
}

.sidebar-group-chevron {
    transition: transform 0.2s ease;
}

.sidebar-nav-scroll::-webkit-scrollbar {
    width: 4px;
}

.sidebar-nav-scroll::-webkit-scrollbar-track {
    background: transparent;
}

.sidebar-nav-scroll::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 2px;
}

.role-themed-hover:hover {
    background-color: rgba(255, 255, 255, 0.08);
}
</style>

<aside
    x-data="sidebarProfileData()"
    x-init="init('{{ $activeGroupKey }}')"
    :class="{
        'w-64': $store.appLayout.sidebarOpen && !$store.appLayout.isMobile,
        'w-20': !$store.appLayout.sidebarOpen && !$store.appLayout.isMobile,
        '-translate-x-full': $store.appLayout.isMobile && !$store.appLayout.sidebarOpen,
        'translate-x-0': !$store.appLayout.isMobile || $store.appLayout.sidebarOpen
    }"
    class="sidebar-bg fixed left-0 top-0 z-40 shadow-xl transition-all duration-300 ease-in-out flex flex-col"
    style="height: 100vh; overflow: hidden;"
>

    {{-- ── TOP BAR: NAVIGATION label + collapse toggle ───────────────────────── --}}
    <div class="flex items-center justify-between px-3 flex-shrink-0 sidebar-profile-border"
         style="height:4rem;">

        {{-- Mobile: close (×) button — no label on mobile --}}
        <button
            x-show="$store.appLayout.isMobile"
            @click="$store.appLayout.toggleSidebar()"
            class="flex items-center justify-center w-8 h-8 rounded-lg sidebar-collapse-btn transition-colors duration-200"
            aria-label="Close Sidebar"
        >
            <i class="fa-solid fa-xmark text-sm"></i>
        </button>

        {{-- Desktop only: centred NAVIGATION branded pill --}}
        <div class="hidden md:flex flex-1 items-center justify-center min-w-0 px-1">
            <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg"
                 style="background: rgba(255,255,255,0.97);
                        box-shadow: inset 0 1px 4px rgba(0,0,0,0.18), 0 1px 0 rgba(255,255,255,0.55);">
                <span class="w-1 h-5 rounded-full flex-shrink-0"
                      style="background: linear-gradient(180deg, #4338ca 0%, #6366f1 100%);"></span>
                <p class="font-extrabold tracking-wide leading-none whitespace-nowrap"
                   style="font-size: 0.8rem;
                          color: #3730a3;
                          text-shadow: 0 1px 0 rgba(255,255,255,0.8), 0 -1px 0 rgba(0,0,0,0.1);
                          letter-spacing: 0.08em;">
                    NAVIGATION
                </p>
            </div>
        </div>

        {{-- Desktop: collapse/expand chevron button --}}
        <button
            x-show="!$store.appLayout.isMobile"
            @click="$store.appLayout.toggleSidebar()"
            class="flex-shrink-0 flex items-center justify-center w-8 h-8 rounded-lg sidebar-collapse-btn transition-colors duration-200"
            aria-label="Toggle Sidebar"
        >
            <i class="fa-solid transition-transform duration-300"
               :class="$store.appLayout.sidebarOpen ? 'fa-chevron-left' : 'fa-chevron-right'"></i>
        </button>

    </div>

    {{-- ── SCROLLABLE NAV ─────────────────────────────────────────────────── --}}
    <nav class="sidebar-nav-scroll py-2 px-2" style="flex:1 1 0%; min-height:0; overflow-y:auto; overflow-x:hidden;">

        @foreach ($groups as $group)
        @if(count($group['links']) > 0)
        <div class="sidebar-group mb-1">

            {{-- Group header (only shown when sidebar is expanded) --}}
            <button
                x-show="$store.appLayout.sidebarOpen"
                @click="toggleGroup('{{ $group['key'] }}')"
                class="sidebar-group-label w-full flex items-center justify-between cursor-pointer"
                type="button"
                :aria-expanded="isGroupOpen('{{ $group['key'] }}')"
            >
                <span class="flex items-center gap-2">
                    <i class="fa-solid {{ $group['icon'] }} fa-fw text-xs"></i>
                    <span>{{ $group['label'] }}</span>
                </span>
                <i class="fa-solid fa-chevron-down text-[10px] sidebar-group-chevron transition-transform duration-200"
                   :class="isGroupOpen('{{ $group['key'] }}') ? 'rotate-180' : 'rotate-0'"></i>
            </button>

            {{-- Group items (collapsible; always visible in icon-only mode) --}}
            <div
                x-show="!$store.appLayout.sidebarOpen || isGroupOpen('{{ $group['key'] }}')"
                x-transition:enter="transition ease-out duration-200"
                x-transition:enter-start="opacity-0 -translate-y-1"
                x-transition:enter-end="opacity-100 translate-y-0"
                x-transition:leave="transition ease-in duration-150"
                x-transition:leave-start="opacity-100 translate-y-0"
                x-transition:leave-end="opacity-0 -translate-y-1"
            >
                @foreach ($group['links'] as $link)
                <a
                    href="{{ $link['url'] }}"
                    title="{{ $link['label'] }}"
                    class="flex items-center px-3 py-2.5 rounded-lg transition-all duration-200 role-themed-hover mb-0.5 sidebar-nav-link {{ $link['active'] ? 'active border-l-4' : '' }}"
                >
                    <i class="fa-solid {{ $link['icon'] }} fa-fw text-base {{ $link['active'] ? 'text-white' : 'text-indigo-300' }}"></i>
                    <span x-show="$store.appLayout.sidebarOpen" x-transition class="ml-3 font-medium text-sm text-inherit">{{ $link['label'] }}</span>
                </a>
                @endforeach
            </div>

        </div>
        @endif
        @endforeach

    </nav>

</aside>
