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

  <!-- Step indicator -->
  <div class="step-indicator">
    <div class="step-item" [class.active]="currentStep >= 1" [class.done]="currentStep > 1" (click)="currentStep > 1 ? goToStep(1) : null">
      <div class="step-dot"><span>1</span></div>
      <span class="step-label">Data</span>
    </div>
    <div class="step-line" [class.done]="currentStep > 1"></div>
    <div class="step-item" [class.active]="currentStep >= 2" [class.done]="currentStep > 2" (click)="currentStep > 2 ? goToStep(2) : null">
      <div class="step-dot"><span>2</span></div>
      <span class="step-label">Disponibilità</span>
    </div>
    <div class="step-line" [class.done]="currentStep > 2"></div>
    <div class="step-item" [class.active]="currentStep >= 3">
      <div class="step-dot"><span>3</span></div>
      <span class="step-label">Dati cliente</span>
    </div>
  </div>

  <!-- STEP 1: TIPO RISORSA -->
  @if (currentStep === 1) {
    <div class="ion-padding">
      <h3>Seleziona il tipo di prenotazione</h3>
      <ion-list>
        @for (type of activeResourceTypes; track type) {
          <ion-item button (click)="onTypeSelected(type, true)"
            [color]="selectedType?.bkrt_id === type.bkrt_id ? 'light' : ''">
            <ion-label>
              <h2>{{ type.bkrt_name }}</h2>
              <p>{{ type.bkrt_description }}</p>
            </ion-label>
            @if (selectedType?.bkrt_id === type.bkrt_id) {
              <ion-icon name="checkmark-circle" color="primary" slot="end"></ion-icon>
            }
          </ion-item>
        }
      </ion-list>
    </div>
  }

  <!-- STEP 2: DATA + RISORSE -->
  @if (currentStep === 2) {
    <div>
      <!-- ============ RISTORANTE ============ -->
      @if (isRestaurant) {
        <!-- Calendario con disponibilità giornaliera -->
        <div class="ion-padding-horizontal ion-padding-top">
          <p class="slot-title">Seleziona la data</p>
          <div class="restaurant-calendar-wrapper">
            <ion-datetime
              presentation="date"
              [min]="minBookingDate"
              [value]="selectedDate"
              [highlightedDates]="highlightedDatesArray"
              (ionChange)="onRestaurantDateChange($event)"
              (ionMonthChange)="onCalendarMonthChange($event)">
            </ion-datetime>
          </div>
          <div class="legend-row">
            <span class="legend-item"><span class="legend-dot legend-dot--green"></span>Disponibile</span>
            <span class="legend-item"><span class="legend-dot legend-dot--yellow"></span>Quasi pieno</span>
            <span class="legend-item"><span class="legend-dot legend-dot--red"></span>Pieno</span>
          </div>
        </div>
        <!-- Numero ospiti -->
        @if (selectedDate) {
          <div class="ion-padding-horizontal ion-padding-top">
            <p class="slot-title">Numero ospiti</p>
            <div class="guests-stepper">
              <ion-button fill="outline" size="small" (click)="decrementGuests()">
                <ion-icon name="remove-outline" slot="icon-only"></ion-icon>
              </ion-button>
              <span class="guests-count">{{ booking.bkb_guests_count || 1 }}</span>
              <ion-button fill="outline" size="small" (click)="incrementGuests()">
                <ion-icon name="add-outline" slot="icon-only"></ion-icon>
              </ion-button>
            </div>
          </div>
        }
        <!-- Fasce orarie con disponibilità per slot -->
        @if (selectedDate && timeSlots.length > 0) {
          <div class="ion-padding-horizontal ion-padding-top">
            <p class="slot-title">Fascia oraria</p>
            <ion-list class="ion-no-padding slots-list">
              @for (slot of timeSlots; track slot) {
                <ion-item button
                  [disabled]="!canFitInSlot(slot)"
                  [color]="selectedSlot?.bkts_id === slot.bkts_id ? 'light' : ''"
                  (click)="onSlotSelected(slot)">
                  <ion-label>
                    <h2>{{ slot.bkts_name }}</h2>
                    <p>{{ slot.bkts_start_time }} - {{ slot.bkts_end_time }}</p>
                    <div class="slot-bar">
                      <div class="slot-bar-fill"
                        [class.slot-bar-fill--yellow]="getSlotOccupancyPercent(slot) >= 50 && getSlotOccupancyPercent(slot) < 85"
                        [class.slot-bar-fill--red]="getSlotOccupancyPercent(slot) >= 85"
                      [style.width.%]="getSlotOccupancyPercent(slot)"></div>
                    </div>
                  </ion-label>
                  <div slot="end" class="slot-avail">
                    <span class="slot-free" [class.no-free]="getSlotFree(slot) === 0">{{ getSlotFree(slot) }}</span>
                    <span class="slot-total">/ {{ totalCapacity }} posti</span>
                  </div>
                  @if (selectedSlot?.bkts_id === slot.bkts_id) {
                    <ion-icon name="checkmark-circle" color="primary" slot="end"></ion-icon>
                  }
                </ion-item>
              }
            </ion-list>
          </div>
        }
        <!-- Riepilogo + pulsante avanti -->
        @if (selectedDate && selectedSlot) {
          <div class="ion-padding">
            <div class="restaurant-summary">
              <ion-icon name="information-circle-outline" color="primary"></ion-icon>
              <span>La prenotazione resterà <strong>in attesa</strong> finché il ristorante non assegna i tavoli.</span>
            </div>
            <ion-button expand="block" color="primary" [disabled]="!canGoNext()" (click)="nextStep()">
              Avanti
              <ion-icon name="arrow-forward-outline" slot="end"></ion-icon>
            </ion-button>
          </div>
        }
      }
      <!-- ============ OMBRELLONE / GENERIC ============ -->
      @if (!isRestaurant) {
        <!-- Date sulla stessa riga -->
        <div class="date-row ion-padding-horizontal ion-padding-top">
          <div class="date-field">
            <label class="date-label">Da</label>
            <input class="date-input" type="date" [(ngModel)]="selectedDate" (change)="onDateFromChange()"/>
          </div>
          <div class="date-field">
            <label class="date-label">A</label>
            <input class="date-input" type="date" [(ngModel)]="selectedDateTo" [min]="selectedDate" (change)="onDateToChange()"/>
          </div>
        </div>
        <!-- Slot orari (solo non-BEACH) -->
        @if (!isBeach && timeSlots.length > 0) {
          <div class="ion-padding-horizontal ion-padding-top">
            <p class="slot-title">Orario</p>
            <div class="slots-container">
              @for (slot of timeSlots; track slot) {
                <ion-chip
                  [color]="selectedSlot?.bkts_id === slot.bkts_id ? 'primary' : 'medium'"
                  (click)="onSlotSelected(slot)">
                  {{ slot.bkts_name }} ({{ slot.bkts_start_time }} - {{ slot.bkts_end_time }})
                </ion-chip>
              }
            </div>
          </div>
        }
        <!-- Risorse: appaiono appena le date sono selezionate -->
        @if (dateReady) {
          <div>
            <!-- Tab full-width -->
            <ion-segment [(ngModel)]="resourceViewMode" class="risorse-segment">
              <ion-segment-button value="lista">
                <ion-icon name="list-outline"></ion-icon>
                <ion-label>Lista</ion-label>
              </ion-segment-button>
              <ion-segment-button value="mappa">
                <ion-icon name="map-outline"></ion-icon>
                <ion-label>Mappa</ion-label>
              </ion-segment-button>
            </ion-segment>
            <!-- Vista Lista -->
            @if (resourceViewMode === 'lista') {
              @if (isBeach && selectedGroupY === null) {
                <ion-list class="ion-no-padding">
                  @for (g of resourceGroups; track g.fila) {
                    <ion-item button (click)="selectedGroupY = g.y"
                      [style.border-left]="'4px solid ' + g.borderColor">
                      <ion-label>
                        <h2>Fila {{ g.fila }} &mdash; {{ g.tipologia }}</h2>
                        @if (g.prezzo > 0) {
                          <p>&euro; {{ g.prezzo | number:'1.2-2' }} &bull; {{ giorni }} gg</p>
                        }
                      </ion-label>
                      <div slot="end" class="group-avail">
                        <span class="group-free" [class.no-free]="g.freeCount === 0">{{ g.freeCount }} liberi</span>
                        <span class="group-total">/ {{ g.total }}</span>
                      </div>
                      <ion-icon name="chevron-forward-outline" slot="end"></ion-icon>
                    </ion-item>
                  }
                </ion-list>
              }
              @if (!isBeach || selectedGroupY !== null) {
                <ion-item lines="none" class="lista-filter-row">
                  @if (isBeach) {
                    <ion-button fill="clear" size="small" slot="start" (click)="selectedGroupY = null">
                      <ion-icon name="arrow-back-outline" slot="icon-only"></ion-icon>
                    </ion-button>
                  }
                  <ion-label>Solo liberi</ion-label>
                  <ion-toggle [(ngModel)]="soloLiberi" slot="end"></ion-toggle>
                </ion-item>
                <ion-list class="ion-no-padding">
                  @for (res of (isBeach ? selectedGroupResources : filteredResources); track res) {
                    <ion-item
                      button (click)="onResourceSelected(res)" [disabled]="isBooked(res.bkr_id)"
                      [color]="selectedResource?.bkr_id === res.bkr_id ? 'light' : ''">
                      <ion-label>
                        <h2>{{ res.bkr_name }}</h2>
                        <p>{{ getResourceSubtype(res) === 'PALMA' ? 'Palma' : 'Ombrellone' }}@if (getPrezzoRisorsa(res) > 0) {
                          &mdash; <strong>&euro; {{ getPrezzoRisorsa(res) | number:'1.2-2' }}</strong>
                        }</p>
                        @if (getPrezzoDettaglioRisorsa(res).length > 1) {
                          <p class="prezzo-info">
                            @for (v of getPrezzoDettaglioRisorsa(res); track v.label; let last = $last) {
                              {{ v.label }} &euro;{{ v.subtotal | number:'1.2-2' }}@if (!last) {
                              &bull;
                            }
                          }
                        </p>
                      }
                    </ion-label>
                    <ion-badge slot="end" [color]="isBooked(res.bkr_id) ? 'danger' : 'success'">
                      {{ isBooked(res.bkr_id) ? 'Occupato' : 'Disponibile' }}
                    </ion-badge>
                    @if (selectedResource?.bkr_id === res.bkr_id) {
                      <ion-icon name="checkmark-circle" color="primary" slot="end"></ion-icon>
                    }
                  </ion-item>
                }
              </ion-list>
            }
          }
          <!-- Vista Mappa — usa il componente condiviso <app-resource-map> -->
          @if (resourceViewMode === 'mappa') {
            <app-resource-map
              [resources]="resourcesAll"
              [bookedResourceIds]="bookedResourceIds"
              [selectedResource]="selectedResource"
              [mode]="isBeach ? 'beach' : 'standard'"
              [getFilaColors]="getFilaColorsCallback"
              (resourceClick)="onResourceSelected($event)">
            </app-resource-map>
          }
        </div>
      }
    }
  </div>
}

