import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { LanguageService } from '../../../../services/language.service';
import { ProjectEditorFacade } from '../../facade/project-editor.facade';
import { IconComponent } from '../../../../shared/ui/icon/icon.component';

interface HomepageHealthItem {
  labelKey: string;
  ok: boolean;
}

@Component({
  selector: 'app-homepage-overview',
  standalone: true,
  imports: [TranslatePipe, IconComponent],
  templateUrl: './homepage-overview.component.html',
  styleUrl: './homepage-overview.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomepageOverviewComponent {
  private readonly facade = inject(ProjectEditorFacade);
  private readonly languageService = inject(LanguageService);

  readonly bootstrap = this.facade.bootstrap;
  readonly widgets = this.facade.homepageWidgets;
  readonly lastSavedAt = this.facade.lastSavedAt;

  private hasType(...keywords: string[]): boolean {
    return this.widgets().some(w => keywords.some(k => w.widget.type.toLowerCase().includes(k)));
  }

  readonly activeCount = computed(() => this.widgets().filter(w => w.widget.visible !== false).length);
  readonly disabledCount = computed(() => this.widgets().filter(w => w.widget.visible === false).length);

  readonly healthItems = computed<HomepageHealthItem[]>(() => {
    if (!this.bootstrap()) {
      return [];
    }
    return [
      { labelKey: 'builder.homepageHealthHero', ok: this.hasType('hero') },
      { labelKey: 'builder.homepageHealthCategories', ok: this.hasType('categor') },
      { labelKey: 'builder.homepageHealthProducts', ok: this.hasType('product') },
      { labelKey: 'builder.homepageHealthPromotion', ok: this.hasType('promo', 'banner') },
      { labelKey: 'builder.homepageHealthNewsletter', ok: this.hasType('newsletter') },
      { labelKey: 'builder.homepageHealthAnySections', ok: this.widgets().length > 0 },
    ];
  });

  readonly completionPercent = computed(() => {
    const items = this.healthItems();
    if (items.length === 0) {
      return null;
    }
    return Math.round((items.filter(i => i.ok).length / items.length) * 100);
  });

  readonly ringBackground = computed(() => {
    const pct = this.completionPercent() ?? 0;
    return `conic-gradient(var(--primary-color) ${pct}%, var(--bg-tertiary) 0)`;
  });

  readonly nextStepKey = computed<string | null>(() => this.healthItems().find(i => !i.ok)?.labelKey ?? null);

  formattedLastSaved(): string | null {
    const timestamp = this.lastSavedAt();
    return timestamp ? new Date(timestamp).toLocaleString(this.languageService.currentLanguage()) : null;
  }
}
