<!--
  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>

  <!-- ========== HERO IMAGE ========== -->
  @if (heroImage) {
    <div class="hero-section" [ngClass]="heroBackgroundClass">
      <div class="hero-image-bg" [style.background-image]="'url(' + heroImage + ')'"></div>
      <div class="hero-dark-overlay" [style.opacity]="1 - heroOpacity"></div>
      <ion-button fill="clear" class="hero-favorite-btn" (click)="toggleFavorite()">
        <ion-icon [name]="isFavorite ? 'heart' : 'heart-outline'" [class.is-favorite]="isFavorite"></ion-icon>
      </ion-button>
    </div>
  }

  <div class="home-container" [class.has-hero]="heroImage">

    <!-- ========== COMPANY HEADER ========== -->
    @if (company) {
      <div class="company-header">
        <h4 class="company-name">{{ company.name }}</h4>
        <!-- Badge valutazione media: tap -> tab recensioni -->
        @if (reviewStats && reviewStats.total_count > 0) {
          <div class="rating-badge" (click)="activeTab = 'reviews'">
            <ion-icon name="star"></ion-icon>
            <span class="rating-value">{{ reviewStats.avg_overall | number: '1.1-1' }}</span>
            <span class="rating-count">({{ reviewStats.total_count }} {{ reviewStats.total_count === 1 ? 'recensione' : 'recensioni' }})</span>
          </div>
        }
        @if (serviceDescription) {
          <p class="company-desc">{{ serviceDescription }}</p>
        }
        <div class="info-chips-row">
          @if (getCompanyAddress()) {
            <div class="info-chip" (click)="getDirections()">
              <ion-icon name="location-outline"></ion-icon>
              <span>{{ getCompanyAddress() }}</span>
            </div>
          }
          @if (getBusinessHoursSummary()) {
            <div class="info-chip">
              <ion-icon name="time-outline"></ion-icon>
              <span>{{ getBusinessHoursSummary() }}</span>
            </div>
          }
        </div>
      </div>
    }

    <!-- ========== ACTION BUTTONS ========== -->
    <div class="action-row">
      @if (company?.cmp_web) {
        <div class="action-pill" (click)="openWebsite()">
          <div class="action-pill-icon"><ion-icon name="globe-outline"></ion-icon></div>
          <span>Sito Web</span>
        </div>
      }
      @if (company?.cmp_phone_number) {
        <div class="action-pill" (click)="callCompany()">
          <div class="action-pill-icon"><ion-icon name="call-outline"></ion-icon></div>
          <span>Chiama</span>
        </div>
      }
      @if (getCompanyAddress()) {
        <div class="action-pill" (click)="getDirections()">
          <div class="action-pill-icon"><ion-icon name="navigate-outline"></ion-icon></div>
          <span>Direzioni</span>
        </div>
      }
      <div class="action-pill" (click)="goToList()">
        <div class="action-pill-icon"><ion-icon name="calendar-outline"></ion-icon></div>
        <span>Appuntamenti</span>
      </div>
      @if (isGestore) {
        <div class="action-pill" (click)="goToServiceTypes()">
          <div class="action-pill-icon"><ion-icon name="settings-outline"></ion-icon></div>
          <span>Gestione</span>
        </div>
      }
      @if (!isGestore && chatEnabled) {
        <div class="action-pill" (click)="openChat()">
          <div class="action-pill-icon"><ion-icon name="chatbubble-ellipses-outline"></ion-icon></div>
          <span>Chat</span>
        </div>
      }
    </div>

    <!-- ========== SEGMENT NAV ========== -->
    <div class="segment-wrap">
      <ion-segment [(ngModel)]="activeTab" mode="md" class="home-segment">
        <ion-segment-button value="services">
          <ion-label>Servizi</ion-label>
        </ion-segment-button>
        @if (galleryPhotos.length > 0) {
          <ion-segment-button value="gallery">
            <ion-label>Galleria</ion-label>
          </ion-segment-button>
        }
        <ion-segment-button value="info">
          <ion-label>Info</ion-label>
        </ion-segment-button>
        <ion-segment-button value="reviews">
          <ion-label>Recensioni</ion-label>
        </ion-segment-button>
      </ion-segment>
    </div>

    <!-- ========== TAB: SERVIZI ========== -->
    @if (activeTab === 'services') {
      <div class="tab-content">
        <div class="services-section">
          <!-- Header normale -->
          @if (!selectedService) {
            <div class="section-header">
              <h6 class="section-title">Servizi</h6>
              <span class="section-count-badge">{{ serviceTypes.length }}</span>
            </div>
          }
          <!-- Header selezione attiva -->
          @if (selectedService) {
            <div class="selection-header">
              <div class="sel-accent" [style.background-color]="selectedService.st_color || '#6366F1'"></div>
              <div class="sel-info">
                <span class="sel-label">Servizio scelto</span>
                <span class="sel-name">
                  @if (additionalServices.length === 0) {
                    {{ selectedService.st_name }}
                  }
                  @if (additionalServices.length > 0) {
                    {{ additionalServices.length + 1 }} servizi
                  }
                </span>
                <span class="sel-meta">{{ getTotalDuration() }} min totali</span>
              </div>
              <button class="sel-clear-btn" (click)="clearSelection()">
                <ion-icon name="close-circle"></ion-icon>
              </button>
            </div>
          }
          @if (loadingServices) {
            <div class="loading-wrap">
              <ion-spinner name="crescent" color="primary"></ion-spinner>
            </div>
          }
          @if (!loadingServices && serviceTypes.length === 0) {
            <div class="empty-state">
              <div class="empty-icon-wrap">
                <ion-icon name="pricetags-outline"></ion-icon>
              </div>
              <p>Nessun servizio disponibile</p>
            </div>
          }
          <!-- Accordion categorie -->
          @if (!loadingServices && groupedServiceTypes.length > 0) {
            <div class="category-list">
              @for (group of groupedServiceTypes; track group) {
                <div
                  class="category-group"
                  [class.has-selection]="hasGroupSelection(group)">
                  <!-- Header categoria -->
                  <div class="category-header" (click)="toggleCategory(group)" [class.is-expanded]="group.expanded">
                    <div class="category-color-strip" [style.background]="getCategoryColor(group)"></div>
                    <div class="category-header-body">
                      <span class="category-name-text">{{ group.category_name }}</span>
                      <span class="category-count-chip">{{ group.services.length }}</span>
                    </div>
                    <ion-icon name="chevron-down" class="category-chevron" [class.rotated]="group.expanded"></ion-icon>
                  </div>
                  <!-- Servizi (accordion) -->
                  <div class="category-services" [class.is-visible]="group.expanded">
                    @for (st of group.services; track st) {
                      <div
                        class="service-row"
                        [class.is-selected]="isSelected(st)"
                        [class.is-additional]="isAdditional(st)"
                        (click)="onServiceTap(st)">
                        <div class="sr-accent" [style.background-color]="st.st_color || '#6366F1'"></div>
                        <div class="sr-body">
                          <span class="sr-name">{{ st.st_name }}</span>
                          <span class="sr-dur">{{ st.st_duration_minutes }} min</span>
                        </div>
                        <div class="sr-end">
                          @if (isSelected(st)) {
                            <ion-icon name="checkmark-circle" class="sr-icon si-selected"></ion-icon>
                          }
                          @if (isAdditional(st)) {
                            <ion-icon name="add-circle" class="sr-icon si-additional"></ion-icon>
                          }
                          @if (!isSelected(st) && !isAdditional(st) && selectedService) {
                            <ion-icon name="add-outline" class="sr-icon si-addmore"></ion-icon>
                          }
                          @if (!isSelected(st) && !isAdditional(st) && !selectedService) {
                            <ion-icon name="chevron-forward" class="sr-icon si-arrow"></ion-icon>
                          }
                        </div>
                      </div>
                    }
                  </div>
                </div>
              }
            </div>
          }
          <!-- Spacer per booking bar -->
          @if (selectedService && !isGestore) {
            <div style="height: 84px;"></div>
          }
        </div>
      </div>
    }

    <!-- ========== TAB: INFO ========== -->
    @if (activeTab === 'info') {
      <div class="tab-content">
        <div class="about-section">
          <div class="about-block">
            <ion-button expand="block" [fill]="isFavorite ? 'solid' : 'outline'" color="primary" (click)="toggleFavorite()">
              <ion-icon [name]="isFavorite ? 'heart' : 'heart-outline'" slot="start"></ion-icon>
              {{ isFavorite ? 'Salvato nei preferiti' : 'Salva nei preferiti' }}
            </ion-button>
          </div>
          @if (company?.description) {
            <div class="about-block">
              <h6 class="about-title">Chi siamo</h6>
              <p class="about-text">{{ company.description }}</p>
            </div>
          }
          @if (businessHours.length > 0) {
            <div class="about-block">
              <h6 class="about-title">Orari di apertura</h6>
              <div class="hours-list">
                @for (day of businessHours; track day) {
                  <div class="hours-row"
                    [class.hours-closed]="!day.isOpen"
                    [class.hours-today]="isToday(day.dayName)">
                    <span class="hours-day">{{ day.dayName }}</span>
                    <span class="hours-time" [class.closed]="!day.isOpen">{{ day.hoursLabel }}</span>
                  </div>
                }
              </div>
            </div>
          }
          @if (getCompanyAddress()) {
            <div class="about-block">
              <h6 class="about-title">Indirizzo</h6>
              <div class="info-row" (click)="getDirections()" style="cursor: pointer;">
                <ion-icon name="location" color="primary"></ion-icon>
                <span>{{ getCompanyAddress() }}</span>
              </div>
            </div>
          }
          @if (company?.cmp_phone_number || company?.cmp_web) {
            <div class="about-block">
              <h6 class="about-title">Contatti</h6>
              @if (company?.cmp_phone_number) {
                <div class="info-row" (click)="callCompany()" style="cursor: pointer;">
                  <ion-icon name="call" color="primary"></ion-icon>
                  <span>{{ company.cmp_phone_number }}</span>
                </div>
              }
              @if (company?.cmp_web) {
                <div class="info-row" (click)="openWebsite()" style="cursor: pointer;">
                  <ion-icon name="globe" color="primary"></ion-icon>
                  <span>{{ company.cmp_web }}</span>
                </div>
              }
            </div>
          }
          <div class="about-block">
            <h6 class="about-title">Azioni rapide</h6>
            <ion-list lines="full" class="profile-list">
              <ion-item button (click)="goToList()" detail="true">
                <ion-icon name="calendar-outline" slot="start" color="primary"></ion-icon>
                <ion-label>I miei appuntamenti</ion-label>
              </ion-item>
              @if (isGestore) {
                <ion-item button (click)="goToAvailability()" detail="true">
                  <ion-icon name="time-outline" slot="start" color="primary"></ion-icon>
                  <ion-label>Gestisci disponibilità</ion-label>
                </ion-item>
              }
              @if (isGestore) {
                <ion-item button (click)="goToServiceTypes()" detail="true">
                  <ion-icon name="pricetags-outline" slot="start" color="primary"></ion-icon>
                  <ion-label>Gestisci servizi</ion-label>
                </ion-item>
              }
            </ion-list>
          </div>
        </div>
      </div>
    }

    <!-- ========== TAB: GALLERIA ========== -->
    @if (activeTab === 'gallery') {
      <div class="tab-content">
        <div class="gallery-grid">
          @for (photo of galleryPhotos; track photo) {
            <div class="gallery-item">
              <img [src]="'data:image/jpeg;base64,' + photo.cg_image_b64" [alt]="photo.cg_caption || ''" class="gallery-photo" />
              @if (photo.cg_caption) {
                <div class="gallery-caption">{{ photo.cg_caption }}</div>
              }
            </div>
          }
        </div>
      </div>
    }

    <!-- ========== TAB: RECENSIONI ========== -->
    @if (activeTab === 'reviews') {
      <div class="tab-content">
        <!-- Sintesi statistiche -->
        @if (reviewStats && reviewStats.total_count > 0) {
          <div class="reviews-summary">
            <div class="rs-avg">
              <div class="rs-avg-value">{{ (reviewStats.avg_overall || 0) | number: '1.1-1' }}</div>
              <div class="review-stars">
                @for (s of stars; track s) {
                  <ion-icon [name]="s <= (reviewStats.avg_overall || 0) ? 'star' : 'star-outline'"></ion-icon>
                }
              </div>
              <div class="rs-count">{{ reviewStats.total_count }} recensioni</div>
            </div>
            <div class="rs-dist">
              @for (d of reviewDistribution; track d.stars) {
                <div class="rs-dist-row">
                  <span class="rs-dist-stars">{{ d.stars }}<ion-icon name="star"></ion-icon></span>
                  <div class="rs-dist-bar"><div class="rs-dist-fill" [style.width.%]="d.pct"></div></div>
                  <span class="rs-dist-count">{{ d.count }}</span>
                </div>
              }
            </div>
          </div>
        }
        <!-- Breakdown per categoria -->
        @if (reviewStats?.by_category?.length) {
          <div class="reviews-categories">
            @for (cat of reviewStats!.by_category; track cat) {
              <ion-chip outline="true">
                <ion-label>{{ cat.service_type_name || 'Altro' }} · {{ cat.avg_overall | number: '1.1-1' }}★ ({{ cat.count }})</ion-label>
              </ion-chip>
            }
          </div>
        }
        <!-- Lista recensioni -->
        @for (r of reviews; track r) {
          <div class="review-card">
            <div class="review-card-head">
              <div class="review-stars">
                @for (s of stars; track s) {
                  <ion-icon [name]="s <= r.rev_rating_overall ? 'star' : 'star-outline'"></ion-icon>
                }
                <span class="review-overall">{{ r.rev_rating_overall | number: '1.1-1' }}</span>
              </div>
              <ion-button fill="clear" size="small" color="medium" (click)="reportReview(r)">
                <ion-icon name="flag-outline" slot="icon-only"></ion-icon>
              </ion-button>
            </div>
            @if (r.rev_title) {
              <div class="review-title">{{ r.rev_title }}</div>
            }
            @if (r.rev_text) {
              <p class="review-text">{{ r.rev_text }}</p>
            }
            <div class="review-meta">
              <span>{{ reviewClientName(r) }}</span>
              @if (r.rev_context_name) {
                <!-- Contesto snapshot: tipo servizio / risorsa prenotata / n. ordine -->
                <span class="review-service-tag" [style.background-color]="r.rev_context_color || '#94A3B8'">{{ r.rev_context_name }}</span>
              }
              <span>{{ r.rev_created_at | date: 'dd/MM/yyyy' }}</span>
            </div>
          </div>
        }
        @if (!loadingReviews && reviews.length === 0) {
          <div class="att-empty">Nessuna recensione</div>
        }
      </div>
    }

    <div style="height: 32px;"></div>
  </div>
