<template>
  <header class="app-header">
    <button class="sidebar-toggle" @click="$emit('toggle-sidebar')">
      <i class="pi pi-bars"></i>
    </button>
    <div class="logo">
      <img src="/LaneBowLogo.png" alt="LaneBow" class="logo-img header-logo" />
      <div class="app-title">볼링 클럽 매니저</div>
    </div>
    
    <div v-if="isLoggedIn" class="header-actions">
      <!-- 관리자 메뉴 -->
      <div v-if="isAdmin" class="admin-menu-wrapper">
        <Button @click="toggleAdminMenu" class="admin-menu-button p-button-outlined">
          <i class="pi pi-cog"></i>        
        </Button>
        <Menu ref="adminMenu" :model="adminMenuItems" :popup="true" />
      </div>
      <!-- 알림 버튼 -->
      <div class="notification-wrapper">
        <Button icon="pi pi-bell" class="notification-button p-button-outlined" @click="toggleNotifications"
          :badge="unreadNotificationsCount > 0 ? unreadNotificationsCount.toString() : undefined" 
          badgeClass="p-badge-danger" />
        <div v-if="showNotifications" class="notifications-panel">
          <div class="notifications-header">
            <h3>알림</h3>
            <Button icon="pi pi-times" class="p-button-text p-button-rounded" @click="showNotifications = false" />
          </div>
          <div class="notifications-content">
            <div v-if="notifications.length > 0">
              <div v-for="(notification, index) in notifications" :key="index" 
                class="notification-item" 
                :class="{ 'unread': !notification.read }"
                @click="handleNotificationClick(notification)">
                <i :class="notification.icon"></i>
                <div class="notification-details">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-message">{{ notification.message }}</div>
                  <div class="notification-time">{{ notification.time }}</div>
                </div>
                <Button icon="pi pi-trash" class="p-button-text p-button-rounded" @click="deleteNotification(notification.id, $event)" />
              </div>
            </div>
            <div v-else class="no-notifications">
              <i class="pi pi-info-circle"></i>
              <p>새로운 알림이 없습니다.</p>
            </div>
          </div>
          <div class="notifications-footer">
            <Button label="모든 알림 읽음 표시" class="p-button-text" @click="markAllAsRead" />
          </div>
        </div>
      </div>
      
      <!-- 클럽 추가 버튼 -->
      <div class="club-add-wrapper">
        <Button icon="pi pi-plus-circle" class="club-add-button p-button-outlined" @click="goToClubCreate"
          title="새 클럽 만들기" />
      </div>
      
      <!-- 사용자 메뉴 -->
      <div class="user-menu-wrapper">
        <Button @click="toggleUserMenu" class="user-menu-button p-button-outlined">
          <Avatar :image="userAvatar" :label="userInitials" size="normal" shape="circle" />
          <span class="user-name hide-on-mobile">{{ userName }}</span>
          <i class="pi pi-chevron-down"></i>
        </Button>
        <Menu ref="userMenu" :model="userMenuItems" :popup="true" />
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, computed, inject, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { API_URL } from '../config';
import Button from 'primevue/button';
import Menu from 'primevue/menu';
import Avatar from 'primevue/avatar';

const router = useRouter();
const userMenu = ref(null);
const adminMenu = ref(null);
const isLoggedIn = computed(() => !!user.value);
const isAdmin = computed(() => {
  const role = localStorage.getItem('userRole');
  return role === 'admin' || role === 'superadmin';
});

// 사용자 정보 (App.vue에서 공유)
const user = inject('user');

// 사용자 정보 computed 속성
const userName = computed(() => user.value?.name || '사용자');
const userInitials = computed(() => {
  if (!user.value?.name) return '';
  return user.value.name.split(' ').map(n => n[0]).join('');
});
const userAvatar = computed(() => user.value?.avatar || '');

// 로그아웃
const logout = () => {
  user.value = null;
  localStorage.removeItem('token');
  localStorage.removeItem('clubId');
  localStorage.removeItem('userRole');
  router.push('/login');
};

// 알림 관련 상태
const showNotifications = ref(false);
const notifications = ref([]);
const unreadNotificationsCount = ref(0);

// 알림 가져오기
const fetchNotifications = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    const response = await axios.get(`${API_URL}/notifications`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    
    if (response.data) {
      notifications.value = response.data.map(notification => {
        const createdAt = new Date(notification.createdAt);
        const now = new Date();
        const diffMs = now - createdAt;
        const diffMins = Math.round(diffMs / 60000);
        const diffHours = Math.round(diffMs / 3600000);
        const diffDays = Math.round(diffMs / 86400000);
        
        let timeText = '';
        if (diffMins < 60) {
          timeText = `${diffMins}분 전`;
        } else if (diffHours < 24) {
          timeText = `${diffHours}시간 전`;
        } else {
          timeText = `${diffDays}일 전`;
        }
        
        return {
          id: notification._id,
          icon: notification.icon || 'pi pi-info-circle',
          title: notification.title,
          message: notification.message,
          time: timeText,
          read: notification.read,
          link: notification.link
        };
      });
      
      unreadNotificationsCount.value = notifications.value.filter(n => !n.read).length;
    }
  } catch (error) {
    console.error('알림 가져오기 오류:', error);
  }
};

// 모든 알림 읽음 표시
const markAllAsRead = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    await axios.put(`${API_URL}/notifications/read-all`, {}, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    
    notifications.value = notifications.value.map(notification => ({
      ...notification,
      read: true
    }));
    
    unreadNotificationsCount.value = 0;
  } catch (error) {
    console.error('모든 알림 읽음 표시 오류:', error);
  }
};

