import { ChangeDetectionStrategy, Component, SecurityContext, computed, inject, input, signal } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';

export type PreviewDevice = 'desktop' | 'tablet' | 'mobile';

interface DevicePreset {
  readonly id: PreviewDevice;
  readonly labelKey: string;
  readonly width: string;
}

const DEVICE_PRESETS: readonly DevicePreset[] = [
  { id: 'desktop', labelKey: 'staticPages.previewDesktop', width: '100%' },
  { id: 'tablet', labelKey: 'staticPages.previewTablet', width: '768px' },
  { id: 'mobile', labelKey: 'staticPages.previewMobile', width: '375px' },
];

/**
 * Client-side, sanitized preview of a static page's HTML at desktop/tablet/
 * mobile widths - no navigation, no publish, no dependency on
 * ProjectEditorPreviewService's full-app reload. Uses the same
 * DomSanitizer.sanitize(SecurityContext.HTML, ...) pattern as the real
 * storefront renderer (StaticPageComponent) so what you preview here is
 * exactly what will render live.
 */
@Component({
  selector: 'app-static-page-preview',
  standalone: true,
  imports: [TranslatePipe, ButtonComponent],
  templateUrl: './static-page-preview.component.html',
  styleUrl: './static-page-preview.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class StaticPagePreviewComponent {
  private readonly sanitizer = inject(DomSanitizer);

  readonly html = input.required<string>();
  readonly title = input<string>('');

  readonly devices = DEVICE_PRESETS;
  readonly activeDevice = signal<PreviewDevice>('desktop');

  readonly activeWidth = computed(() => this.devices.find(device => device.id === this.activeDevice())?.width ?? '100%');

  readonly safeHtml = computed<SafeHtml>(() => {
    const sanitized = this.sanitizer.sanitize(SecurityContext.HTML, this.html()) ?? '';
    return this.sanitizer.bypassSecurityTrustHtml(sanitized);
  });

  setDevice(device: PreviewDevice): void {
    this.activeDevice.set(device);
  }
}
