<!--
  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
-->
<!-- ===== CONTACTS PERMISSION MODAL ===== -->
<ion-modal
  [isOpen]="showContactsModal"
  (didDismiss)="declineContacts()"
  [initialBreakpoint]="0.88"
  [breakpoints]="[0, 0.88]"
  handleBehavior="none"
  cssClass="contacts-modal">
  <ng-template>
    <ion-content class="ctc-content">
      <div class="ctc-shell">
        <!-- Icon with pulsing rings -->
        <div class="ctc-icon-wrap">
          <div class="ctc-ring ctc-ring-3"></div>
          <div class="ctc-ring ctc-ring-2"></div>
          <div class="ctc-ring ctc-ring-1"></div>
          <div class="ctc-glow"></div>
          <div class="ctc-icon">
            <ion-icon name="people"></ion-icon>
          </div>
        </div>

        <!-- Text block -->
        <div class="ctc-text">
          <h2 class="ctc-headline">Riconosci i tuoi <em>contatti</em></h2>
          <p class="ctc-sub">Mostriamo i nomi della tua rubrica nelle chat quando il numero combacia, come fa WhatsApp.</p>
        </div>

        <!-- Feature rows -->
        <div class="ctc-features">
          <div class="ctc-feature">
            <div class="ctc-feat-icon">
              <ion-icon name="person-outline"></ion-icon>
            </div>
            <div class="ctc-feat-text">
              <span class="ctc-feat-title">Nome dalla tua rubrica</span>
              <span class="ctc-feat-desc">Al posto del nome del portale</span>
            </div>
          </div>
          <div class="ctc-feature">
            <div class="ctc-feat-icon">
              <ion-icon name="phone-portrait-outline"></ion-icon>
            </div>
            <div class="ctc-feat-text">
              <span class="ctc-feat-title">Solo sul dispositivo</span>
              <span class="ctc-feat-desc">Nessun contatto inviato al server</span>
            </div>
          </div>
          <div class="ctc-feature">
            <div class="ctc-feat-icon">
              <ion-icon name="shield-checkmark-outline"></ion-icon>
            </div>
            <div class="ctc-feat-text">
              <span class="ctc-feat-title">Privacy garantita</span>
              <span class="ctc-feat-desc">I dati restano sempre sul telefono</span>
            </div>
          </div>
        </div>

        <!-- Actions -->
        <div class="ctc-actions">
          <button class="ctc-btn-primary" (click)="acceptContacts()" [disabled]="contactsLoading">
            @if (contactsLoading) {
              <ion-spinner name="crescent" class="ctc-btn-spinner"></ion-spinner>
            }
            @if (!contactsLoading) {
              <ion-icon name="people-outline"></ion-icon>
            }
            {{ contactsLoading ? 'Caricamento...' : 'Abilita rubrica' }}
          </button>
          <button class="ctc-btn-skip" (click)="declineContacts()" [disabled]="contactsLoading">Non ora</button>
        </div>
      </div>
    </ion-content>
  </ng-template>
</ion-modal>

<!-- ===== SEARCH ZONE ===== -->
@if (!loading && conversations.length > 0) {
  <div class="search-zone">
    <div class="search-row">
      <ion-searchbar
        placeholder="Cerca chat o messaggi..."
        [(ngModel)]="searchText"
        (ionInput)="onConvSearchInput()"
        (ionClear)="onConvSearchClear()"
        showClearButton="focus"
        animated="true"
        class="search-input">
      </ion-searchbar>
    </div>
    @if (searchText) {
      <div class="result-bar">
        <span class="result-count">{{ filteredConversations.length }} risultati</span>
        <button class="clear-btn" (click)="onConvSearchClear()">
          <ion-icon name="close-outline"></ion-icon>
          Ripulisci
        </button>
      </div>
    }
  </div>
}

