import {
  Component,
  computed,
  inject,
  input
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { extractSpotifyResource } from '../../../../../domain/rules/link-embed.rules';

@Component({
  selector: 'app-chat-spotify-embed',
  standalone: true,
  templateUrl: './chat-spotify-embed.component.html'
})
export class ChatSpotifyEmbedComponent {
  readonly url = input.required<string>();

  readonly resource = computed(() => extractSpotifyResource(this.url()));

  readonly embedHeight = computed(() => {
    const resource = this.resource();

    if (!resource) {
      return 0;
    }

    switch (resource.type) {
      case 'track':
      case 'episode':
        return 152;
      default:
        return 352;
    }
  });

  readonly embedUrl = computed(() => {
    const resource = this.resource();

    if (!resource) {
      return '';
    }

    const embedUrl = new URL(`https://open.spotify.com/embed/${resource.type}/${encodeURIComponent(resource.id)}`);

    embedUrl.searchParams.set('utm_source', 'generator');

    return this.sanitizer.bypassSecurityTrustResourceUrl(embedUrl.toString());
  });

  private readonly sanitizer = inject(DomSanitizer);
}
