/* eslint-disable max-statements-per-line */ import { Component, inject, signal } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { NgIcon, provideIcons } from '@ng-icons/core'; import { lucideUserPlus } from '@ng-icons/lucide'; import { AuthService } from '../../../core/services/auth.service'; import { ServerDirectoryService } from '../../../core/services/server-directory.service'; import { UsersActions } from '../../../store/users/users.actions'; import { User } from '../../../core/models/index'; import { STORAGE_KEY_CURRENT_USER_ID } from '../../../core/constants'; @Component({ selector: 'app-register', standalone: true, imports: [ CommonModule, FormsModule, NgIcon ], viewProviders: [provideIcons({ lucideUserPlus })], templateUrl: './register.component.html' }) /** * Registration form allowing new users to create an account on a selected server. */ export class RegisterComponent { serversSvc = inject(ServerDirectoryService); servers = this.serversSvc.servers; username = ''; displayName = ''; password = ''; serverId: string | undefined = this.serversSvc.activeServer()?.id; error = signal(null); private auth = inject(AuthService); private store = inject(Store); private route = inject(ActivatedRoute); private router = inject(Router); /** TrackBy function for server list rendering. */ trackById(_index: number, item: { id: string }) { return item.id; } /** Validate and submit the registration form, then navigate to search on success. */ submit() { this.error.set(null); const sid = this.serverId || this.serversSvc.activeServer()?.id; this.auth.register({ username: this.username.trim(), password: this.password, displayName: this.displayName.trim(), serverId: sid }).subscribe({ next: (resp) => { if (sid) this.serversSvc.setActiveServer(sid); const user: User = { id: resp.id, oderId: resp.id, username: resp.username, displayName: resp.displayName, status: 'online', role: 'member', joinedAt: Date.now() }; try { localStorage.setItem(STORAGE_KEY_CURRENT_USER_ID, resp.id); } catch {} this.store.dispatch(UsersActions.setCurrentUser({ user })); const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl')?.trim(); if (returnUrl?.startsWith('/')) { this.router.navigateByUrl(returnUrl); return; } this.router.navigate(['/search']); }, error: (err) => { this.error.set(err?.error?.error || 'Registration failed'); } }); } /** Navigate to the login page. */ goLogin() { const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl')?.trim(); this.router.navigate(['/login'], { queryParams: returnUrl ? { returnUrl } : undefined }); } }