import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { DataSyncService } from '../../../services/data-sync.service'; import { CampaignSidebarService } from '../../../services/campaign-sidebar.service'; import { ActivatedRoute } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { CdkDropList, CdkDrag, CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, Dices, Drama, Check, Play, Upload, Sparkles, Download, FileText, ChevronDown, ChevronRight, X, Network } from 'lucide-angular'; import { TranslatePipe, TranslateService } from '@ngx-translate/core'; import { Router, RouterLink } from '@angular/router'; import { forkJoin, of, Observable } from 'rxjs'; import { catchError, switchMap, filter, map } from 'rxjs/operators'; import { CampaignService, FoundryExportOptions } from '../../../services/campaign.service'; import { LoreService } from '../../../services/lore.service'; import { GameSystemService } from '../../../services/game-system.service'; import { GameSystem } from '../../../services/game-system.model'; import { NpcService } from '../../../services/npc.service'; import { RandomTableService } from '../../../services/random-table.service'; import { EnemyService } from '../../../services/enemy.service'; import { SessionService } from '../../../services/session.service'; import { PlaythroughService } from '../../../services/playthrough.service'; import { Playthrough } from '../../../services/campaign.model'; import { Session } from '../../../services/session.model'; import { Npc } from '../../../services/npc.model'; import { LayoutService } from '../../../services/layout.service'; import { PageTitleService } from '../../../services/page-title.service'; import { Campaign, Arc } from '../../../services/campaign.model'; import { Lore } from '../../../services/lore.model'; import { loadCampaignTreeData, buildCampaignSidebarConfig, CampaignTreeData } from '../../campaign-tree.helper'; import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service'; import { FolderGroup, groupByFolder, byOrder } from '../../../shared/folder-grouping.util'; import { CampaignReadinessAssessment } from '../../../services/readiness.model'; import { ReadinessPanelComponent } from '../../../shared/readiness-panel/readiness-panel.component'; import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component'; import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.component'; import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component'; @Component({ selector: 'app-campaign-detail', imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, CampaignPlayBlockComponent, FoundryExportDialogComponent], templateUrl: './campaign-detail.component.html', styleUrls: ['./campaign-detail.component.scss'] }) export class CampaignDetailComponent implements OnInit, OnDestroy { readonly Swords = Swords; readonly Plus = Plus; readonly Globe = Globe; readonly Pencil = Pencil; readonly Trash2 = Trash2; readonly Dices = Dices; readonly Drama = Drama; readonly Check = Check; readonly Play = Play; readonly Upload = Upload; readonly Sparkles = Sparkles; readonly Download = Download; readonly FileText = FileText; readonly ChevronDown = ChevronDown; readonly ChevronRight = ChevronRight; readonly X = X; readonly Network = Network; /** Export Foundry en cours (anti double-clic). */ exportingFoundry = false; /** Modale de périmètre de l'export Foundry. */ foundryDialogOpen = false; /** Export PDF en cours (anti double-clic). */ exportingPdf = false; campaign: Campaign | null = null; arcs: Arc[] = []; /** Nombre de chapitres par arc — alimente le compteur des cartes. */ chapterCountByArc: Record = {}; /** Lore associé si `campaign.loreId` est renseigné ; sinon null. */ linkedLore: Lore | null = null; /** Lores disponibles pour changer l'association en mode édition. */ availableLores: Lore[] = []; /** GameSystems disponibles pour changer l'association en mode édition. */ availableGameSystems: GameSystem[] = []; /** GameSystem associé si `campaign.gameSystemId` est renseigné ; sinon null. */ linkedGameSystem: GameSystem | null = null; /** Fiches de personnages non-joueurs (PNJ) de la campagne. */ npcs: Npc[] = []; /** PNJ groupés par dossier (dossiers alpha, ordre manuel dans chacun) — comme la sidebar. */ npcGroups: FolderGroup[] = []; /** En-tête : description repliée par défaut (clamp), dépliable via « Voir plus ». */ descExpanded = false; /** Dossiers de PNJ repliés (section Personnages) — par nom ('' = « Sans dossier »). */ collapsedNpcFolders = new Set(); /** Renommage inline d'une partie : id en cours d'édition + valeur saisie. */ editingPlaythroughId: string | null = null; editPlaythroughName = ''; /** Sessions de jeu (passées et en cours) liées à cette campagne. */ sessions: Session[] = []; /** Parties (Playthroughs) de cette campagne. */ playthroughs: Playthrough[] = []; /** Bilan de préparation (Pilier B — guidage) : alimente le panneau + les pastilles. */ readiness: CampaignReadinessAssessment | null = null; /** Mode édition inline. */ editing = false; editName = ''; editDescription = ''; editLoreId = ''; editGameSystemId = ''; /** Valeur sentinelle de l'option "Creer un systeme" dans le GameSystem. */ onEditGameSystemChange(value: string): void { if (value === this.CREATE_GAMESYSTEM_SENTINEL) { this.editGameSystemId = ''; this.startCreateGameSystem(); } } startCreateGameSystem(): void { this.creatingGameSystem = true; this.newGameSystemName = ''; } cancelCreateGameSystem(): void { this.creatingGameSystem = false; this.newGameSystemName = ''; } submitCreateGameSystem(): void { const name = this.newGameSystemName.trim(); if (!name || this.creatingGameSystemInFlight) return; this.creatingGameSystemInFlight = true; this.gameSystemService.create({ name, isPublic: false }).subscribe({ next: (created) => { this.creatingGameSystemInFlight = false; this.availableGameSystems = [...this.availableGameSystems, created]; if (created.id) { this.editGameSystemId = created.id; } this.creatingGameSystem = false; this.newGameSystemName = ''; }, error: () => { this.creatingGameSystemInFlight = false; console.error('Erreur lors de la creation du systeme de jeu'); } }); } saveEdit(): void { if (!this.campaign || !this.editName.trim()) return; const newGameSystemId = this.editGameSystemId ? this.editGameSystemId : null; const currentGameSystemId = this.campaign.gameSystemId ?? null; const gameSystemChanged = newGameSystemId !== currentGameSystemId; const hasSheets = this.npcs.length > 0; if (gameSystemChanged && hasSheets) { const count = this.npcs.length; this.confirmDialog.confirm({ title: this.translate.instant('campaignDetail.gameSystemChange.title'), message: this.translate.instant('campaignDetail.gameSystemChange.message'), details: [ this.translate.instant('campaignDetail.gameSystemChange.detailSheets', { n: count }), this.translate.instant('campaignDetail.gameSystemChange.detailFields'), this.translate.instant('campaignDetail.gameSystemChange.detailStored') ], confirmLabel: this.translate.instant('campaignDetail.gameSystemChange.confirm'), variant: 'warning' }).then(ok => { if (ok) this.persistEdit(newGameSystemId); }); return; } this.persistEdit(newGameSystemId); } private persistEdit(newGameSystemId: string | null): void { if (!this.campaign) return; this.campaignService.updateCampaign(this.campaign.id!, { name: this.editName.trim(), description: this.editDescription, playerCount: this.campaign.playerCount ?? 0, loreId: this.editLoreId ? this.editLoreId : null, gameSystemId: newGameSystemId }).subscribe({ next: (updated) => { this.campaign = updated; this.editing = false; // Recharge pour actualiser le badge "Univers" et le titre sidebar. this.reload(updated.id!); }, error: () => console.error('Erreur lors de la mise à jour de la campagne') }); } /** * Suppression en cascade : récupère d'abord le détail de ce qui sera effacé * (arcs / chapitres / scènes / personnages), affiche le récapitulatif dans * la confirmation, puis supprime. Le cascade est orchestré côté backend dans * une seule transaction. */ deleteCampaign(): void { if (!this.campaign) return; const campaign = this.campaign; this.campaignService.getCampaignDeletionImpact(campaign.id!).subscribe({ next: impact => { const parts: string[] = []; if (impact.arcs > 0) parts.push(this.translate.instant(impact.arcs > 1 ? 'campaignDetail.delete.arcsPlural' : 'campaignDetail.delete.arcs', { n: impact.arcs })); if (impact.chapters > 0) parts.push(this.translate.instant(impact.chapters > 1 ? 'campaignDetail.delete.chaptersPlural' : 'campaignDetail.delete.chapters', { n: impact.chapters })); if (impact.scenes > 0) parts.push(this.translate.instant(impact.scenes > 1 ? 'campaignDetail.delete.scenesPlural' : 'campaignDetail.delete.scenes', { n: impact.scenes })); if (impact.playthroughs > 0) parts.push(this.translate.instant(impact.playthroughs > 1 ? 'campaignDetail.delete.playthroughsPlural' : 'campaignDetail.delete.playthroughs', { n: impact.playthroughs })); const details: string[] = []; if (parts.length) details.push(this.translate.instant('campaignDetail.delete.alsoDeletes', { items: parts.join(', ') })); details.push(this.translate.instant('campaignDetail.delete.irreversible')); this.confirmDialog.confirm({ title: this.translate.instant('campaignDetail.delete.title'), message: this.translate.instant('campaignDetail.delete.message', { name: campaign.name }), confirmLabel: this.translate.instant('common.delete'), details, variant: 'danger' }).then(ok => { if (!ok) return; this.campaignService.deleteCampaign(campaign.id!).subscribe({ next: () => this.router.navigate(['/campaigns']), error: () => console.error('Erreur lors de la suppression de la campagne') }); }); }, error: () => console.error('Impossible de récupérer les dépendances de la campagne') }); } ngOnDestroy(): void { this.layoutService.hide(); } }