@php
  use Illuminate\Support\Facades\Storage;
  use Carbon\Carbon;
  use App\Models\EventoForm;

  $prenotaHasEventoForm = $evento->form && $evento->form->count() > 0;
  $prenotaWizardTotalSteps = $prenotaHasEventoForm ? 4 : 3;
@endphp

@extends('layouts/guest')

@section('title', 'Prenotazione - '.$evento->nome)

@section('page-style')
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet" />
@endsection

@section('app-css-extra')
@vite(['resources/css/guest-client.css'])
@endsection

@section('pageTitle')
<div class="d-flex flex-column align-items-center">
  <h2 class="mb-1 fw-bold">
    <i class="bx bx-calendar-check"></i>
    {{ $evento->nome }}
  </h2>
  <small class="text-muted">Prenotazione</small>
</div>
@endsection

@section('content')
<style>
  .evento-cover {
    width: 100%;
    height: 310px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    border-top-left-radius: 1rem;
    border-top-right-radius: 1rem;
    position: relative;
    margin-bottom: -50px;
    background: linear-gradient(120deg, #d1d7e6 0%, #b5cae6 100%);
  }
  .evento-cover-image {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .evento-cover-placeholder {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #607080;
    font-size: 0.95rem;
  }
  .evento-banner {
    margin-top: 60px;
    width: 100%;
    background: #fff;
    border-radius: 0 0 1rem 1rem;
    padding: 2rem 2rem 1.5rem 2rem;
    box-shadow: 0 4px 30px 0 rgba(44, 62, 80, 0.10);
    min-height: 240px;
  }
  @media (max-width: 768px) {
    .evento-cover {
      height: 180px;
    }
    .evento-banner {
      padding: 1.2rem 0.5rem 1rem 0.5rem;
    }
  }
  .prenota-form-section {
    margin-bottom: 1.5rem;
    padding-bottom: 1.25rem;
    border-bottom: 1px solid rgba(226, 230, 239, 0.95);
  }
  .prenota-form-section:last-of-type {
    border-bottom: 0;
    padding-bottom: 0;
    margin-bottom: 0;
  }
  .prenota-form-section .form-label {
    font-weight: 600;
    font-size: 0.875rem;
    margin-bottom: 0.35rem;
  }
  .prenota-field-stack .input-group > .form-control,
  .prenota-field-stack .input-group > .form-select {
    min-height: 2.85rem;
  }
  .prenota-wizard-step {
    display: none;
    animation: prenotaWizardFade 0.2s ease;
  }
  .prenota-wizard-step.is-active {
    display: block;
  }
  @keyframes prenotaWizardFade {
    from { opacity: 0.35; }
    to { opacity: 1; }
  }
  .prenota-wizard-progress-num {
    font-size: 0.7rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: var(--fest-muted, #6b7280);
  }
  .prenota-wizard-dots {
    display: flex;
    justify-content: center;
    gap: 0.35rem;
    flex-wrap: wrap;
  }
  .prenota-wizard-dot {
    width: 8px;
    height: 8px;
    border-radius: 999px;
    background: #d1d5db;
    transition: background 0.2s ease, transform 0.2s ease;
  }
  .prenota-wizard-dot.is-done {
    background: var(--fest-orange, #f58220);
  }
  .prenota-wizard-dot.is-current {
    background: var(--fest-purple, #602d91);
    transform: scale(1.25);
  }
  #prenotaWizardNav .btn {
    min-height: 2.85rem;
  }
</style>

@include('_partials.status')

<div class="guest-fest guest-fest-bg">
<div class="row justify-content-center">
  <div class="col-xxl-7 col-lg-10 mt-2 mb-4">
    <div class="card p-0 border-0 shadow-sm" style="border-radius: 1rem; overflow: hidden;">

      <div class="evento-cover">
        @if($evento->copertina)
          <img
            class="evento-cover-image"
            src="{{ Storage::disk('eventi')->url($evento->copertina) }}"
            alt="Copertina {{ $evento->nome }}"
          >
        @else
          <div class="evento-cover-placeholder bg-light">
            <span><i class="bx bx-image me-1"></i> Nessuna copertina</span>
          </div>
        @endif
      </div>

      <div class="evento-banner">
        <h2 class="guest-fest-page-title text-center mb-2" style="font-size: clamp(1.25rem, 3vw, 1.65rem);">
          {{ $evento->nome }}
        </h2>
        <div class="d-flex flex-wrap justify-content-center align-items-center gap-3 small mb-3 text-secondary">
          @php
            $dataInizio = $evento->data_inizio ? Carbon::parse($evento->data_inizio) : null;
            $dataFine = $evento->data_fine ? Carbon::parse($evento->data_fine) : null;
            $sameDay = $dataInizio && $dataFine && $dataInizio->isSameDay($dataFine);
            $allDayInizio = $dataInizio && $dataInizio->format('H:i') === '00:00';
            $allDayFine = $dataFine && $dataFine->format('H:i') === '00:00';
            $isAllDay = $allDayInizio && ($sameDay ? $allDayFine : true);
          @endphp

          @if($dataInizio)
            @if($sameDay)
              <div>
                <i class="bx bx-calendar fs-5 align-middle" style="color: #ffbc42;"></i>
                <span class="fw-semibold">Giorno:</span>
                <span>{{ $dataInizio->format('d/m/Y') }}</span>
                @if(!$isAllDay)
                  <span class="mx-2">
                    <i class="bx bx-time fs-5 align-middle" style="color:#8257e5;"></i>
                    <span>
                      {{ $dataInizio->format('H:i') }} - {{ $dataFine ? $dataFine->format('H:i') : $dataInizio->format('H:i') }}
                    </span>
                  </span>
                @endif
              </div>
            @else
              @if($isAllDay)
                <div>
                  <i class="bx bx-calendar fs-5 align-middle" style="color: #ffbc42;"></i>
                  <span class="fw-semibold">Dal</span>
                  <span>{{ $dataInizio->format('d/m/Y') }}</span>
                  <span class="fw-semibold">al</span>
                  <span>{{ $dataFine ? $dataFine->format('d/m/Y') : '-' }}</span>
                </div>
              @else
                <div>
                  <i class="bx bx-calendar fs-5 align-middle" style="color: #ffbc42;"></i>
                  <span class="fw-semibold">Inizio:</span>
                  <span>{{ $dataInizio->format('d/m/Y') }}</span>
                  <i class="bx bx-time fs-5 align-middle ms-1" style="color:#8257e5;"></i>
                  <span>{{ $dataInizio->format('H:i') }}</span>
                </div>
                @if($dataFine)
                  <div>
                    <i class="bx bx-calendar-minus fs-5 align-middle" style="color: #2ec4b6;"></i>
                    <span class="fw-semibold">Fine:</span>
                    <span>{{ $dataFine->format('d/m/Y') }}</span>
                    <i class="bx bx-time fs-5 align-middle ms-1" style="color:#8257e5;"></i>
                    <span>{{ $dataFine->format('H:i') }}</span>
                  </div>
                @endif
              @endif
            @endif
          @endif

          <div>
            <i class="bx bx-map fs-5 align-middle" style="color: #54428e;"></i>
            <span class="fw-semibold">Luogo:</span>
            <span>{{ $evento->luogo ?? '-' }}</span>
          </div>
        </div>

        <div class="text-center mb-4">
          <a href="{{ route('evento.show', ['evento_id' => $evento->id]) }}" class="btn btn-sm btn-outline-secondary">
            <i class="bx bx-arrow-back me-1"></i> Scheda evento
          </a>
        </div>

        <p class="text-center text-muted small mb-0">
          Compila il modulo a passi e invia la richiesta di prenotazione.
        </p>

        <div class="mt-4 pt-4 border-top">
          <form
            method="POST"
            action="{{ route('prenotazone.prenota', ['evento_id' => $evento->id]) }}"
            class="prenota-field-stack"
            id="prenotaWizardForm"
            novalidate
            data-wizard-total="{{ $prenotaWizardTotalSteps }}"
          >
            @csrf

            <div class="prenota-wizard-progress mb-4" aria-live="polite">
              <div class="d-flex justify-content-between align-items-start gap-2 mb-2">
                <span id="prenotaWizardStepLabel" class="prenota-wizard-progress-num">Passo 1 di {{ $prenotaWizardTotalSteps }}</span>
                <span class="small text-muted text-end" id="prenotaWizardStepHint" style="max-width: 12rem;"></span>
              </div>
              <div class="prenota-wizard-dots" id="prenotaWizardDots" role="tablist" aria-label="Avanzamento passi"></div>
            </div>

            <div class="prenota-wizard-step is-active" data-step-title="I tuoi dati">
            <section class="prenota-form-section border-0 pb-0 mb-0" aria-labelledby="prenota-sec-contatti">
              <h3 id="prenota-sec-contatti" class="guest-fest-subsection-title mb-3">I tuoi dati</h3>
              <p class="small text-muted mb-3 mb-md-4">Nome, contatti e recapito: servono per confermare la prenotazione.</p>
              <div class="row g-3">
                <div class="col-12 col-md-6">
                  <label class="form-label" for="nome">Nome *</label>
                  <div class="input-group input-group-merge">
                    <span id="prenota-nome-icon" class="input-group-text"><i class="bx bx-user"></i></span>
                    <input
                      type="text"
                      class="form-control @error('nome') is-invalid @enderror"
                      id="nome"
                      name="nome"
                      value="{{ old('nome') }}"
                      placeholder="Mario"
                      autocomplete="given-name"
                      inputmode="text"
                      aria-label="Nome"
                      aria-describedby="prenota-nome-icon"
                      required
                    >
                  </div>
                  @error('nome')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                  @enderror
                </div>

                <div class="col-12 col-md-6">
                  <label class="form-label" for="cognome">Cognome *</label>
                  <div class="input-group input-group-merge">
                    <span id="prenota-cognome-icon" class="input-group-text"><i class="bx bx-user-circle"></i></span>
                    <input
                      type="text"
                      class="form-control @error('cognome') is-invalid @enderror"
                      id="cognome"
                      name="cognome"
                      value="{{ old('cognome') }}"
                      placeholder="Rossi"
                      autocomplete="family-name"
                      inputmode="text"
                      aria-label="Cognome"
                      aria-describedby="prenota-cognome-icon"
                      required
                    >
                  </div>
                  @error('cognome')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                  @enderror
                </div>

                <div class="col-12">
                  <label class="form-label" for="email">Email *</label>
                  <div class="input-group input-group-merge">
                    <span class="input-group-text"><i class="bx bx-envelope"></i></span>
                    <input
                      type="email"
                      class="form-control @error('email') is-invalid @enderror"
                      id="email"
                      name="email"
                      value="{{ old('email') }}"
                      placeholder="nome@esempio.it"
                      autocomplete="email"
                      inputmode="email"
                      aria-label="Email"
                      required
                    >
                  </div>
                  @error('email')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                  @enderror
                </div>

                <div class="col-12">
                  <label class="form-label" for="telefono">Telefono <span class="text-muted fw-normal">(facoltativo)</span></label>
                  <div class="input-group input-group-merge">
                    <span id="prenota-telefono-icon" class="input-group-text"><i class="bx bx-phone"></i></span>
                    <input
                      type="tel"
                      class="form-control @error('telefono') is-invalid @enderror"
                      id="telefono"
                      name="telefono"
                      value="{{ old('telefono') }}"
                      placeholder="+39 333 1234567"
                      autocomplete="tel"
                      inputmode="tel"
                      aria-label="Telefono"
                      aria-describedby="prenota-telefono-icon"
                    >
                  </div>
                  @error('telefono')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                  @enderror
                </div>
              </div>
            </section>
            </div>

            <div class="prenota-wizard-step" data-step-title="Prenotazione">
            <section class="prenota-form-section border-0 pb-0 mb-0" aria-labelledby="prenota-sec-prenotazione">
              <h3 id="prenota-sec-prenotazione" class="guest-fest-subsection-title mb-3">Prenotazione</h3>
              <div class="row g-3">
                <div class="col-12 col-sm-8 col-md-6">
                  <label class="form-label" for="numero_persone">Quante persone? *</label>
                  <div class="input-group input-group-merge">
                    <span id="prenota-persone-icon" class="input-group-text"><i class="bx bx-group"></i></span>
                    <input
                      type="number"
                      min="1"
                      class="form-control @error('numero_persone') is-invalid @enderror"
                      id="numero_persone"
                      name="numero_persone"
                      value="{{ old('numero_persone', 1) }}"
                      inputmode="numeric"
                      aria-label="Numero persone"
                      aria-describedby="prenota-persone-icon prenota-persone-suffix"
                      required
                    >
                    <span id="prenota-persone-suffix" class="input-group-text">coperti</span>
                  </div>
                  @error('numero_persone')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                  @enderror
                </div>

                <div class="col-12">
                  <label class="form-label" for="note">Note <span class="text-muted fw-normal">(facoltativo)</span></label>
                  <div class="input-group input-group-merge">
                    <span id="prenota-note-icon" class="input-group-text align-items-start pt-3"><i class="bx bx-comment"></i></span>
                    <textarea
                      class="form-control @error('note') is-invalid @enderror"
                      id="note"
                      name="note"
                      rows="3"
                      placeholder="Allergie, preferenze o altre informazioni utili"
                      autocomplete="off"
                      aria-label="Note"
                      aria-describedby="prenota-note-icon"
                    >{{ old('note') }}</textarea>
                  </div>
                  @error('note')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                  @enderror
                </div>
              </div>
            </section>
            </div>

            @if($prenotaHasEventoForm)
            <div class="prenota-wizard-step" data-step-title="Richieste evento">
              <section class="prenota-form-section border-0 pb-0 mb-0" aria-labelledby="prenota-sec-evento">
                <h3 id="prenota-sec-evento" class="guest-fest-subsection-title mb-3">Richieste per l&apos;evento</h3>
                <p class="small text-muted mb-3">Compila i campi richiesti dall&apos;organizzazione.</p>
                <div class="row g-3">
                  @foreach($evento->form as $form)
                    @if($form->tipo == EventoForm::ELENCO)
                      <div class="col-12">
                        <label class="form-label" for="prenotazione_risposta_{{ $form->id }}">{{ $form->label }}</label>
                        <select class="form-select" id="prenotazione_risposta_{{ $form->id }}" name="prenotazione_risposta_{{ $form->id }}">
                          <option value="">Seleziona</option>
                          @foreach($form->opzioni_form as $opzione)
                            <option value="{{ $opzione->id }}" @selected(old('prenotazione_risposta_'.$form->id) == $opzione->id)>{{ $opzione->label }}</option>
                          @endforeach
                        </select>
                      </div>
                    @elseif($form->tipo == EventoForm::TESTO)
                      <div class="col-12">
                        <label class="form-label" for="prenotazione_risposta_{{ $form->id }}">{{ $form->label }}</label>
                        <input type="text" class="form-control" id="prenotazione_risposta_{{ $form->id }}" name="prenotazione_risposta_{{ $form->id }}" value="{{ old('prenotazione_risposta_'.$form->id) }}">
                      </div>
                    @elseif($form->tipo == EventoForm::NUMERO)
                      <div class="col-12 col-sm-8 col-md-6">
                        <label class="form-label" for="prenotazione_risposta_{{ $form->id }}">{{ $form->label }}</label>
                        <input type="number" class="form-control" id="prenotazione_risposta_{{ $form->id }}" name="prenotazione_risposta_{{ $form->id }}" value="{{ old('prenotazione_risposta_'.$form->id) }}" inputmode="numeric">
                      </div>
                    @elseif($form->tipo == EventoForm::ORA)
                      <div class="col-12 col-sm-8 col-md-6">
                        <label class="form-label" for="prenotazione_risposta_{{ $form->id }}">{{ $form->label }}</label>
                        <input type="time" class="form-control" id="prenotazione_risposta_{{ $form->id }}" name="prenotazione_risposta_{{ $form->id }}" value="{{ old('prenotazione_risposta_'.$form->id) }}">
                      </div>
                    @elseif($form->tipo == EventoForm::SELEZIONE)
                      <div class="col-12">
                        <label class="form-label" for="selezione_{{ $form->id }}">{{ $form->label }}</label>
                        <select class="form-select" id="selezione_{{ $form->id }}" name="selezione_{{ $form->id }}">
                          <option value="">Seleziona</option>
                          @foreach($form->opzioni as $opzione)
                            <option value="{{ $opzione }}" @selected(old('selezione_'.$form->id) == $opzione)>{{ $opzione }}</option>
                          @endforeach
                        </select>
                      </div>
                    @endif
                  @endforeach
                </div>
              </section>
            </div>
            @endif

            <div class="prenota-wizard-step" data-step-title="Privacy e invio">
            <section class="prenota-form-section mb-0 pb-0 border-0" aria-labelledby="prenota-sec-privacy">
              <h3 id="prenota-sec-privacy" class="guest-fest-subsection-title mb-3">Privacy</h3>
              <p class="small text-muted mb-3">Leggi l&apos;informativa prima di inviare. Puoi aprirla qui sotto.</p>
              <div class="accordion guest-fest-accordion" id="accordionPrivacy">
                <div class="accordion-item border-0">
                  <h2 class="accordion-header" id="headingPrivacy">
                    <button
                      type="button"
                      class="accordion-button collapsed guest-fest-accordion-btn rounded"
                      data-bs-toggle="collapse"
                      data-bs-target="#accordionPrivacyContent"
                      aria-expanded="false"
                      aria-controls="accordionPrivacyContent"
                    >
                      Apri testo completo dell&apos;informativa privacy
                    </button>
                  </h2>
                  <div
                    id="accordionPrivacyContent"
                    class="accordion-collapse collapse"
                    aria-labelledby="headingPrivacy"
                    data-bs-parent="#accordionPrivacy"
                  >
                    <div class="accordion-body guest-fest-accordion-body mt-2">
                      @include('testi.show', ['testi' => \App\Models\Testi::where('ambiente', 'cliente')->where('tipo', 'privacy')->where('is_attivo', true)->first()])
                    </div>
                  </div>
                </div>
              </div>
            </section>

            <p class="small text-muted text-center mt-3 mb-0 px-1">
              Inviando il modulo dichiari di aver preso visione dell&apos;informativa privacy.
            </p>
            </div>

            <div class="d-flex flex-column flex-sm-row gap-2 gap-sm-3 mt-4 pt-3 border-top align-items-stretch align-items-sm-center" id="prenotaWizardNav">
              <button type="button" class="btn btn-outline-secondary order-2 order-sm-1" id="prenotaWizardPrev" hidden>
                <i class="bx bx-chevron-left"></i> Indietro
              </button>
              <button type="button" class="btn btn-primary btn-lg py-3 rounded-pill order-1 order-sm-2 ms-sm-auto" id="prenotaWizardNext">
                Avanti <i class="bx bx-chevron-right"></i>
              </button>
              <button type="submit" class="btn btn-primary btn-lg py-3 rounded-pill order-1 order-sm-2 ms-sm-auto" id="prenotaWizardSubmit" hidden>
                <i class="bx bx-send me-1"></i> Invia richiesta di prenotazione
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</div>

@endsection

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', function () {
    var form = document.getElementById('prenotaWizardForm');
    if (!form) return;

    var steps = Array.prototype.slice.call(form.querySelectorAll('.prenota-wizard-step'));
    var total = steps.length;
    var labelEl = document.getElementById('prenotaWizardStepLabel');
    var hintEl = document.getElementById('prenotaWizardStepHint');
    var dotsEl = document.getElementById('prenotaWizardDots');
    var btnPrev = document.getElementById('prenotaWizardPrev');
    var btnNext = document.getElementById('prenotaWizardNext');
    var btnSubmit = document.getElementById('prenotaWizardSubmit');
    var currentIdx = 0;

    if (!total || !dotsEl) return;

    for (var d = 0; d < total; d++) {
      var dot = document.createElement('span');
      dot.className = 'prenota-wizard-dot';
      dot.setAttribute('aria-hidden', 'true');
      dotsEl.appendChild(dot);
    }

    function validateStep(stepEl) {
      var controls = stepEl.querySelectorAll('input, select, textarea');
      for (var i = 0; i < controls.length; i++) {
        var el = controls[i];
        if (el.closest('.prenota-wizard-step') !== stepEl) continue;
        if (el.type === 'hidden' || el.disabled) continue;
        if (typeof el.checkValidity === 'function' && !el.checkValidity()) {
          el.reportValidity();
          return false;
        }
      }
      return true;
    }

    function goToStep(idx) {
      if (idx < 0 || idx >= total) return;
      currentIdx = idx;
      for (var s = 0; s < total; s++) {
        steps[s].classList.toggle('is-active', s === currentIdx);
      }
      var dots = dotsEl.querySelectorAll('.prenota-wizard-dot');
      for (var j = 0; j < dots.length; j++) {
        dots[j].classList.toggle('is-done', j < currentIdx);
        dots[j].classList.toggle('is-current', j === currentIdx);
      }
      if (labelEl) {
        labelEl.textContent = 'Passo ' + (currentIdx + 1) + ' di ' + total;
      }
      if (hintEl) {
        var title = steps[currentIdx].getAttribute('data-step-title') || '';
        hintEl.textContent = title;
      }
      if (btnPrev) btnPrev.hidden = currentIdx === 0;
      var last = currentIdx === total - 1;
      if (btnNext) btnNext.hidden = last;
      if (btnSubmit) btnSubmit.hidden = !last;
      try {
        steps[currentIdx].scrollIntoView({ block: 'nearest', behavior: 'smooth' });
      } catch (e) {}
    }

    var invalid = form.querySelector('.is-invalid');
    if (invalid) {
      var parentStep = invalid.closest('.prenota-wizard-step');
      if (parentStep) {
        var ix = steps.indexOf(parentStep);
        if (ix !== -1) currentIdx = ix;
      }
    }

    goToStep(currentIdx);

    if (btnNext) {
      btnNext.addEventListener('click', function () {
        if (!validateStep(steps[currentIdx])) return;
        if (currentIdx < total - 1) goToStep(currentIdx + 1);
      });
    }
    if (btnPrev) {
      btnPrev.addEventListener('click', function () {
        if (currentIdx > 0) goToStep(currentIdx - 1);
      });
    }

    form.addEventListener('submit', function (e) {
      for (var k = 0; k < total; k++) {
        if (!validateStep(steps[k])) {
          e.preventDefault();
          goToStep(k);
          return;
        }
      }
    });
  });
</script>
@endsection
