---
export interface Props {
  userName?: string;
  userEmail?: string;
  class?: string;
}

const {
  userName = '',
  userEmail = '',
  class: className = '',
}: Props = Astro.props;

// Получаем первую букву имени
const firstLetter = userName ? userName.charAt(0).toUpperCase() : userEmail?.charAt(0).toUpperCase() || 'U';
---

<div class={`user-menu ${className}`}>
  <div class="user-avatar" title={userName || userEmail}>
    {firstLetter}
  </div>
  
  <button class="logout-btn" id="logout-btn" title="Выйти">
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
      <polyline points="16 17 21 12 16 7"></polyline>
      <line x1="21" y1="12" x2="9" y2="12"></line>
    </svg>
    <span class="logout-text">Выход</span>
  </button>
</div>

<style>
  .user-menu {
    display: flex;
    align-items: center;
    gap: 0.75rem;
  }

  .user-avatar {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%);
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 1.1rem;
    cursor: default;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }

  .user-avatar:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(206, 159, 64, 0.4);
  }

  .logout-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1rem;
    background: transparent;
    border: 2px solid #1e3050;
    border-radius: 8px;
    color: #1e3050;
    font-weight: 600;
    font-size: 0.9rem;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .logout-btn:hover {
    background: #1e3050;
    color: #ffffff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .logout-btn:active {
    transform: translateY(0);
  }

  @media (max-width: 992px) {
    .logout-text {
      display: none;
    }
    
    .logout-btn {
      padding: 0.6rem;
    }
  }
</style>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const logoutBtn = document.getElementById('logout-btn');
    
    logoutBtn?.addEventListener('click', async () => {
      try {
        await fetch('/api/auth/logout', {
          method: 'POST',
        });
      } catch (e) {
        console.error('Logout error:', e);
      }
      
      // Очищаем localStorage
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user');
      
      // Перенаправляем на главную
      window.location.href = '/';
    });
  });
</script>