<!--
  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 class="profile-content" [fullscreen]="true">

  <!-- ═══ HERO SECTION ═══ -->
  <div class="hero-wrapper">
    <div class="hero-bg"></div>
    <div class="hero-body">
      <div class="avatar-ring">
        @if (user?.avatar) {
          <div class="avatar-inner avatar-inner--img">
            <img [src]="user.avatar" alt="avatar" />
          </div>
        } @else {
          <div class="avatar-inner" style="background: var(--app-brand); color: var(--app-on-brand);">
            {{ getUserInitials() }}
          </div>
        }
        <button type="button" class="avatar-edit-btn" [disabled]="avatarUploading" (click)="avatarInput.click()" aria-label="Cambia immagine profilo">
          <ion-icon [name]="avatarUploading ? 'hourglass-outline' : 'camera-outline'"></ion-icon>
        </button>
        @if (user?.avatar && !avatarUploading) {
          <button type="button" class="avatar-remove-btn" (click)="removeAvatar()" aria-label="Rimuovi immagine profilo">
            <ion-icon name="close-outline"></ion-icon>
          </button>
        }
        <input type="file" hidden accept="image/*" #avatarInput (change)="onAvatarSelected($event)" />
      </div>
      @if (user) {
        <div class="hero-info">
          <h1 class="hero-name">{{ user.usr_firstname }} {{ user.usr_lastname }}</h1>
          <span class="hero-username">&#64;{{ user.usr_displayname }}</span>
          <div class="hero-chips">
            <div class="hero-chip">
              <ion-icon name="shield-checkmark-outline"></ion-icon>
              <span>{{ getActiveRolesCount() }} {{ getActiveRolesCount() === 1 ? 'ruolo' : 'ruoli' }}</span>
            </div>
            <div class="hero-chip hero-chip--id">
              <ion-icon name="finger-print-outline"></ion-icon>
              <span>ID {{ user.usr_id }}</span>
            </div>
          </div>
        </div>
      }
    </div>
  </div>

  <!-- ═══ SEGMENT TABS ═══ -->
  <div class="tabs-bar">
    <button
      class="tab-btn"
      [class.tab-active]="selectedSegment === 'profile'"
      (click)="selectedSegment = 'profile'">
      <ion-icon name="person-outline"></ion-icon>
      <span>Profilo</span>
    </button>
    <button
      class="tab-btn"
      [class.tab-active]="selectedSegment === 'roles'"
      (click)="selectedSegment = 'roles'">
      <ion-icon name="shield-outline"></ion-icon>
      <span>Ruoli</span>
    </button>
    <button
      class="tab-btn"
      [class.tab-active]="selectedSegment === 'settings'"
      (click)="selectedSegment = 'settings'">
      <ion-icon name="settings-outline"></ion-icon>
      <span>Impostazioni</span>
    </button>
    <div class="tab-indicator" [ngClass]="'tab-indicator--' + selectedSegment"></div>
  </div>

  <!-- ═══ TAB CONTENT ═══ -->
  @if (user) {
    <div class="tab-panels">
      <!-- ── PROFILO ── -->
      @if (selectedSegment === 'profile') {
        <div class="tab-panel panel-enter">
          <div class="section-card">
            <div class="section-header">
              <ion-icon name="person-circle-outline" class="section-icon"></ion-icon>
              <h3>Informazioni personali</h3>
            </div>
            <div class="info-row">
              <div class="info-icon-wrap" style="background: #e0f0fb;">
                <ion-icon name="text-outline" style="color: var(--app-brand);"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Nome</span>
                <span class="info-value">{{ user.usr_firstname }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-icon-wrap" style="background: #e0f0fb;">
                <ion-icon name="text-outline" style="color: var(--app-brand);"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Cognome</span>
                <span class="info-value">{{ user.usr_lastname }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-icon-wrap" style="background: #e8f7ee;">
                <ion-icon name="mail-outline" style="color: #198754;"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Email</span>
                <span class="info-value">{{ user.usr_mail || '—' }}</span>
              </div>
            </div>
            <div class="info-row" style="border-bottom: none;">
              <div class="info-icon-wrap" style="background: #fff3e0;">
                <ion-icon name="call-outline" style="color: #e07b00;"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Telefono</span>
                <span class="info-value">{{ user.usr_phone || '—' }}</span>
              </div>
            </div>
          </div>
          <div class="section-card">
            <div class="section-header">
              <ion-icon name="at-outline" class="section-icon"></ion-icon>
              <h3>Account</h3>
            </div>
            <div class="info-row">
              <div class="info-icon-wrap" style="background: #f0eaff;">
                <ion-icon name="person-outline" style="color: #7c3aed;"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Username</span>
                <span class="info-value">{{ user.usr_username }}</span>
              </div>
            </div>
            <div class="info-row" style="border-bottom: none;">
              <div class="info-icon-wrap" style="background: #fce4ec;">
                <ion-icon name="id-card-outline" style="color: #c62828;"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Display name</span>
                <span class="info-value">{{ user.usr_displayname }}</span>
              </div>
            </div>
          </div>
        </div>
      }
      <!-- ── RUOLI ── -->
      @if (selectedSegment === 'roles') {
        <div class="tab-panel panel-enter">
          <!-- Empty state -->
          @if ((!portalRoles || portalRoles.length === 0) && (!companyRoles || companyRoles.length === 0)) {
            <div class="empty-state">
              <ion-icon name="shield-outline"></ion-icon>
              <p>Nessun ruolo assegnato</p>
            </div>
          }
          <!-- ── Ruoli Portale ── -->
          @if (portalRoles && portalRoles.length > 0) {
            <div class="section-card">
              <div class="section-header">
                <ion-icon name="globe-outline" class="section-icon"></ion-icon>
                <h3>Ruoli portale</h3>
                <span class="section-count">{{ portalRoles.length }}</span>
              </div>
              @for (role of portalRoles; track role; let last = $last) {
                <div class="info-row" [style.border-bottom]="last ? 'none' : null">
                  <div class="info-icon-wrap" style="background: #e0f0fb;">
                    <ion-icon name="shield-checkmark-outline" style="color: var(--app-brand);"></ion-icon>
                  </div>
                  <div class="info-content">
                    <span class="info-label">{{ role.rl_type || 'Ruolo #' + role.rl_id }}</span>
                    <span class="info-value">{{ role.rl_description || role.rl_name || '—' }}</span>
                  </div>
                </div>
              }
            </div>
          }
          <!-- ── Ruoli Aziendali ── -->
          @if (companyRoles && companyRoles.length > 0) {
            <div class="section-card">
              <div class="section-header">
                <ion-icon name="business-outline" class="section-icon"></ion-icon>
                <h3>Ruoli aziendali</h3>
                <span class="section-count">{{ companyRoles.length }}</span>
              </div>
              @for (role of companyRoles; track role; let last = $last) {
                <div class="info-row" [style.border-bottom]="last ? 'none' : null">
                  <div class="info-icon-wrap" style="background: #fff3e0;">
                    <ion-icon name="briefcase-outline" style="color: #e07b00;"></ion-icon>
                  </div>
                  <div class="info-content">
                    <span class="info-label">{{ role.rl_name || 'Ruolo #' + role.rl_id }}</span>
                    <span class="info-value">{{ role.rl_description || '—' }}</span>
                  </div>
                </div>
              }
            </div>
          }
        </div>
      }
      <!-- ── IMPOSTAZIONI ── -->
      @if (selectedSegment === 'settings') {
        <div class="tab-panel panel-enter">
          <!-- ======= NOTIFICHE PUSH ======= -->
          @if (isNativePlatform) {
            <div class="section-card">
              <div class="section-header">
                <ion-icon name="notifications-outline" class="section-icon"></ion-icon>
                <h3>Notifiche push</h3>
              </div>
              <!-- Skeleton caricamento -->
              @if (pushSystemLoading) {
                <div class="push-loading">
                  <ion-spinner name="crescent" style="color: var(--app-brand);"></ion-spinner>
                  <span>Verifica stato notifiche...</span>
                </div>
              }
              @if (!pushSystemLoading) {
                <!-- ── STATO: PERMESSO NEGATO DAL SISTEMA ── -->
                @if (pushSystemStatus === 'denied') {
                  <div class="push-status-banner push-status-banner--denied">
                    <div class="push-status-icon">
                      <ion-icon name="notifications-off-outline"></ion-icon>
                    </div>
                    <div class="push-status-body">
                      <div class="push-status-title">Notifiche disabilitate</div>
                      <div class="push-status-desc">
                        Le notifiche push sono bloccate nelle impostazioni di sistema del dispositivo.
                      </div>
                      <button class="push-open-settings-btn" (click)="onOpenSystemSettings()">
                        <ion-icon name="settings-outline"></ion-icon>
                        Apri impostazioni di sistema
                      </button>
                    </div>
                  </div>
                }
                <!-- ── STATO: PERMESSO DA RICHIEDERE ── -->
                @if (pushSystemStatus === 'prompt') {
                  <div class="push-status-banner push-status-banner--prompt">
                    <div class="push-status-icon">
                      <ion-icon name="notifications-outline"></ion-icon>
                    </div>
                    <div class="push-status-body">
                      <div class="push-status-title">Notifiche non ancora abilitate</div>
                      <div class="push-status-desc">
                        Abilita le notifiche push per ricevere aggiornamenti in tempo reale.
                      </div>
                      <button class="push-open-settings-btn push-open-settings-btn--primary" (click)="onRequestSystemPermission()">
                        <ion-icon name="checkmark-circle-outline"></ion-icon>
                        Abilita notifiche push
                      </button>
                    </div>
                  </div>
                }
                <!-- ── STATO: PERMESSO CONCESSO → toggle in-app ── -->
                @if (pushSystemStatus === 'granted') {
                  <div class="push-status-granted">
                    <ion-icon name="checkmark-circle" style="color: #198754; font-size: 16px;"></ion-icon>
                    <span>Permesso di sistema <strong>attivo</strong></span>
                  </div>
                  <div class="toggle-row">
                    <div class="toggle-info">
                      <div class="info-icon-wrap" style="background: #e0f7f0; flex-shrink: 0;">
                        <ion-icon name="notifications-outline" style="color: #0f9060;"></ion-icon>
                      </div>
                      <div>
                        <div class="toggle-label">Ricevi notifiche push</div>
                        <div class="toggle-sub">
                          {{ pushLocalEnabled ? 'Attive — ricevi avvisi in tempo reale' : 'Disabilitate — nessuna notifica push' }}
                        </div>
                      </div>
                    </div>
                    <ion-toggle
                      [(ngModel)]="pushLocalEnabled"
                      [disabled]="pushToggleLoading"
                      (ionChange)="onTogglePushLocal(pushLocalEnabled)">
                    </ion-toggle>
                  </div>
                  @if (!pushLocalEnabled) {
                    <div class="push-disabled-warning">
                      <ion-icon name="information-circle-outline"></ion-icon>
                      <span>Hai disabilitato le notifiche push dall'app. Puoi riabilitarle in qualsiasi momento.</span>
                    </div>
                  }
                }
                <!-- ── STATO: NON DISPONIBILE (web) ── -->
                @if (pushSystemStatus === 'unavailable') {
                  <div class="push-unavailable">
                    <ion-icon name="phone-portrait-outline"></ion-icon>
                    <span>Le notifiche push sono disponibili solo sull'app mobile.</span>
                  </div>
                }
              }
            </div>
          }
          <!-- ======= NOTIFICHE EMAIL + SMS ======= -->
          <div class="section-card">
            <div class="section-header">
              <ion-icon name="notifications-circle-outline" class="section-icon"></ion-icon>
              <h3>Preferenze notifiche</h3>
            </div>
            <!-- Email -->
            <div class="toggle-row">
              <div class="toggle-info">
                <div class="info-icon-wrap" style="background: #e0f0fb; flex-shrink: 0;">
                  <ion-icon name="mail-outline" style="color: var(--app-brand);"></ion-icon>
                </div>
                <div>
                  <div class="toggle-label">Notifiche e-mail</div>
                  <div class="toggle-sub">Ricevi aggiornamenti via email</div>
                </div>
              </div>
              <ion-toggle
                [(ngModel)]="emailNotificationsEnabled"
                (ionChange)="saveNotificationPreferences()">
              </ion-toggle>
            </div>
            <div class="pref-divider"></div>
            <!-- SMS -->
            <div class="toggle-row" [class.toggle-row--disabled]="!hasPhone()">
              <div class="toggle-info">
                <div class="info-icon-wrap"
                  [style.background]="hasPhone() ? '#e8f7ee' : '#f0f0f0'"
                  style="flex-shrink: 0;">
                  <ion-icon name="chatbubble-outline"
                    [style.color]="hasPhone() ? '#198754' : '#aaa'">
                  </ion-icon>
                </div>
                <div>
                  <div class="toggle-label">Notifiche SMS</div>
                  @if (hasPhone()) {
                    <div class="toggle-sub">
                      Ricevi avvisi via SMS al {{ user.usr_phone }}
                    </div>
                  }
                  @if (!hasPhone()) {
                    <div class="toggle-sub toggle-sub--warn">
                      <ion-icon name="warning-outline"></ion-icon>
                      Inserisci un numero di telefono nel tuo profilo per abilitare gli SMS
                    </div>
                  }
                </div>
              </div>
              <ion-toggle
                [(ngModel)]="smsNotificationsEnabled"
                [disabled]="!hasPhone() || preferencesLoading"
                (ionChange)="saveNotificationPreferences()">
              </ion-toggle>
            </div>
            <!-- Saving indicator -->
            @if (preferencesLoading) {
              <div class="pref-saving">
                <ion-spinner name="dots" style="width:16px; height:16px;"></ion-spinner>
                <span>Salvataggio...</span>
              </div>
            }
          </div>
          <!-- ======= POSIZIONE ======= -->
          <div class="section-card">
            <div class="section-header">
              <ion-icon name="location-outline" class="section-icon"></ion-icon>
              <h3>Posizione</h3>
            </div>
            <!-- Stato: granted -->
            @if (geoStatus === 'granted' && geoPosition) {
              <div class="push-status-granted">
                <ion-icon name="checkmark-circle" style="color: #198754; font-size: 16px;"></ion-icon>
                <span>Posizione <strong>attiva</strong></span>
              </div>
              <div class="info-row">
                <div class="info-icon-wrap" style="background: #e0f0fb;">
                  <ion-icon name="navigate-outline" style="color: var(--app-brand);"></ion-icon>
                </div>
                <div class="info-content">
                  <span class="info-label">Coordinate rilevate</span>
                  <span class="info-value mono">{{ geoPosition.latitude | number:'1.4-4' }}, {{ geoPosition.longitude | number:'1.4-4' }}</span>
                </div>
              </div>
              <div class="toggle-row" style="border-bottom: none; padding-top: 12px;">
                <div class="toggle-info">
                  <div class="info-icon-wrap" style="background: #fce4ec; flex-shrink: 0;">
                    <ion-icon name="location-outline" style="color: #c62828;"></ion-icon>
                  </div>
                  <div>
                    <div class="toggle-label">Disabilita posizione</div>
                    <div class="toggle-sub">Rimuove la posizione salvata dal dispositivo</div>
                  </div>
                </div>
                <button class="push-open-settings-btn" style="white-space: nowrap;" (click)="onDisableGeolocation()">
                  <ion-icon name="close-circle-outline"></ion-icon>
                  Disabilita
                </button>
              </div>
            }
            <!-- Stato: denied -->
            @if (geoStatus === 'denied') {
              <div class="push-status-banner push-status-banner--denied">
                <div class="push-status-icon">
                  <ion-icon name="location-outline"></ion-icon>
                </div>
                <div class="push-status-body">
                  <div class="push-status-title">Posizione negata</div>
                  <div class="push-status-desc">
                    Il permesso è stato rifiutato. Abilitalo nelle impostazioni del dispositivo.
                  </div>
                  <button class="push-open-settings-btn" (click)="onOpenGeoSettings()">
                    <ion-icon name="settings-outline"></ion-icon>
                    Apri impostazioni di sistema
                  </button>
                </div>
              </div>
            }
            <!-- Stato: idle / non concesso -->
            @if (geoStatus === 'idle' || geoStatus === 'loading') {
              <div class="push-status-banner push-status-banner--prompt">
                <div class="push-status-icon">
                  <ion-icon name="location-outline"></ion-icon>
                </div>
                <div class="push-status-body">
                  <div class="push-status-title">Posizione non attiva</div>
                  <div class="push-status-desc">
                    Attiva la posizione per vedere la distanza dai servizi vicino a te.
                  </div>
                  <button class="push-open-settings-btn push-open-settings-btn--primary"
                    [disabled]="geoLoading"
                    (click)="onEnableGeolocation()">
                    @if (geoLoading) {
                      <ion-spinner name="crescent" style="width:14px; height:14px;"></ion-spinner>
                    }
                    @if (!geoLoading) {
                      <ion-icon name="location-outline"></ion-icon>
                    }
                    {{ geoLoading ? 'Richiesta in corso...' : 'Abilita posizione' }}
                  </button>
                </div>
              </div>
            }
          </div>
          <!-- ======= RUBRICA ======= -->
          @if (isNativePlatform) {
            <div class="section-card">
              <div class="section-header">
                <ion-icon name="people-outline" class="section-icon"></ion-icon>
                <h3>Rubrica telefono</h3>
              </div>
              @if (contactsStatus$ | async; as ctcStatus) {
                <!-- Stato: granted (caricata) -->
                @if (ctcStatus === 'granted') {
                  <div class="push-status-granted">
                    <ion-icon name="checkmark-circle" style="color: #198754; font-size: 16px;"></ion-icon>
                    <span>Rubrica <strong>attiva</strong> — {{ contactsService.getCount() }} contatti caricati</span>
                  </div>
                  <div class="push-disabled-warning" style="margin-top: 8px;">
                    <ion-icon name="information-circle-outline"></ion-icon>
                    <span>I contatti restano sul dispositivo e non vengono mai inviati al server.</span>
                  </div>
                  <div class="toggle-row" style="border-bottom: none; padding-top: 12px;">
                    <div class="toggle-info">
                      <div class="info-icon-wrap" style="background: #fce4ec; flex-shrink: 0;">
                        <ion-icon name="people-outline" style="color: #c62828;"></ion-icon>
                      </div>
                      <div>
                        <div class="toggle-label">Disabilita rubrica</div>
                        <div class="toggle-sub">Rimuove i contatti caricati dal dispositivo</div>
                      </div>
                    </div>
                    <button class="push-open-settings-btn" style="white-space: nowrap;" (click)="onDisableContacts()">
                      <ion-icon name="close-circle-outline"></ion-icon>
                      Disabilita
                    </button>
                  </div>
                }
                <!-- Stato: denied -->
                @if (ctcStatus === 'denied') {
                  <div class="push-status-banner push-status-banner--denied">
                    <div class="push-status-icon">
                      <ion-icon name="people-outline"></ion-icon>
                    </div>
                    <div class="push-status-body">
                      <div class="push-status-title">Accesso negato</div>
                      <div class="push-status-desc">
                        Il permesso alla rubrica è stato rifiutato. Abilitalo nelle impostazioni del dispositivo.
                      </div>
                      <button class="push-open-settings-btn" (click)="onOpenContactsSettings()">
                        <ion-icon name="settings-outline"></ion-icon>
                        Apri impostazioni di sistema
                      </button>
                    </div>
                  </div>
                }
                <!-- Stato: idle / loading / non ancora chiesto -->
                @if (ctcStatus === 'idle' || ctcStatus === 'loading') {
                  <div class="push-status-banner push-status-banner--prompt">
                    <div class="push-status-icon">
                      <ion-icon name="people-outline"></ion-icon>
                    </div>
                    <div class="push-status-body">
                      <div class="push-status-title">Rubrica non ancora abilitata</div>
                      <div class="push-status-desc">
                        Attiva per mostrare i nomi della tua rubrica nelle chat, come fa WhatsApp.
                      </div>
                      <button class="push-open-settings-btn push-open-settings-btn--primary"
                        [disabled]="contactsLoading"
                        (click)="onEnableContacts()">
                        @if (contactsLoading) {
                          <ion-spinner name="crescent" style="width:14px; height:14px;"></ion-spinner>
                        }
                        @if (!contactsLoading) {
                          <ion-icon name="people-outline"></ion-icon>
                        }
                        {{ contactsLoading ? 'Caricamento...' : 'Abilita rubrica' }}
                      </button>
                    </div>
                  </div>
                }
              }
            </div>
          }
          <!-- ======= INFORMAZIONI ACCOUNT ======= -->
          <div class="section-card">
            <div class="section-header">
              <ion-icon name="finger-print-outline" class="section-icon"></ion-icon>
              <h3>Informazioni account</h3>
            </div>
            <div class="info-row">
              <div class="info-icon-wrap" style="background: #e0f0fb;">
                <ion-icon name="id-card-outline" style="color: var(--app-brand);"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">ID Utente</span>
                <span class="info-value mono">{{ user.usr_id }}</span>
              </div>
            </div>
            <div class="info-row" style="border-bottom: none;">
              <div class="info-icon-wrap" style="background: #f0eaff;">
                <ion-icon name="person-outline" style="color: #7c3aed;"></ion-icon>
              </div>
              <div class="info-content">
                <span class="info-label">Username</span>
                <span class="info-value mono">{{ user.usr_username }}</span>
              </div>
            </div>
          </div>
        </div>
      }
    </div>

    <!-- ======= LOGOUT (sempre visibile, a prescindere dalla sezione) ======= -->
    <div class="logout-card">
      <div class="logout-card-body">
        <div class="logout-icon-wrap">
          <ion-icon name="log-out-outline"></ion-icon>
        </div>
        <div class="logout-text">
          <div class="logout-title">Disconnetti</div>
          <div class="logout-desc">
            Sei connesso come <strong>&#64;{{ user.usr_displayname }}</strong>.
            Uscendo dovrai inserire di nuovo le credenziali al prossimo accesso.
          </div>
        </div>
      </div>
      <button class="logout-btn" [disabled]="logoutLoading" (click)="confirmLogout()">
        @if (logoutLoading) {
          <ion-spinner name="crescent" style="width:16px; height:16px;"></ion-spinner>
        }
        @if (!logoutLoading) {
          <ion-icon name="log-out-outline"></ion-icon>
        }
        {{ logoutLoading ? 'Uscita in corso...' : 'Esci dall\'account' }}
      </button>
    </div>
  }

  <!-- skeleton loading -->
  @if (!user) {
    <div class="skeleton-wrap">
      <div class="skeleton-avatar"></div>
      <div class="skeleton-line skeleton-line--lg"></div>
      <div class="skeleton-line"></div>
      <div class="skeleton-card"></div>
    </div>
  }

</ion-content>