// 단일 알림 읽음 표시
const markAsRead = async (notificationId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    await axios.put(`${API_URL}/notifications/${notificationId}/read`, {}, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    
    const index = notifications.value.findIndex(n => n.id === notificationId);
    if (index !== -1) {
      notifications.value[index].read = true;
      unreadNotificationsCount.value = notifications.value.filter(n => !n.read).length;
    }
  } catch (error) {
    console.error('알림 읽음 표시 오류:', error);
  }
};

// 알림 클릭 처리
const handleNotificationClick = (notification) => {
  if (!notification.read) {
    markAsRead(notification.id);
  }
  
  if (notification.link) {
    router.push(notification.link);
    showNotifications.value = false;
  }
};

// 알림 삭제
const deleteNotification = async (notificationId, event) => {
  event.stopPropagation();
  
  try {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    await axios.delete(`${API_URL}/notifications/${notificationId}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    
    notifications.value = notifications.value.filter(n => n.id !== notificationId);
    unreadNotificationsCount.value = notifications.value.filter(n => !n.read).length;
  } catch (error) {
    console.error('알림 삭제 오류:', error);
  }
};

// 관리자 메뉴 아이템
const adminMenuItems = ref([
  {
    label: '대시보드',
    icon: 'pi pi-home',
    command: () => {
      router.push('/admin');
    }
  },
  {
    label: '클럽 관리',
    icon: 'pi pi-users',
    command: () => {
      router.push('/admin/clubs');
    }
  },
  {
    label: '사용자 관리',
    icon: 'pi pi-user',
    command: () => {
      router.push('/admin/users');
    }
  },
  {
    label: '구독 관리',
    icon: 'pi pi-credit-card',
    command: () => {
      router.push('/admin/subscriptions');
    }
  },
  {
    label: '활동 로그',
    icon: 'pi pi-history',
    command: () => {
      router.push('/admin/activity-logs');
    }
  }
]);

// 사용자 메뉴 아이템
const userMenuItems = ref([
  {
    label: '프로필',
    icon: 'pi pi-user',
    command: () => {
      router.push('/profile');
    }
  },
  {
    separator: true
  },
  {
    label: '로그아웃',
    icon: 'pi pi-power-off',
    command: logout
  }
]);

const toggleUserMenu = (event) => {
  userMenu.value.toggle(event);
};

const toggleAdminMenu = (event) => {
  adminMenu.value.toggle(event);
};

// 메뉴 토글
const toggleNotifications = (event) => {
  showNotifications.value = !showNotifications.value;
  event.stopPropagation();
};

// 클럽 생성 페이지로 이동
const goToClubCreate = () => {
  router.push({ name: 'UserClubCreate' });
};

// 문서 클릭 시 알림 패널 닫기
const handleDocumentClick = (event) => {
  const notificationWrapper = document.querySelector('.notification-wrapper');
  if (notificationWrapper && !notificationWrapper.contains(event.target)) {
    showNotifications.value = false;
  }
};

// 컴포넌트 마운트/언마운트
onMounted(() => {
  if (isLoggedIn.value) {
    fetchNotifications();
  }
  document.addEventListener('click', handleDocumentClick);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick);
});
</script>

<style scoped>
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: #1976d2;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.logo-img {
  height: 70px;
  width: auto;
  margin-bottom: 0.3rem;
}
.app-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: white;
  letter-spacing: 1px;
  text-shadow: 0 2px 4px rgba(0,0,0,1);
  margin-bottom: 0;
  margin-top: -30px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.user-menu-wrapper,
.admin-menu-wrapper,
.notification-wrapper,
.club-add-wrapper {
  position: relative;
}

.user-menu-button,
.admin-menu-button,
.notification-button,
.club-add-button {
  background-color: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: white !important;
}

.user-menu-button:hover,
.admin-menu-button:hover,
.notification-button:hover,
.club-add-button:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.user-menu-button {
  display: flex;
  align-items: center;
  padding: 0.5rem 1rem;
}

.user-name {
  margin: 0 0.5rem;
}

.notifications-panel {
  position: absolute;
  top: 45px;
  right: 0;
  width: 320px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1001;
  color: #333;
}

.notifications-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.notifications-header h3 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 500;
}

.notifications-content {
  max-height: 350px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 1rem;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: #f5f5f5;
}

.notification-item.unread {
  background-color: #f0f7ff;
  border-left: 3px solid #1976d2;
}

.notification-item i {
  font-size: 1.2rem;
  color: #1976d2;
  margin-right: 0.75rem;
  margin-top: 0.25rem;
}

.notification-details {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.notification-message {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 0.25rem;
  word-wrap: break-word;
}

.notification-time {
  font-size: 0.8rem;
  color: #999;
}

.no-notifications {
  padding: 2rem;
  text-align: center;
  color: #666;
}

.no-notifications i {
  font-size: 2rem;
  color: #ccc;
  margin-bottom: 0.5rem;
}

.notifications-footer {
  padding: 0.75rem;
  text-align: center;
  border-top: 1px solid #eee;
}

:deep(.p-menu) {
  z-index: 1001 !important;
}

@media (max-width: 767px) {
  .hide-on-mobile {
    display: none;
  }
  
  .app-header {
    padding: 1rem;
  }
  
  .notifications-panel {
    position: fixed;
    top: 64px;
    left: 0;
    right: 0;
    width: auto;
    margin: 0.5rem;
  }
}
.header-logo {
  height: 60px;
  transition: height 0.2s;
}

.sidebar-toggle {
  display: none;
  background: none;
  border: none;
  font-size: 2rem;
  margin-right: 10px;
  cursor: pointer;
}

@media (max-width: 600px) {
  .header-logo {
    height: 36px;
  }
  .app-title {
    font-size: .8rem;
    margin-top: -10px;
  }
  .sidebar-toggle {
    display: block;
  }
}
</style>
