import { Component, HostListener, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'app-sidebar',
  standalone: false,
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css'],
  animations: [
    trigger('sidebarState', [
      state('expanded', style({
        width: '220px',
        opacity: 1
      })),
      state('collapsed', style({
        width: '70px',
        opacity: 0.95
      })),
      transition('expanded <=> collapsed', [
        animate('300ms ease-in-out')
      ])
    ])
  ]
})
export class SidebarComponent implements OnInit {
  isOpen = true;      // ขยายไหม
  isMobile = false;   // ตรวจอุปกรณ์
  showOverlay = false; // สำหรับ mobile overlay

  constructor(private router: Router) {}

  ngOnInit() {
    this.checkDevice();
    window.addEventListener('resize', () => this.checkDevice());
  }

  @HostListener('window:resize')
  checkDevice() {
    this.isMobile = window.innerWidth <= 768;
    if (this.isMobile) {
      this.isOpen = false; // ซ่อน sidebar ตอนเข้า mobile
    } else {
      this.isOpen = true;  // เปิดไว้ตลอดใน desktop
      this.showOverlay = false;
    }
  }

  toggleSidebar() {
    if (this.isMobile) {
      this.showOverlay = !this.showOverlay;
      this.isOpen = this.showOverlay;
    } else {
      this.isOpen = !this.isOpen;
    }
  }

  navigate(path: string) {
    this.router.navigate([path]);
  }

  logout() {
    localStorage.removeItem('access_token');
    this.router.navigate(['/login']);
  }
}
