@php
    $userRoles = auth()->check() ? auth()->user()->getRoleNames()->toArray() : [];
    $panelPrefix = '';
    if (in_array('super-admin', $userRoles)) {
        $panelPrefix = 'superadmin.';
    } elseif (in_array('admin', $userRoles) || in_array('amministratore', $userRoles)) {
        $panelPrefix = 'admin.';
    }
    
    // Variabili per la gestione stabile/anno
    $stabileAttivo = session('stabile_corrente', 'Seleziona Stabile');
    $annoAttivo = session('anno_corrente', date('Y'));
    $gestione = session('gestione_corrente', 'Ord.');
    $stabili = collect([
        (object)['denominazione' => 'Condominio Roma Centro'],
        (object)['denominazione' => 'Residence Milano Nord'],
        (object)['denominazione' => 'Palazzina Napoli Est'],
        (object)['denominazione' => 'Villa Torino Ovest']
    ]);

    $mainMenu = [
        [
            'icon' => 'fa-solid fa-home',
            'label' => 'Dashboard',
            'route' => $panelPrefix . 'dashboard',
            'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore', 'condomino'],
        ],
        [
            'icon' => 'fa-solid fa-building',
            'label' => 'Stabili',
            'route' => $panelPrefix . 'stabili.index',
            'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore'],
            'expandable' => true,
            'id' => 'stabili-menu',
            'submenu' => [
                [
                    'icon' => 'fa-solid fa-door-open',
                    'label' => 'Unità Immobiliari',
                    'route' => $panelPrefix . 'unitaImmobiliari.index',
                    'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore'],
                ],
                [
                    'icon' => 'fa-solid fa-address-book',
                    'label' => 'Anagrafica Condominiale',
                    'route' => $panelPrefix . 'anagrafica-condominiale.index',
                    'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore'],
                ],
                [
                    'icon' => 'fa-solid fa-table',
                    'label' => 'Tabelle Millesimali',
                    'route' => $panelPrefix . 'tabelle-millesimali.index',
                    'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore'],
                ],
            ]
        ],
        [
            'icon' => 'fa-solid fa-users',
            'label' => 'Soggetti',
            'route' => $panelPrefix . 'soggetti.index',
            'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore'],
        ],
        [
            'icon' => 'fa-solid fa-truck',
            'label' => 'Fornitori',
            'route' => $panelPrefix . 'fornitori.index',
            'roles' => ['admin', 'super-admin', 'amministratore', 'collaboratore'],
        ],
        [
            'icon' => 'fa-solid fa-file-invoice-dollar',
            'label' => 'Contabilità',
            'route' => $panelPrefix . 'contabilita.index',
            'roles' => ['admin', 'super-admin', 'amministratore'],
        ],
        [
            'icon' => 'fa-solid fa-ticket-simple',
            'label' => 'Tickets',
            'route' => $panelPrefix . 'tickets.index',
            'roles' => ['admin', 'super-admin', 'amministratore'],
        ],
        [
            'icon' => 'fa-solid fa-cog',
            'label' => 'Impostazioni',
            'route' => $panelPrefix . 'impostazioni',
            'roles' => ['admin', 'super-admin', 'amministratore'],
        ],
    ];
@endphp

