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 { contrastRatio } from './contrast.util';
import { IconComponent } from '../../../../shared/ui/icon/icon.component';

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

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

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

  readonly branding = computed(() => this.bootstrap()?.branding ?? null);
  readonly palette = computed(() => this.bootstrap()?.theme.palette ?? null);
  readonly typography = computed(() => this.bootstrap()?.theme.typography ?? null);

  readonly paletteSwatches = computed(() => {
    const palette = this.palette();
    if (!palette) {
      return [];
    }
    return [
      { key: 'primary', labelKey: 'builder.primaryColor', value: palette.primary },
      { key: 'secondary', labelKey: 'builder.secondaryColor', value: palette.secondary },
      { key: 'accent', labelKey: 'builder.brandAccentColor', value: palette.accent },
      { key: 'success', labelKey: 'builder.successColor', value: palette.success },
      { key: 'warning', labelKey: 'builder.warningColor', value: palette.warning },
      { key: 'danger', labelKey: 'builder.dangerColor', value: palette.danger },
      { key: 'backgroundPrimary', labelKey: 'builder.backgroundColor', value: palette.backgroundPrimary },
      { key: 'backgroundSecondary', labelKey: 'builder.surfaceColor', value: palette.backgroundSecondary },
      { key: 'textPrimary', labelKey: 'builder.textColor', value: palette.textPrimary },
      { key: 'border', labelKey: 'builder.brandBorderColor', value: palette.border },
    ];
  });

  /** Real WCAG contrast math against the real configured colors - null when a value isn't a parseable hex, never fabricated. */
  readonly textContrast = computed<number | null>(() => {
    const palette = this.palette();
    return palette ? contrastRatio(palette.textPrimary, palette.backgroundPrimary) : null;
  });

  readonly primaryContrast = computed<number | null>(() => {
    const palette = this.palette();
    return palette ? contrastRatio(palette.primary, palette.backgroundPrimary) : null;
  });

  readonly textContrastPasses = computed(() => {
    const ratio = this.textContrast();
    return ratio !== null && ratio >= 4.5;
  });

  readonly healthItems = computed<BrandHealthItem[]>(() => {
    const branding = this.branding();
    if (!branding) {
      return [];
    }
    return [
      { labelKey: 'builder.readinessLogoUploaded', ok: !!branding.logoUrl },
      { labelKey: 'builder.brandFaviconUploaded', ok: !!branding.faviconUrl },
      { labelKey: 'builder.brandColorsSelected', ok: !!this.palette() },
      { labelKey: 'builder.brandTypographyConfigured', ok: !!this.typography() },
      { labelKey: 'builder.brandSocialImageUploaded', ok: !!branding.socialImageUrl },
      { labelKey: 'builder.brandAccessibilityPassed', ok: this.textContrastPasses() },
    ];
  });

  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>(() => {
    const items = this.healthItems();
    const missing = items.find(i => !i.ok);
    return missing?.labelKey ?? null;
  });

  readonly socialTitle = computed(() => this.bootstrap()?.seo.default.title || this.branding()?.brandName || null);
  readonly socialDescription = computed(() => this.bootstrap()?.seo.default.description || null);

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