/**
 * Sidebar Controller
 *
 * Handles sidebar collapse/expand and tooltip functionality
 */

export class SidebarController {
  private menuToggle: HTMLElement | null = null;
  private appLayout: HTMLElement | null = null;
  private menuTooltip: HTMLElement | null = null;

  constructor() {
    this.menuToggle = document.getElementById('menuToggle');
    this.appLayout = document.querySelector('swp-app-layout');
    this.menuTooltip = document.getElementById('menuTooltip');

    this.setupListeners();
    this.setupTooltips();
    this.restoreState();
  }

  /**
   * Check if sidebar is collapsed
   */
  get isCollapsed(): boolean {
    return this.appLayout?.classList.contains('menu-collapsed') ?? false;
  }

  /**
   * Toggle sidebar collapsed state
   */
  toggle(): void {
    if (!this.appLayout) return;

    this.appLayout.classList.toggle('menu-collapsed');
    localStorage.setItem('sidebar-collapsed', String(this.isCollapsed));
  }

  /**
   * Collapse the sidebar
   */
  collapse(): void {
    this.appLayout?.classList.add('menu-collapsed');
    localStorage.setItem('sidebar-collapsed', 'true');
  }

  /**
   * Expand the sidebar
   */
  expand(): void {
    this.appLayout?.classList.remove('menu-collapsed');
    localStorage.setItem('sidebar-collapsed', 'false');
  }

  private setupListeners(): void {
    this.menuToggle?.addEventListener('click', () => this.toggle());
  }

  private setupTooltips(): void {
    if (!this.menuTooltip) return;

    const menuItems = document.querySelectorAll<HTMLElement>('swp-side-menu-item[data-tooltip]');

    menuItems.forEach(item => {
      item.addEventListener('mouseenter', () => this.showTooltip(item));
      item.addEventListener('mouseleave', () => this.hideTooltip());
    });
  }

  private showTooltip(item: HTMLElement): void {
    if (!this.isCollapsed || !this.menuTooltip) return;

    const rect = item.getBoundingClientRect();
    const tooltipText = item.dataset.tooltip;

    if (!tooltipText) return;

    this.menuTooltip.textContent = tooltipText;
    this.menuTooltip.style.left = `${rect.right + 8}px`;
    this.menuTooltip.style.top = `${rect.top + rect.height / 2}px`;
    this.menuTooltip.style.transform = 'translateY(-50%)';
    this.menuTooltip.showPopover();
  }

  private hideTooltip(): void {
    this.menuTooltip?.hidePopover();
  }

  private restoreState(): void {
    if (!this.appLayout) return;

    if (localStorage.getItem('sidebar-collapsed') === 'true') {
      this.appLayout.classList.add('menu-collapsed');
    }
  }
}
