<!--
  Questo file fa parte di MyTown.
  MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
  i termini della GNU Affero General Public License come pubblicata dalla
  Free Software Foundation, versione 3.
  Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
  Copyright (C) Kondor Consulting & Services S.r.l.
  SPDX-License-Identifier: AGPL-3.0-or-later
-->
<ion-content>
  <ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>

  <!-- Identity strip: who am I talking to? -->
  <div class="chat-identity-strip" [class.clickable]="chatIsGroup" (click)="openGroupManager()">
    <div class="cis-avatar" [class.is-company]="chatIsCompany">
      @if (chatIsGroup) {
        <ion-icon name="people"></ion-icon>
      }
      @if (chatIsCompany && !chatIsGroup) {
        <ion-icon name="business"></ion-icon>
      }
      @if (!chatIsCompany && !chatIsGroup) {
        <span>{{ getChatWithInitials() }}</span>
      }
    </div>
    <div class="cis-info">
      <span class="cis-name">{{ chatWithName }}</span>
      @if (chatIsGroup) {
        <span class="cis-sub">Tocca per gestire il gruppo</span>
      }
      @if (chatIsCompany && !chatIsGroup) {
        <span class="cis-sub">Qualsiasi operatore può rispondere</span>
      }
    </div>
    @if (chatIsGroup) {
      <ion-icon name="chevron-forward" class="cis-arrow"></ion-icon>
    }
  </div>

  <!-- Loading -->
  @if (loading) {
    <div class="loading-wrap">
      <ion-spinner name="crescent" color="primary"></ion-spinner>
    </div>
  }

  <!-- Empty -->
  @if (!loading && messages.length === 0) {
    <div class="empty-chat">
      <ion-icon name="chatbubbles-outline"></ion-icon>
      <p>Inizia la conversazione</p>
    </div>
  }

  <!-- Messages -->
  @if (messages.length > 0) {
    <div class="chat-container">
      @for (msg of messages; track msg; let i = $index) {
        <div>
          <!-- Date separator -->
          @if (shouldShowDate(i)) {
            <div class="date-sep">
              <span>{{ getDateLabel(msg) }}</span>
            </div>
          }
          <!-- Own message (right) -->
          @if (isOwnMessage(msg)) {
            <div class="msg-row own">
              <div class="msg-bubble own-bubble" [class.deleted-bubble]="isDeleted(msg)" (click)="onOwnMessageTap(msg)">
                @if (isDeleted(msg)) {
                  <div class="msg-deleted-text">
                    <ion-icon name="ban-outline"></ion-icon> Questo messaggio è stato eliminato
                  </div>
                } @else {
                  @if (msg.attachments?.length) {
                    <div class="msg-attachments">
                      @for (att of msg.attachments; track att) {
                        @if (isImage(att) && att._objectUrl) {
                          <img [src]="att._objectUrl" class="msg-att-img" (click)="openAttachment(att)" />
                        }
                        @if (!isImage(att)) {
                          <div class="msg-att-file" (click)="openAttachment(att)">
                            <ion-icon name="document-outline"></ion-icon>
                            <span>{{ att.att_filename }}</span>
                          </div>
                        }
                      }
                    </div>
                  }
                  @if (msg.msg_text) {
                    <div class="msg-text">{{ msg.msg_text }}</div>
                  }
                }
                <div class="msg-meta">
                  <span class="msg-time">{{ formatTime(msg.msg_created_at) }}</span>
                  @if (isEdited(msg) && !isDeleted(msg)) {
                    <span class="msg-edited">modificato</span>
                  }
                  @if (!isDeleted(msg)) {
                    <ion-icon name="checkmark-done" class="msg-read" [class.read]="msg.msg_read_at"></ion-icon>
                  }
                </div>
              </div>
            </div>
          }
          <!-- Other message (left) -->
          @if (!isOwnMessage(msg)) {
            <div class="msg-row other">
              <div class="msg-avatar" [class.is-company]="msg.sender_company_name" [class.hidden-avatar]="isDeleted(msg)">
                @if (msg.sender_company_name) {
                  <ion-icon name="business"></ion-icon>
                }
                @if (!msg.sender_company_name) {
                  <span>{{ getSenderInitials(msg) }}</span>
                }
              </div>
              <div class="msg-bubble other-bubble" [class.deleted-bubble]="isDeleted(msg)">
                @if (!isDeleted(msg)) {
                  <div class="msg-sender">{{ getSenderLabel(msg) }}</div>
                }
                @if (isDeleted(msg)) {
                  <div class="msg-deleted-text">
                    <ion-icon name="ban-outline"></ion-icon> Questo messaggio è stato eliminato
                  </div>
                } @else {
                  @if (msg.attachments?.length) {
                    <div class="msg-attachments">
                      @for (att of msg.attachments; track att) {
                        @if (isImage(att) && att._objectUrl) {
                          <img [src]="att._objectUrl" class="msg-att-img" (click)="openAttachment(att)" />
                        }
                        @if (!isImage(att)) {
                          <div class="msg-att-file" (click)="openAttachment(att)">
                            <ion-icon name="document-outline"></ion-icon>
                            <span>{{ att.att_filename }}</span>
                          </div>
                        }
                      }
                    </div>
                  }
                  @if (msg.msg_text) {
                    <div class="msg-text">{{ msg.msg_text }}</div>
                  }
                }
                <div class="msg-meta">
                  <span class="msg-time">{{ formatTime(msg.msg_created_at) }}</span>
                  @if (isEdited(msg)) {
                    <span class="msg-edited">modificato</span>
                  }
                </div>
              </div>
            </div>
          }
        </div>
      }
    </div>
  }