<ion-content>
  <ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>

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

  <!-- Empty state -->
  @if (!loading && conversations.length === 0) {
    <div class="empty-wrap">
      <div class="empty-icon">
        <ion-icon name="chatbubbles-outline"></ion-icon>
      </div>
      <p class="empty-title">Nessuna conversazione</p>
      <p class="empty-sub">Le tue chat con le aziende appariranno qui</p>
    </div>
  }

  <!-- No search results -->
  @if (!loading && conversations.length > 0 && filteredConversations.length === 0) {
    <div class="empty-wrap">
      <div class="empty-icon">
        <ion-icon name="search-outline"></ion-icon>
      </div>
      <p class="empty-title">Nessun risultato</p>
      <p class="empty-sub">Nessuna chat corrisponde a "{{ searchText }}"</p>
    </div>
  }

  <!-- Conversation list -->
  @if (!loading && filteredConversations.length > 0) {
    <div class="conv-list">
      @for (conv of filteredConversations; track conv) {
        <div
          class="conv-item"
          [class.has-unread]="conv.unread_count > 0"
          (click)="openChat(conv)"
          (touchstart)="onConvTouchStart(conv, $event)"
          (touchend)="onConvTouchEnd()"
          (touchmove)="onConvTouchEnd()">
          <!-- Avatar -->
          <div class="conv-avatar" [class.is-company]="conv.other_company_name">
            <span class="avatar-initials">{{ getInitials(conv) }}</span>
            @if (conv.other_company_name) {
              <div class="avatar-company-dot">
                <ion-icon name="business"></ion-icon>
              </div>
            }
          </div>
          <!-- Content -->
          <div class="conv-body">
            <div class="conv-top">
              <span class="conv-name">{{ getOtherName(conv) }}</span>
              <span class="conv-time">{{ getTimeAgo(conv.conv_last_message_at) }}</span>
            </div>
            <div class="conv-bottom">
              <p class="conv-preview" [class.is-unread]="conv.unread_count > 0">{{ getConvPreview(conv) }}</p>
              @if (conv.unread_count > 0) {
                <span class="unread-pill">{{ conv.unread_count }}</span>
              }
            </div>
          </div>
          <!-- Arrow -->
          <ion-icon name="chevron-forward" class="conv-arrow"></ion-icon>
        </div>
      }
    </div>
  }

  <!-- FAB nuova conversazione -->
  <ion-fab slot="fixed" vertical="bottom" horizontal="end">
    <ion-fab-button (click)="openNewChat()">
      <ion-icon name="create-outline"></ion-icon>
    </ion-fab-button>
  </ion-fab>
</ion-content>

<!-- ===== NUOVA CONVERSAZIONE / NUOVO GRUPPO ===== -->
<ion-modal #newChatModal [isOpen]="showNewChatModal" (didDismiss)="closeNewChat()" [initialBreakpoint]="0.92" [breakpoints]="[0, 0.92]">
  <ng-template>
    <ion-header>
      <ion-toolbar>
        <ion-title>{{ groupMode ? 'Nuovo gruppo' : 'Nuova conversazione' }}</ion-title>
        <ion-buttons slot="start">
          <ion-button (click)="toggleGroupMode()">
            <ion-icon slot="icon-only" [name]="groupMode ? 'person-outline' : 'people-outline'"></ion-icon>
          </ion-button>
        </ion-buttons>
        <ion-buttons slot="end">
          <ion-button (click)="closeNewChat()">Chiudi</ion-button>
        </ion-buttons>
      </ion-toolbar>
      @if (groupMode) {
        <ion-toolbar>
          <ion-input
            placeholder="Nome del gruppo"
            [(ngModel)]="groupName"
            class="ion-padding-start">
          </ion-input>
          <ion-buttons slot="end">
            <ion-button strong="true" [disabled]="!groupName.trim() || selectedMembers.length === 0" (click)="createGroup()">
              Crea ({{ selectedMembers.length }})
            </ion-button>
          </ion-buttons>
        </ion-toolbar>
      }
      <ion-toolbar>
        <ion-searchbar
          placeholder="Cerca una persona..."
          [(ngModel)]="userSearchText"
          (ionInput)="onUserSearchInput()"
          [debounce]="0">
        </ion-searchbar>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      @if (searchingUsers) {
        <div class="loading-wrap">
          <ion-spinner name="crescent" color="primary"></ion-spinner>
        </div>
      }
      @if (!searchingUsers && userResults.length === 0) {
        <div class="empty-wrap">
          <p class="empty-sub">Cerca un membro della tua azienda{{ groupMode ? ' da aggiungere al gruppo' : ' per iniziare a chattare' }}</p>
        </div>
      }
      @if (userResults.length > 0) {
        <ion-list>
          @for (u of userResults; track u) {
            <ion-item button (click)="groupMode ? toggleMemberSelection(u) : startChatWith(u)">
              <div class="conv-avatar" slot="start">
                <span class="avatar-initials">{{ getUserInitials(u) }}</span>
              </div>
              <ion-label>
                <h2>{{ u.usr_firstname }} {{ u.usr_lastname }}</h2>
                <p>{{ u.usr_username }}</p>
              </ion-label>
              @if (groupMode) {
                <ion-icon slot="end" [name]="isMemberSelected(u) ? 'checkmark-circle' : 'ellipse-outline'" [color]="isMemberSelected(u) ? 'primary' : 'medium'"></ion-icon>
              }
            </ion-item>
          }
        </ion-list>
      }
    </ion-content>
  </ng-template>
</ion-modal>
