import { Component, EventEmitter, Input, Output } from '@angular/core';
import { CommonModule } from '@angular/common';

type Station = { station_id: string; device_type?: string; name?: string; station_alias?: string; location?: string; last_update?: string };

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './header.component.html'
})
export class HeaderComponent {
  @Input() onlineDevices = 0;
  @Input() stations: Station[] = [];
  @Output() selectStation = new EventEmitter<{ stationId: string, hex: string }>();

  modalOpen = false;
  currentPage = 1;
  itemsPerPage = 10;

  get wh65Count(): number { return (this.stations||[]).filter(s => s.device_type === 'WH65LP').length; }
  get totalPages(): number { return Math.max(1, Math.ceil(this.stations.length / this.itemsPerPage)); }
  get pageItems(): Station[] {
    const start = (this.currentPage - 1) * this.itemsPerPage;
    return this.stations.slice(start, start + this.itemsPerPage);
  }

  open() { this.modalOpen = true; this.currentPage = 1; }
  close() { this.modalOpen = false; }
  prev() { if (this.currentPage > 1) this.currentPage--; }
  next() { if (this.currentPage < this.totalPages) this.currentPage++; }

  hexSuffix(s: Station): string {
    const id = s.station_id || '';
    if (id.length <= 6) return id.toUpperCase();
    return id.slice(-6).toUpperCase();
  }

  isOnline(s: Station): boolean {
    const lu = (s as any).last_update as string | undefined;
    if (!lu) return false;
    const t = new Date(lu.replace(' ', 'T')).getTime();
    if (isNaN(t)) return false;
    return Date.now() - t <= 5 * 60 * 1000;
  }

  choose(s: Station) {
    const hex = this.hexSuffix(s);
    if (hex) this.selectStation.emit({ stationId: s.station_id, hex });
    this.close();
  }
}