<!-- STEP 3: DATI CLIENTE -->
@if (currentStep === 3) {
  <div class="ion-padding">
    <!-- Riepilogo prenotazione (ristorante) -->
    @if (isRestaurant) {
      <div class="restaurant-recap">
        <div class="recap-row">
          <ion-icon name="calendar-outline" color="primary"></ion-icon>
          <span>{{ selectedDate | date:'EEEE d MMMM y' }}</span>
        </div>
        @if (selectedSlot) {
          <div class="recap-row">
            <ion-icon name="time-outline" color="primary"></ion-icon>
            <span>{{ selectedSlot.bkts_name }} ({{ selectedSlot.bkts_start_time }} - {{ selectedSlot.bkts_end_time }})</span>
          </div>
        }
        <div class="recap-row">
          <ion-icon name="people-outline" color="primary"></ion-icon>
          <span>{{ booking.bkb_guests_count || 1 }} ospiti</span>
        </div>
      </div>
    }
    <h3>Dati del cliente</h3>
    <ion-list>
      <ion-item>
        <ion-label position="stacked">Nome *</ion-label>
        <ion-input [(ngModel)]="booking.bkb_customer_name" placeholder="Nome e cognome"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="stacked">Telefono *</ion-label>
        <ion-input type="tel" [(ngModel)]="booking.bkb_customer_phone" placeholder="+39 ..."></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="stacked">Email</ion-label>
        <ion-input type="email" [(ngModel)]="booking.bkb_customer_email" placeholder="email@esempio.com"></ion-input>
      </ion-item>
      @if (!isBeach) {
        <ion-item>
          <ion-label position="stacked">Numero ospiti</ion-label>
          <ion-input type="number" [(ngModel)]="booking.bkb_guests_count" min="1"></ion-input>
        </ion-item>
      }
      <ion-item>
        <ion-label position="stacked">Note</ion-label>
        <ion-textarea [(ngModel)]="booking.bkb_notes" rows="3" placeholder="Richieste particolari..."></ion-textarea>
      </ion-item>
      @if (isBeach) {
        <ion-item>
          <ion-label position="stacked">Lettini</ion-label>
          <ion-input type="number" [(ngModel)]="booking.bkb_lettini" min="0" (ionChange)="calcolaPrezzo()"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label position="stacked">Sedie</ion-label>
          <ion-input type="number" [(ngModel)]="booking.bkb_sedie" min="0" (ionChange)="calcolaPrezzo()"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label position="stacked">Sdraio</ion-label>
          <ion-input type="number" [(ngModel)]="booking.bkb_sdraio" min="0" (ionChange)="calcolaPrezzo()"></ion-input>
        </ion-item>
      }
    </ion-list>
    <!-- Riepilogo prezzo (solo spiaggia) -->
    @if (isBeach && prezzoBase > 0) {
      <div class="prezzo-riepilogo">
        <div class="prezzo-header">
          <span class="prezzo-label">
            <ion-icon name="calculator-outline"></ion-icon>
            Prezzo base stimato
          </span>
          <strong class="prezzo-totale">€ {{ prezzoBase | number:'1.2-2' }}</strong>
        </div>
        @for (v of prezzoDettaglio; track v) {
          <div class="prezzo-riga">
            <span>{{ v.label }}</span>
            <span>€ {{ v.subtotal | number:'1.2-2' }}</span>
          </div>
        }
      </div>
    }
    <div class="ion-padding">
      <ion-button expand="block" color="success" [disabled]="!canGoNext()" (click)="conferma()">
        <ion-icon name="checkmark-outline" slot="start"></ion-icon>
        Conferma prenotazione
      </ion-button>
    </div>
  </div>
}

