import { ChangeDetectionStrategy, Component, computed, inject, input, signal } from '@angular/core';
import { take } from 'rxjs/operators';
import { SOCIAL_IDENTITY_GATEWAY } from '../../core/identity/services/social-identity-gateway.token';
import { SocialProvider } from '../../core/identity/services/social-identity-gateway.interface';
import { IconComponent } from '../../shared/ui/icon/icon.component';

const PROVIDER_LABEL: Record<SocialProvider, string> = {
  vk: 'Continue with VK ID',
  yandex: 'Continue with Yandex ID',
};

/**
 * One button per social provider, per v3.1 §14 (VK ID is the primary
 * storefront social login; Yandex ID is the second instance of the same
 * flow, not a separate integration).
 *
 * Deliberately not spliced into TelegramLoginComponent's dialog yet. That
 * component is the live customer login surface, and adding providers to it
 * belongs in the pass that also demotes Telegram to one ExternalIdentity
 * among several (FH-4.6) - not before a real OAuth application exists to
 * test against.
 */
@Component({
  selector: 'app-social-login-button',
  standalone: true,
  imports: [IconComponent],
  templateUrl: './social-login-button.component.html',
  styleUrls: ['./social-login-button.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SocialLoginButtonComponent {
  private readonly gateway = inject(SOCIAL_IDENTITY_GATEWAY);

  readonly provider = input.required<SocialProvider>();
  /** Where to land after the callback. Validated backend-side. */
  readonly returnTo = input<string | undefined>(undefined);

  readonly loading = signal(false);
  readonly label = computed(() => PROVIDER_LABEL[this.provider()]);

  startLogin(): void {
    this.loading.set(true);
    this.gateway
      .getAuthorizeUrl(this.provider(), this.returnTo())
      .pipe(take(1))
      .subscribe({
        next: url => {
          this.loading.set(false);
          if (typeof window !== 'undefined') {
            window.location.href = url;
          }
        },
        error: () => this.loading.set(false),
      });
  }
}
