import {
  Component,
  OnInit,
  OnDestroy,
  AfterViewInit,
  inject,
  PLATFORM_ID,
  signal
} from '@angular/core';
import { isPlatformBrowser, NgOptimizedImage } from '@angular/common';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { RouterLink } from '@angular/router';
import { ReleaseService, DetectedOS } from '../../services/release.service';
import { SeoService } from '../../services/seo.service';
import { ScrollAnimationService } from '../../services/scroll-animation.service';
import { AdSlotComponent } from '../../components/ad-slot/ad-slot.component';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    NgOptimizedImage,
    TranslateModule,
    RouterLink,
    AdSlotComponent
  ],
  templateUrl: './home.component.html',
  styleUrl: './home.component.scss'
})
export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
  readonly detectedOS = signal<DetectedOS>({
    key: 'linux',
    icon: '🐧',
    filePattern: /\.AppImage$/i,
    ymlFile: 'latest-linux.yml'
  });
  readonly downloadUrl = signal<string | null>(null);
  readonly latestVersion = signal<string | null>(null);

  private readonly releaseService = inject(ReleaseService);
  private readonly seoService = inject(SeoService);
  private readonly scrollAnimation = inject(ScrollAnimationService);
  private readonly platformId = inject(PLATFORM_ID);
  private readonly translate = inject(TranslateService);

  ngOnInit(): void {
    this.seoService.updateFromTranslations('pages.home.seo', {
      url: 'https://toju.app/'
    });

    const os = this.releaseService.detectOS();

    this.detectedOS.set(os);

    this.releaseService.getLatestRelease().then((release) => {
      if (release) {
        this.latestVersion.set(release.tag_name);
      }
    });

    this.releaseService.getDownloadUrl(os).then((url) => {
      this.downloadUrl.set(url);
    });
  }

  ngAfterViewInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      setTimeout(() => this.scrollAnimation.init(), 100);
    }
  }

  ngOnDestroy(): void {
    this.scrollAnimation.destroy();
  }

  getDetectedOsLabel(): string {
    return this.translate.instant(`common.os.${this.detectedOS().key}`);
  }
}