</ion-content>

<!-- ========== BOOKING BAR ========== -->
@if (selectedService && activeTab === 'services' && !isGestore) {
  <div class="booking-bar">
    <div class="booking-bar-inner">
      <div class="booking-bar-info">
        <span class="booking-bar-service">
          @if (additionalServices.length === 0) {
            {{ selectedService.st_name }}
          }
          @if (additionalServices.length > 0) {
            {{ additionalServices.length + 1 }} servizi
          }
        </span>
        <span class="booking-bar-meta">{{ getTotalDuration() }} min</span>
      </div>
      <button class="booking-bar-btn" (click)="proceedToRequest()">
        Prenota
        <ion-icon name="arrow-forward-outline"></ion-icon>
      </button>
    </div>
  </div>
}

<!-- ========== CHAT MODAL ========== -->
<ion-modal #chatModal [breakpoints]="[0, 1]" [initialBreakpoint]="1" [handle]="true" class="chat-init-modal">
  <ng-template>
    <div class="chat-modal-wrap">
      <!-- Handle -->
      <div class="modal-handle-bar"></div>

      <!-- Avatar + Nome azienda -->
      <div class="chat-modal-header">
        <div class="company-avatar-ring">
          <div class="company-avatar-circle" [style.background]="getCompanyAvatarGradient()">
            <span>{{ getCompanyInitials() }}</span>
          </div>
        </div>
        <div class="chat-modal-company-info">
          <h3 class="chat-company-name">{{ company?.name || company?.cmp_name }}</h3>
          <p class="chat-company-sub">Invia un messaggio</p>
        </div>
      </div>

      <!-- Divider decorativo -->
      <div class="chat-modal-divider"></div>

      <!-- Textarea -->
      <div class="chat-textarea-wrap">
        <ion-textarea
          [(ngModel)]="chatMessage"
          placeholder="Scrivi qui la tua domanda o richiesta..."
          [autoGrow]="true"
          rows="4"
          maxlength="1000"
          class="chat-textarea">
        </ion-textarea>
        <div class="char-counter">{{ chatMessage.length }} / 1000</div>
      </div>

      <!-- Bottone invia -->
      <div class="chat-modal-actions">
        <button class="chat-send-btn" [class.sending]="chatSending" [disabled]="chatSending" (click)="sendChatMessage()">
          @if (!chatSending) {
            <span class="btn-label">
              <ion-icon name="send"></ion-icon>
              Apri Chat
            </span>
          }
          @if (chatSending) {
            <span class="btn-loading">
              <ion-spinner name="dots" color="light"></ion-spinner>
            </span>
          }
        </button>
        <button class="chat-cancel-btn" (click)="closeChatModal()" [disabled]="chatSending">
          Annulla
        </button>
      </div>
    </div>
  </ng-template>
</ion-modal>
