export class HeaderDrawerManager {
  private drawer!: HTMLElement;
  private expanded = false;
  private currentRows = 0;
  private readonly rowHeight = 25;
  private readonly duration = 200;

  init(container: HTMLElement): void {
    this.drawer = container.querySelector('swp-header-drawer')!;

    if (!this.drawer) console.error('HeaderDrawerManager: swp-header-drawer not found');
  }

  toggle(): void {
    this.expanded ? this.collapse() : this.expand();
  }

  /**
   * Expand drawer to single row (legacy support)
   */
  expand(): void {
    this.expandToRows(1);
  }

  /**
   * Expand drawer to fit specified number of rows
   */
  expandToRows(rowCount: number): void {
    const targetHeight = rowCount * this.rowHeight;
    const currentHeight = this.expanded ? this.currentRows * this.rowHeight : 0;

    // Skip if already at target
    if (this.expanded && this.currentRows === rowCount) return;

    this.currentRows = rowCount;
    this.expanded = true;
    this.animate(currentHeight, targetHeight);
  }

  collapse(): void {
    if (!this.expanded) return;
    const currentHeight = this.currentRows * this.rowHeight;
    this.expanded = false;
    this.currentRows = 0;
    this.animate(currentHeight, 0);
  }

  private animate(from: number, to: number): void {
    const keyframes = [
      { height: `${from}px` },
      { height: `${to}px` }
    ];
    const options: KeyframeAnimationOptions = {
      duration: this.duration,
      easing: 'ease',
      fill: 'forwards'
    };

    // Kun animér drawer - ScrollManager synkroniserer header-spacer via ResizeObserver
    this.drawer.animate(keyframes, options);
  }

  isExpanded(): boolean {
    return this.expanded;
  }

  getRowCount(): number {
    return this.currentRows;
  }
}
