<!-- Language selector for sidebar/offcanvas -->
<div class="dropdown nav">
    <a class="nav-link dropdown-toggle py-1 px-0" href="#" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" aria-label="{{ __('locale.' . app()->getLocale()) }}">
        <div class="ratio ratio-1x1" style="width: 20px">
            <img src="/img/flags/{{ app()->getLocale() === 'en' ? 'en-us' : 'id' }}.png" alt="{{ __('locale.' . app()->getLocale()) }}">
        </div>
    </a>
    <ul class="dropdown-menu fs-sm" style="--cz-dropdown-spacer: .5rem">
        <li>
            <a class="dropdown-item {{ app()->getLocale() === 'en' ? 'active' : '' }}" href="#" onclick="switchLanguageSidebar('en')">
                <img src="/img/flags/en-us.png" class="flex-shrink-0 me-2" width="20" alt="United States">
                {{ __('languages.en') }}
            </a>
        </li>
    
        <li>
            <a class="dropdown-item {{ app()->getLocale() === 'id' ? 'active' : '' }}" href="#" onclick="switchLanguageSidebar('id')">
                <img src="/img/flags/id.png" class="flex-shrink-0 me-2" width="20" alt="Indonesia">
                {{ __('languages.id') }}
            </a>
        </li>
     
    </ul>
</div>

<script>
function switchLanguageSidebar(locale) {
    // Store language in session via AJAX
    fetch('/locale/switch', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({
            locale: locale
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload page to reflect changes
            window.location.reload();
        }
    })
    .catch(error => console.error('Error switching language:', error));
}
</script>
