import { DeesElement, customElement, html, css, cssManager, state, type TemplateResult } from '../plugins.js';
import { appState, type IAppState } from '../state/appstate.js';
import { viewHostCss } from './shared/index.js';

@customElement('sipproxy-view-log')
export class SipproxyViewLog extends DeesElement {
  @state() accessor appData: IAppState = appState.getState();

  private chartLog: any = null;
  private lastLogCount = 0;

  public static styles = [
    cssManager.defaultStyles,
    viewHostCss,
    css`
      dees-chart-log { height: calc(100vh - 140px); }
    `,
  ];

  connectedCallback() {
    super.connectedCallback();
    this.rxSubscriptions.push({
      unsubscribe: appState.subscribe((s) => {
        const prev = this.appData;
        this.appData = s;
        this.pushNewLogs(prev.logLines, s.logLines);
      }),
    } as any);
  }

  firstUpdated() {
    this.chartLog = this.shadowRoot?.querySelector('dees-chart-log');
  }

  private pushNewLogs(oldLines: string[], newLines: string[]) {
    if (!this.chartLog || !newLines.length) return;

    // Only push lines that are new since last update.
    const newCount = newLines.length;
    if (newCount <= this.lastLogCount) return;

    const fresh = newLines.slice(this.lastLogCount);
    this.lastLogCount = newCount;

    for (const line of fresh) {
      const level = this.detectLevel(line);
      this.chartLog.addLog(level, line);
    }
  }

  private detectLevel(line: string): 'debug' | 'info' | 'warn' | 'error' | 'success' {
    if (line.includes('[err]') || line.includes('error') || line.includes('ERR')) return 'error';
    if (line.includes('WARN') || line.includes('warn')) return 'warn';
    if (line.includes('registered') || line.includes('CONNECTED')) return 'success';
    if (line.includes('[rtp') || line.includes('[detect]')) return 'debug';
    return 'info';
  }

  public render(): TemplateResult {
    return html`
      <dees-heading level="3">Log</dees-heading>

      <dees-chart-log
        label="SIP Trace Log"
        mode="structured"
        .autoScroll=${true}
        .maxEntries=${500}
        .showMetrics=${true}
        .highlightKeywords=${['REGISTER', 'INVITE', 'BYE', 'registered', 'error', 'CONNECTED']}
      ></dees-chart-log>
    `;
  }
}
