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

const BLOCK_ICON_BY_TYPE: Record<string, AppIconName> = {
  hero: 'image',
  categories: 'layoutGrid',
  'product-collection': 'package',
  'product-carousel': 'images',
  'recently-viewed': 'history',
  banner: 'megaphone',
  partners: 'verified',
  html: 'code',
};

/**
 * Schematic (not pixel-accurate) representation of the storefront homepage,
 * built from the same bootstrap the section editors mutate. It exists so a
 * field can highlight "the area it affects" (§ PreviewHighlightService)
 * without re-navigating away like ProjectEditorPreviewService.preview() does.
 */
@Component({
  selector: 'app-builder-live-preview',
  standalone: true,
  imports: [TranslatePipe, IconComponent],
  templateUrl: './builder-live-preview.component.html',
  styleUrl: './builder-live-preview.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class BuilderLivePreviewComponent {
  private readonly facade = inject(ProjectEditorFacade);
  private readonly highlight = inject(PreviewHighlightService);

  readonly bootstrap = this.facade.bootstrap;
  readonly homepagePage = this.facade.homepagePage;
  readonly activeHighlight = this.highlight.activeId;

  readonly blocks = computed(() =>
    [...(this.homepagePage()?.sections ?? [])]
      .sort((a, b) => a.order - b.order)
      .map(section => ({
        id: section.id,
        type: section.type,
        strategy: section.layout?.strategy ?? 'stack',
        columns: section.layout?.columns ?? 1,
        visible: section.visible !== false,
        icon: BLOCK_ICON_BY_TYPE[section.type] ?? 'stop',
      }))
  );

  isActive(id: string): boolean {
    return this.activeHighlight() === id;
  }
}
