@if (page) {
  <div class="page">
    <app-breadcrumb [items]="breadcrumbItems"></app-breadcrumb>
    <header class="page-header">
      <div>
        <h1>{{ page.title }}</h1>
        <p class="subtitle">{{ template?.name || ('pageEdit.pageFallback' | translate) }}</p>
      </div>
      <div class="header-actions">
        <button type="button" class="btn-ai"
          (click)="toggleChat()"
          [disabled]="aiLoading"
          [class.active]="chatOpen"
          [title]="'pageEdit.aiTitle' | translate">
          <lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
          {{ (aiLoading ? 'pageEdit.generating' : 'pageEdit.aiAssistant') | translate }}
        </button>
        <button type="button" class="btn-secondary" [routerLink]="['/lore', loreId, 'pages', pageId]">{{ 'common.cancel' | translate }}</button>
        <button type="button" class="btn-danger" (click)="delete()">{{ 'common.delete' | translate }}</button>
        <button type="button" class="btn-primary" (click)="save()" [disabled]="!title.trim()">
          {{ 'common.save' | translate }}
        </button>
      </div>
    </header>
    @if (aiError) {
      <div class="ai-error-banner" role="alert">
        <span>{{ aiError }}</span>
        <button type="button" class="ai-error-dismiss" (click)="aiError = null" [attr.aria-label]="'common.close' | translate">×</button>
      </div>
    }
    <form class="edit-form">
      <!-- Identité ----------------------------------------------------- -->
      <div class="field">
        <label>{{ 'common.name' | translate }}</label>
        <input type="text" [(ngModel)]="title" name="title" required />
      </div>
      <div class="field">
        <label>{{ 'pageEdit.folder' | translate }}</label>
        <select [(ngModel)]="nodeId" name="nodeId">
          @for (node of nodes; track node) {
            <option [value]="node.id">{{ node.name }}</option>
          }
        </select>
        <p class="hint">{{ 'pageEdit.folderHint' | translate }}</p>
      </div>
      <!-- Champs dynamiques du template -------------------------------- -->
      @if (template?.fields?.length) {
        <h2 class="section-title">{{ 'pageEdit.fields' | translate }}</h2>
        @for (field of template!.fields; track field) {
          <!-- Champ TEXT : textarea editable -->
          @if (field.type === 'TEXT') {
            <div class="field">
              <label>{{ field.name }}</label>
              <textarea
                [(ngModel)]="values[field.name]"
                [name]="'value_' + field.name"
                rows="4"
                [placeholder]="'pageEdit.valuePlaceholder' | translate:{ field: field.name }">
              </textarea>
            </div>
          }
          <!-- Champ IMAGE : galerie editable. -->
          @if (field.type === 'IMAGE') {
            <div class="field">
              <label>{{ field.name }}</label>
              <app-image-gallery
                [imageIds]="imageValues[field.name] || []"
                [editable]="true"
                [layout]="field.layout ?? 'GALLERY'"
                (imageIdsChange)="imageValues[field.name] = $event">
              </app-image-gallery>
            </div>
          }
          <!-- Champ KEY_VALUE_LIST : liste libellé/valeur (labels figés par le template). -->
          @if (field.type === 'KEY_VALUE_LIST') {
            <div class="field">
              <label>{{ field.name }}</label>
              <div class="kv-grid">
                @for (lbl of field.labels ?? []; track $index) {
                  <div class="kv-cell">
                    <span class="kv-label">{{ lbl }}</span>
                    <input
                      type="text"
                      [(ngModel)]="keyValueValues[field.name][lbl]"
                      [name]="'kv_' + field.name + '_' + lbl"
                      placeholder="—" />
                  </div>
                }
                @if (!(field.labels ?? []).length) {
                  <p class="kv-empty">{{ 'pageEdit.noLabels' | translate }}</p>
                }
              </div>
            </div>
          }
          <!-- Champ TABLE : colonnes figées par le template, lignes libres. -->
          @if (field.type === 'TABLE') {
            <div class="field">
              <label>{{ field.name }}</label>
              @if ((field.labels ?? []).length) {
                <div class="table-edit-wrap">
                  <table class="table-edit">
                    <thead>
                      <tr>
                        @for (col of field.labels; track $index) {
                          <th>{{ col }}</th>
                        }
                        <th class="table-edit-actions-col"></th>
                      </tr>
                    </thead>
                    <tbody>
                      @for (row of tableValues[field.name] ?? []; track $index; let ri = $index) {
                        <tr>
                          @for (col of field.labels; track $index) {
                            <td>
                              <input
                                type="text"
                                [(ngModel)]="row[col]"
                                [name]="'tbl_' + field.name + '_' + ri + '_' + col"
                                [placeholder]="col" />
                            </td>
                          }
                          <td class="table-edit-actions-col">
                            <button type="button" class="btn-row-delete"
                              (click)="removeTableRow(field.name, ri)"
                              [attr.aria-label]="'pageEdit.deleteRowN' | translate:{ n: (ri + 1) }" [title]="'pageEdit.deleteRow' | translate">
                              <lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
                            </button>
                          </td>
                        </tr>
                      }
                    </tbody>
                  </table>
                  <button type="button" class="btn-row-add" (click)="addTableRow(field.name, field.labels)">
                    <lucide-icon [img]="Plus" [size]="13"></lucide-icon>
                    {{ 'pageEdit.addRow' | translate }}
                  </button>
                </div>
              } @else {
                <p class="kv-empty">{{ 'pageEdit.noColumns' | translate }}</p>
              }
            </div>
          }
        }
      }
      <!-- Tags --------------------------------------------------------- -->
      <h2 class="section-title">{{ 'pageEdit.tags' | translate }}</h2>
      <div class="field">
        <app-chips-input
          [value]="tags"
          (valueChange)="tags = $event"
          [placeholder]="'pageEdit.tagsPlaceholder' | translate">
        </app-chips-input>
        <p class="hint">{{ 'pageEdit.tagsHint' | translate }}</p>
      </div>
      <!-- Liens vers d'autres pages ----------------------------------- -->
      <h2 class="section-title">{{ 'pageEdit.relatedPages' | translate }}</h2>
      <div class="field">
        <app-lore-link-picker
          [value]="relatedPageIds"
          [availablePages]="allPages"
          [excludePageId]="pageId"
          [loreId]="loreId"
          (valueChange)="relatedPageIds = $event">
        </app-lore-link-picker>
        <p class="hint">{{ 'pageEdit.relatedPagesHint' | translate }}</p>
      </div>
      <!-- Notes privées ----------------------------------------------- -->
      <h2 class="section-title">{{ 'pageEdit.privateNotes' | translate }}</h2>
      <div class="field">
        <textarea
          [(ngModel)]="notes"
          name="notes"
          rows="4"
          [placeholder]="'pageEdit.privateNotesPlaceholder' | translate">
        </textarea>
        <p class="hint">{{ 'pageEdit.privateNotesHint' | translate }}</p>
      </div>
    </form>
  </div>
}

<!-- Drawer chat IA (hors du .page pour pouvoir couvrir le viewport côté droit) -->
<app-ai-chat-drawer
  [loreId]="loreId"
  [pageId]="pageId"
  [isOpen]="chatOpen"
  [quickSuggestions]="chatQuickSuggestions"
  [primaryAction]="chatPrimaryAction"
  (close)="chatOpen = false"
  (primaryActionClick)="onChatFillRequested()">
</app-ai-chat-drawer>
