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

const YOUTUBE_EMBED_FALLBACK_ORIGIN = 'https://toju.app';

function resolveYoutubeClientOrigin(): string {
  if (typeof window === 'undefined') {
    return YOUTUBE_EMBED_FALLBACK_ORIGIN;
  }

  const origin = window.location.origin;

  return /^https?:\/\//.test(origin)
    ? origin
    : YOUTUBE_EMBED_FALLBACK_ORIGIN;
}

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

  readonly videoId = computed(() => extractYoutubeVideoId(this.url()));

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

    if (!id)
      return '';

    const clientOrigin = resolveYoutubeClientOrigin();
    const embedUrl = new URL(`https://www.youtube-nocookie.com/embed/${encodeURIComponent(id)}`);

    embedUrl.searchParams.set('origin', clientOrigin);
    embedUrl.searchParams.set('widget_referrer', clientOrigin);

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

  private readonly sanitizer = inject(DomSanitizer);
}