</ion-content>

<!-- FOOTER PREZZI FILA -->
@if (currentStep === 2 && isBeach && resourceViewMode === 'mappa' && filaLegend.length > 0) {
  <ion-footer>
    <div class="prezzi-fila">
      <div class="prezzi-fila-header" (click)="togglePrezzi()">
        <span>PREZZI PER FILA &mdash; {{ giorni }} GG</span>
        <ion-icon [name]="prezziExpanded ? 'chevron-up-outline' : 'chevron-down-outline'" class="prezzi-toggle-icon"></ion-icon>
      </div>
      @if (prezziExpanded) {
        <table class="prezzi-table">
          <thead>
            <tr>
              <th class="col-color"></th>
              <th class="col-nome"></th>
              <th class="col-price">Ombr.</th>
              <th class="col-price">Palma</th>
            </tr>
          </thead>
          <tbody>
            @for (f of filaLegendGrouped; track f.filaFrom) {
              <tr>
                <td class="col-color">
                  <div class="fila-color-box" [style.background]="f.bgColor" [style.border-color]="f.borderColor"></div>
                </td>
                <td class="col-nome">Fila {{ f.filaFrom }}{{ f.filaFrom !== f.filaTo ? '&ndash;' + f.filaTo : '' }}</td>
                <td class="col-price">
                  @if (f.ombrTotal !== null) {
                    <span>&euro; {{ f.ombrTotal | number:'1.0-2' }}</span>
                  }
                  @if (f.ombrTotal === null) {
                    <span class="no-price">&mdash;</span>
                  }
                </td>
                <td class="col-price">
                  @if (f.palmaTotal !== null) {
                    <span>&euro; {{ f.palmaTotal | number:'1.0-2' }}</span>
                  }
                  @if (f.palmaTotal === null) {
                    <span class="no-price">&mdash;</span>
                  }
                </td>
              </tr>
            }
          </tbody>
        </table>
        @if (filaLegend[0]?.periodName) {
          <div class="periodo-name">{{ filaLegend[0].periodName }}</div>
        }
        <div class="disp-legend">
          <span class="dot dot-libero"></span> Libero
          <span class="dot dot-prenotato"></span> Prenotato
        </div>
      }
    </div>
  </ion-footer>
}