</ion-content>

<ion-footer>
  <div class="input-bar">
    <input #fileInput type="file" multiple (change)="onFilesPicked($event)" style="display: none" />
    <button class="attach-btn" (click)="triggerFilePicker()" [disabled]="sending">
      <ion-icon name="attach-outline"></ion-icon>
    </button>
    <ion-textarea
      [(ngModel)]="newMessage"
      placeholder="Scrivi un messaggio..."
      [autoGrow]="true"
      rows="1"
      (keydown)="onKeyDown($event)"
      class="input-area">
    </ion-textarea>
    <button class="send-btn" (click)="sendMessage()" [disabled]="sending || !newMessage.trim()">
      <ion-icon name="send"></ion-icon>
    </button>
  </div>
</ion-footer>

<!-- ===== GESTIONE GRUPPO ===== -->
<ion-modal [isOpen]="showGroupModal" (didDismiss)="closeGroupManager()" [initialBreakpoint]="0.92" [breakpoints]="[0, 0.92]">
  <ng-template>
    <ion-header>
      <ion-toolbar>
        <ion-title>{{ chatWithName }}</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="closeGroupManager()">Chiudi</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <div class="group-actions">
        @if (isGroupAdmin) {
          <ion-button size="small" fill="outline" (click)="promptRenameGroup()">
            <ion-icon slot="start" name="create-outline"></ion-icon> Rinomina
          </ion-button>
        }
        <ion-button size="small" fill="outline" color="danger" (click)="confirmLeaveGroup()">
          <ion-icon slot="start" name="exit-outline"></ion-icon> Abbandona
        </ion-button>
      </div>

      <h3>Membri ({{ groupMembers.length }})</h3>
      <ion-list>
        @for (m of groupMembers; track m) {
          <ion-item>
            <div class="conv-avatar" slot="start"><span class="avatar-initials">{{ (m.usr_firstname || '?').charAt(0) }}{{ (m.usr_lastname || '').charAt(0) }}</span></div>
            <ion-label>
              <h2>{{ memberName(m) }}</h2>
              @if (m.cvm_role === 'ADMIN') {
                <p>Amministratore</p>
              }
            </ion-label>
            @if (isGroupAdmin && m.cvm_usr_id !== currentUserId) {
              <ion-button slot="end" fill="clear" color="danger" (click)="removeMember(m)">
                <ion-icon slot="icon-only" name="person-remove-outline"></ion-icon>
              </ion-button>
            }
          </ion-item>
        }
      </ion-list>

      @if (isGroupAdmin) {
        <div>
          <h3>Aggiungi membri</h3>
          <ion-searchbar placeholder="Cerca una persona..." [(ngModel)]="memberSearchText" (ionInput)="onMemberSearchInput()" [debounce]="0"></ion-searchbar>
          @if (searchingMembers) {
            <div class="loading-wrap"><ion-spinner name="crescent" color="primary"></ion-spinner></div>
          }
          @if (memberResults.length > 0) {
            <ion-list>
              @for (u of memberResults; track u) {
                <ion-item button (click)="addMember(u)">
                  <ion-label>
                    <h2>{{ u.usr_firstname }} {{ u.usr_lastname }}</h2>
                    <p>{{ u.usr_username }}</p>
                  </ion-label>
                  <ion-icon slot="end" name="person-add-outline" color="primary"></ion-icon>
                </ion-item>
              }
            </ion-list>
          }
        </div>
      }
    </ion-content>
  </ng-template>
</ion-modal>