<nav class="h-100 d-flex flex-column bg-warning border-end border-4 border-primary py-3 px-2 shadow">
    
    <!-- Header stabile/anno -->
    <div class="px-2 pt-2 pb-3 bg-warning-subtle border-bottom border-primary position-sticky top-0" style="z-index: 20;">
        <div class="d-flex flex-column align-items-center">
            <small class="text-muted mb-1">{{ $annoAttivo }}/{{ $gestione }}</small>
            <div class="d-flex align-items-center gap-2 bg-light rounded px-2 py-1 shadow-sm" style="min-width: 160px;">
                <div class="d-flex flex-column me-1">
                    <button id="prev-stabile" class="btn btn-primary btn-sm p-1 mb-1" style="width: 24px; height: 24px;" title="Stabile precedente">
                        <i class="fas fa-chevron-up" style="font-size: 10px;"></i>
                    </button>
                    <button id="next-stabile" class="btn btn-primary btn-sm p-1" style="width: 24px; height: 24px;" title="Stabile successivo">
                        <i class="fas fa-chevron-down" style="font-size: 10px;"></i>
                    </button>
                </div>
                <button id="current-stabile" class="btn btn-outline-primary btn-sm flex-fill text-start" title="Cambia stabile">
                    {{ $stabileAttivo }}
                </button>
            </div>
            <button id="toggle-darkmode" class="btn btn-dark btn-sm mt-2" title="Attiva/disattiva modalità scura">
                <i class="fas fa-moon me-1"></i>
                <span>Dark</span>
            </button>
        </div>
    </div>
    
    <!-- Menu principale -->
    <div class="flex-fill overflow-auto">
        <div class="list-group list-group-flush">
            @foreach($mainMenu as $item)
                @if(array_intersect($item['roles'], $userRoles))
                    @if(isset($item['expandable']) && $item['expandable'])
                        <!-- Menu item with submenu -->
                        <div class="menu-item-wrapper">
                            <button class="list-group-item list-group-item-action d-flex align-items-center justify-content-between border-0 {{ Route::currentRouteName() == $item['route'] ? 'active' : '' }}" 
                                    type="button" 
                                    data-bs-toggle="collapse" 
                                    data-bs-target="#submenu-{{ $item['id'] }}" 
                                    aria-expanded="false" 
                                    aria-controls="submenu-{{ $item['id'] }}">
                                <div class="d-flex align-items-center">
                                    <i class="{{ $item['icon'] }} me-2"></i>
                                    <span>{{ $item['label'] }}</span>
                                </div>
                                <i class="fas fa-chevron-down"></i>
                            </button>
                            <!-- Submenu -->
                            <div class="collapse" id="submenu-{{ $item['id'] }}">
                                <div class="list-group list-group-flush ms-3">
                                    @foreach($item['submenu'] as $subItem)
                                        @if(array_intersect($subItem['roles'], $userRoles))
                                            @if(Route::has($subItem['route']))
                                                <a href="{{ route($subItem['route']) }}" 
                                                   class="list-group-item list-group-item-action py-2 border-0 {{ Route::currentRouteName() == $subItem['route'] ? 'active' : '' }}">
                                                    <i class="{{ $subItem['icon'] }} me-2 text-sm"></i>
                                                    <span class="small">{{ $subItem['label'] }}</span>
                                                </a>
                                            @else
                                                <div class="list-group-item py-2 text-muted border-0" title="Funzionalità in sviluppo">
                                                    <i class="{{ $subItem['icon'] }} me-2 text-sm"></i>
                                                    <span class="small">{{ $subItem['label'] }}</span>
                                                    <i class="fas fa-code ms-auto small"></i>
                                                </div>
                                            @endif
                                        @endif
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    @else
                        <!-- Regular menu item -->
                        @if(Route::has($item['route']))
                            <a href="{{ route($item['route']) }}" 
                               class="list-group-item list-group-item-action d-flex align-items-center border-0 {{ Route::currentRouteName() == $item['route'] ? 'active' : '' }}">
                                <i class="{{ $item['icon'] }} me-2"></i>
                                <span>{{ $item['label'] }}</span>
                            </a>
                        @else
                            <div class="list-group-item py-2 text-muted d-flex align-items-center border-0" title="Funzionalità in sviluppo">
                                <i class="{{ $item['icon'] }} me-2"></i>
                                <span>{{ $item['label'] }}</span>
                                <i class="fas fa-code ms-auto small"></i>
                            </div>
                        @endif
                    @endif
                @endif
            @endforeach
        </div>
    </div>
    
    <!-- Footer -->
    <div class="mt-auto pt-3 border-top">
        <div class="text-center">
            <small class="text-muted">NetGesCon &copy; {{ date('Y') }}</small>
            <br>
            <small class="text-muted">v0.7.0-dev</small>
        </div>
    </div>
    
</nav>

<!-- Modale ricerca stabile -->
<div class="modal fade" id="modal-stabile" tabindex="-1" aria-labelledby="modalStabileLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalStabileLabel">Cerca stabile</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="text" id="input-stabile" class="form-control mb-3" placeholder="Digita il nome dello stabile...">
                <div id="result-stabile" class="list-group" style="max-height: 200px; overflow-y: auto;"></div>
            </div>
        </div>
    </div>
</div>

<script>
// Dati stabili
const stabili = @json($stabili->pluck('denominazione')->values()->toArray());
let currentIndex = stabili.indexOf(@json($stabileAttivo));
if(currentIndex === -1) currentIndex = 0;

// Dark mode toggle
const darkBtn = document.getElementById('toggle-darkmode');
if (darkBtn) {
    darkBtn.addEventListener('click', function() {
        document.documentElement.classList.toggle('dark');
        const isDark = document.documentElement.classList.contains('dark');
        localStorage.setItem('darkMode', isDark ? 'enabled' : 'disabled');
    });
}

// Inizializza dark mode da localStorage
if (localStorage.getItem('darkMode') === 'enabled') {
    document.documentElement.classList.add('dark');
}

// Gestione stabile
function updateStabile() {
    const button = document.getElementById('current-stabile');
    if (button) {
        button.textContent = stabili[currentIndex] || 'Nessuno selezionato';
    }
}

// Bottoni navigazione stabile
const prevBtn = document.getElementById('prev-stabile');
const nextBtn = document.getElementById('next-stabile');
const currentBtn = document.getElementById('current-stabile');

if (prevBtn) {
    prevBtn.onclick = function() {
        currentIndex = (currentIndex - 1 + stabili.length) % stabili.length;
        updateStabile();
    };
}

if (nextBtn) {
    nextBtn.onclick = function() {
        currentIndex = (currentIndex + 1) % stabili.length;
        updateStabile();
    };
}

if (currentBtn) {
    currentBtn.onclick = function() {
        const modal = new bootstrap.Modal(document.getElementById('modal-stabile'));
        modal.show();
        document.getElementById('input-stabile').value = '';
        document.getElementById('result-stabile').innerHTML = '';
    };
}

// Ricerca stabile
const inputStabile = document.getElementById('input-stabile');
if (inputStabile) {
    inputStabile.oninput = function(e) {
        const val = e.target.value.toLowerCase();
        const results = stabili.filter(s => s.toLowerCase().includes(val));
        const resultDiv = document.getElementById('result-stabile');
        resultDiv.innerHTML = results.map(s => 
            `<button type="button" class="list-group-item list-group-item-action" onclick="selectStabile('${s}')">${s}</button>`
        ).join('');
    };
}

// Selezione stabile
window.selectStabile = function(nome) {
    document.getElementById('current-stabile').textContent = nome;
    const modal = bootstrap.Modal.getInstance(document.getElementById('modal-stabile'));
    modal.hide();
    
    // Chiamata AJAX per aggiornare la sessione stabile_corrente
    fetch('/session/stabile', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({ stabile: nome })
    }).then(res => {
        if(res.ok) window.location.reload();
    });
};

// Inizializza stabile
updateStabile();
</script>
