/**
 * StatusBar Component
 *
 * 显示状态栏
 */

import blessed from 'blessed';
import type { Widgets } from 'blessed';

export interface StatusBarOptions {
  parent: Widgets.Screen;
  bottom: number;
}

export interface StatusInfo {
  serverUrl: string;
  connected: boolean;
  sessionId?: string;
  sessionName?: string;
  agentAvailable: boolean;
}

export class StatusBar {
  private container: Widgets.BoxElement;
  private status: StatusInfo = {
    serverUrl: '',
    connected: false,
    agentAvailable: false,
  };

  constructor(options: StatusBarOptions) {
    this.container = blessed.box({
      parent: options.parent,
      bottom: options.bottom,
      left: 0,
      right: 0,
      height: 1,
      tags: true,
      style: {
        bg: 'blue',
        fg: 'white',
      },
    });

    this.updateContent();
  }

  /**
   * 更新状态
   */
  setStatus(status: Partial<StatusInfo>): void {
    this.status = { ...this.status, ...status };
    this.updateContent();
  }

  /**
   * 更新显示内容
   */
  private updateContent(): void {
    const parts: string[] = [];

    // 连接状态
    const connIcon = this.status.connected ? '{green-fg}●{/green-fg}' : '{red-fg}●{/red-fg}';
    parts.push(`${connIcon} ${this.status.serverUrl || 'Not connected'}`);

    // Agent 状态
    if (this.status.connected) {
      const agentIcon = this.status.agentAvailable ? '{green-fg}✓{/green-fg}' : '{yellow-fg}✗{/yellow-fg}';
      parts.push(`Agent: ${agentIcon}`);
    }

    // 当前会话
    if (this.status.sessionId) {
      const name = this.status.sessionName || this.status.sessionId.slice(0, 8);
      parts.push(`Session: ${name}`);
    }

    // 快捷键提示
    parts.push('{gray-fg}Tab: Switch  q: Quit{/gray-fg}');

    this.container.setContent(' ' + parts.join('  │  '));
    this.render();
  }

  /**
   * 渲染
   */
  render(): void {
    this.container.screen.render();
  }

  /**
   * 销毁
   */
  destroy(): void {
    this.container.destroy();
  }

  /**
   * 获取容器元素
   */
  getElement(): Widgets.BoxElement {
    return this.container;
  }
}
