@php
$configData = Helper::appClasses();
$hasSnapshot = !empty($snapshot) && (
  isset($snapshot['incasso'])
  || !empty($snapshot['pagamenti_per_metodo'])
  || !empty($snapshot['cucine'])
);
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Chiusura servizio')

@section('vendor-style')
@vite([
  'resources/assets/vendor/libs/apex-charts/apex-charts.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/apex-charts/apexcharts.js'
])
@endsection

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1 text-sm-small mt-md-4 mt-lg-4">
    <i class="bx bx-time d-none d-md-inline-flex d-lg-inline-flex"></i>
    Chiusura servizio
    @if($chiusura->chiusura_at)
      <span class="text-muted fs-6 fw-normal">· {{ $chiusura->chiusura_at->format('d/m/Y H:i') }}</span>
    @endif
  </h4>
  <!-- <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block d-lg-block mb-0">
    <ol class="breadcrumb breadcrumb-custom-icon m-0">
      <li class="breadcrumb-item">
        <a href="{{ route('chiusura-servizio.index') }}">Chiusure servizio</a>
        <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
      </li>
      <li class="breadcrumb-item active text-primary">
        {{ $chiusura->chiusura_at?->format('d/m/Y H:i') ?? ('#' . $chiusura->id) }}
      </li>
    </ol>
  </nav> -->
</div>
@endsection

@section('content')
<style>
  .servizio-kpi-value {
    font-size: 1.75rem;
    font-weight: 700;
    line-height: 1.2;
  }

  .servizio-kpi-label {
    font-size: .8rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: var(--bs-secondary-color);
  }

  .servizio-metodo-row:last-child {
    border-bottom: 0 !important;
  }

  .snapshot-field-label {
    font-size: .75rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: var(--bs-secondary-color);
    margin-bottom: .25rem;
  }

  .snapshot-table-panel {
    border: 1px solid var(--bs-border-color);
    border-radius: .5rem;
    overflow: hidden;
    height: 100%;
  }

  .snapshot-table-panel__header {
    display: flex;
    align-items: center;
    gap: .5rem;
    padding: .75rem 1rem;
    border-bottom: 1px solid var(--bs-border-color);
    background: rgba(var(--bs-body-color-rgb), .03);
  }

  .snapshot-table-panel--qty {
    border-top: 3px solid var(--bs-success);
  }

  .snapshot-table-panel--qty .snapshot-table-panel__header {
    background: rgba(var(--bs-success-rgb), .08);
  }

  .snapshot-table-panel--incasso {
    border-top: 3px solid var(--bs-primary);
  }

  .snapshot-table-panel--incasso .snapshot-table-panel__header {
    background: rgba(var(--bs-primary-rgb), .08);
  }

  .snapshot-table-panel--orario {
    border-top: 3px solid var(--bs-warning);
  }

  .snapshot-table-panel--orario .snapshot-table-panel__header {
    background: rgba(var(--bs-warning-rgb), .08);
  }

  .snapshot-performance-table {
    margin-bottom: 0;
  }

  .snapshot-performance-table thead th {
    font-size: .72rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: var(--bs-secondary-color);
    font-weight: 600;
    border-bottom-width: 1px;
    white-space: nowrap;
  }

  .snapshot-performance-table tbody tr:hover {
    background: rgba(var(--bs-primary-rgb), .04);
  }

  .snapshot-performance-table tbody td {
    vertical-align: middle;
    padding-top: .55rem;
    padding-bottom: .55rem;
  }

  .snapshot-rank {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 1.75rem;
    height: 1.75rem;
    border-radius: 50%;
    font-size: .75rem;
    font-weight: 700;
  }

  .snapshot-rank--1 {
    background: rgba(var(--bs-warning-rgb), .18);
    color: var(--bs-warning);
  }

  .snapshot-rank--2 {
    background: rgba(var(--bs-secondary-rgb), .16);
    color: var(--bs-secondary-color);
  }

  .snapshot-rank--3 {
    background: rgba(var(--bs-info-rgb), .16);
    color: var(--bs-info);
  }

  .snapshot-rank--default {
    background: rgba(var(--bs-body-color-rgb), .06);
    color: var(--bs-secondary-color);
    font-weight: 600;
  }

  .snapshot-value-qty {
    font-variant-numeric: tabular-nums;
    font-weight: 600;
  }

  .snapshot-value-incasso {
    font-variant-numeric: tabular-nums;
    font-weight: 600;
    color: var(--bs-primary);
  }

  .snapshot-cucina-summary {
    padding: .65rem .85rem;
    border-radius: .5rem;
    border: 1px dashed var(--bs-border-color);
    background: rgba(var(--bs-body-color-rgb), .02);
  }

  .snapshot-metodo-icon {
    width: 2.25rem;
    height: 2.25rem;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: .45rem;
    background: rgba(var(--bs-primary-rgb), .1);
    color: var(--bs-primary);
    flex-shrink: 0;
  }
</style>

@include('_partials.status')

<!-- <div class="d-flex flex-wrap gap-2 mb-3">
  <a href="{{ route('chiusura-servizio.index') }}" class="btn btn-sm btn-label-secondary">
    <i class="bx bx-chevron-left me-1"></i> Torna all'elenco
  </a>
</div> -->

{{-- Dati chiusura --}}
<div class="card mb-4">
  <div class="card-header">
    <h5 class="mb-0">Registro chiusura</h5>
  </div>
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-3">
        <div class="snapshot-field-label">Data e ora</div>
        <span class="fw-semibold">{{ $chiusura->chiusura_at?->format('d/m/Y H:i:s') ?? '—' }}</span>
      </div>
      <div class="col-md-3">
        <div class="snapshot-field-label">Operatore</div>
        <span class="fw-semibold">{{ $chiusura->user?->fullName ?? '—' }}</span>
      </div>
      <div class="col-md-3">
        <div class="snapshot-field-label">Attività</div>
        <span class="fw-semibold">{{ $chiusura->attivita?->nome ?? '—' }}</span>
      </div>
      <div class="col-md-3">
        <div class="snapshot-field-label">Note</div>
        <span>{{ $chiusura->note ?: '—' }}</span>
      </div>
    </div>
  </div>
</div>

@if($hasSnapshot)
  @if($periodoDa && $periodoA)
    <div class="card mb-4 border-start border-3 border-info">
      <div class="card-body py-3 d-flex flex-wrap align-items-center gap-3">
        <div class="avatar avatar-sm">
          <span class="avatar-initial rounded bg-label-info">
            <i class="bx bx-time-five"></i>
          </span>
        </div>
        <div>
          <div class="fw-semibold">Periodo del servizio chiuso</div>
          <div class="text-muted small">
            Dal <strong>{{ $periodoDa->format('d/m/Y H:i') }}</strong>
            al <strong>{{ $periodoA->format('d/m/Y H:i') }}</strong>
            @if(!empty($snapshot['generato_at']))
              <span class="d-block mt-1">Snapshot generato il {{ \Carbon\Carbon::parse($snapshot['generato_at'])->format('d/m/Y H:i:s') }}</span>
            @endif
          </div>
        </div>
      </div>
    </div>
  @endif

  {{-- KPI snapshot --}}
  <div class="row g-3">
    <div class="col-md-4">
      <div class="card h-100 border-start border-4 border-primary">
        <div class="card-body">
          <div class="servizio-kpi-label mb-1">Incasso</div>
          <div class="servizio-kpi-value text-primary">
            € {{ number_format($totaleIncasso, 2, ',', '.') }}
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card h-100">
        <div class="card-body">
          <div class="servizio-kpi-label mb-1">Transazioni</div>
          <div class="servizio-kpi-value">
            {{ number_format($totaleTransazioni, 0, ',', '.') }}
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card h-100">
        <div class="card-body">
          <div class="servizio-kpi-label mb-1">Piatti ordinati</div>
          <div class="servizio-kpi-value">
            {{ number_format($totPiattiOrdinati, 0, ',', '.') }}
          </div>
        </div>
      </div>
    </div>
  </div>

  {{-- Pagamenti per metodo --}}
  <div class="card mt-4">
    <div class="card-header">
      <h5 class="mb-0">Pagamenti per metodo</h5>
    </div>
    <div class="card-body p-0">
      @forelse($paymentSummary as $row)
        <div class="d-flex justify-content-between align-items-center px-4 py-3 border-bottom servizio-metodo-row gap-3">
          <div class="d-flex align-items-center gap-3">
            <span class="snapshot-metodo-icon">
              <i class="bx bx-wallet"></i>
            </span>
            <div>
              <div class="fw-semibold">{{ $row['metodo'] ?? 'N/D' }}</div>
              <small class="text-muted">
                {{ number_format((int) ($row['count'] ?? 0), 0, ',', '.') }}
                {{ (int) ($row['count'] ?? 0) === 1 ? 'transazione' : 'transazioni' }}
              </small>
            </div>
          </div>
          <div class="fs-5 fw-semibold text-primary">
            € {{ number_format((float) ($row['totale'] ?? 0), 2, ',', '.') }}
          </div>
        </div>
      @empty
        <div class="p-4 text-muted">Nessun pagamento nello snapshot.</div>
      @endforelse
    </div>
  </div>

  {{-- Cucine e piatti --}}
  <div class="card mt-4">
    <div class="card-header">
      <h5 class="mb-0">Cucine e piatti</h5>
    </div>
    <div class="card-body">
      @if($cucineRows->isNotEmpty())
        <ul class="nav nav-tabs mb-3 flex-nowrap overflow-auto" role="tablist">
          @foreach($cucineRows as $index => $cucina)
            <li class="nav-item" role="presentation">
              <button
                class="nav-link {{ $index === 0 ? 'active' : '' }}"
                type="button"
                data-bs-toggle="tab"
                data-bs-target="#snapshot-cucina-{{ $index }}"
                role="tab"
                aria-selected="{{ $index === 0 ? 'true' : 'false' }}"
              >
                {{ $cucina['nome'] ?? 'Cucina' }}
                <span class="text-muted small ms-1">
                  ({{ number_format((int) ($cucina['tot_quantita'] ?? 0), 0, ',', '.') }})
                </span>
              </button>
            </li>
          @endforeach
        </ul>

        <div class="tab-content">
          @foreach($cucineRows as $index => $cucina)
            @php
              $piatti = collect($cucina['piatti'] ?? []);
              $piattiPerQuantita = $piatti
                ->sortByDesc(fn ($p) => (int) ($p['quantita'] ?? 0))
                ->values();
              $piattiPerIncasso = $piatti
                ->sortByDesc(fn ($p) => (float) ($p['totale'] ?? 0))
                ->values();
            @endphp
            <div
              class="tab-pane fade {{ $index === 0 ? 'show active' : '' }}"
              id="snapshot-cucina-{{ $index }}"
              role="tabpanel"
            >
              <div class="snapshot-cucina-summary d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                <span class="fw-semibold">
                  <i class="bx bx-restaurant me-1 text-success"></i>
                  {{ $cucina['nome'] ?? 'Cucina' }}
                </span>
                <span class="text-muted small">
                  {{ number_format((int) ($cucina['tot_quantita'] ?? 0), 0, ',', '.') }} ord.
                  · € {{ number_format((float) ($cucina['tot_importo'] ?? 0), 2, ',', '.') }}
                </span>
              </div>

              <div class="snapshot-table-panel snapshot-table-panel--orario mb-3">
                <div class="snapshot-table-panel__header">
                  <i class="bx bx-line-chart text-warning"></i>
                  <span class="fw-semibold">Affluenza oraria</span>
                  <span class="text-muted small">ordinazioni per ora nel servizio chiuso</span>
                </div>
                <div
                  id="chart-affluenza-cucina-{{ $index }}"
                  class="px-2 pb-2"
                  style="min-height: 240px;"
                  data-cucina-index="{{ $index }}"
                ></div>
              </div>

              <div class="row g-3">
                <div class="col-lg-6">
                  <div class="snapshot-table-panel snapshot-table-panel--qty">
                    <div class="snapshot-table-panel__header">
                      <i class="bx bx-trending-up text-success"></i>
                      <span class="fw-semibold">Più venduti</span>
                      <span class="text-muted small">per quantità</span>
                    </div>
                    <div class="table-responsive">
                      <table class="table table-sm table-hover snapshot-performance-table">
                        <thead>
                          <tr>
                            <th style="width: 3rem;">#</th>
                            <th>Piatto</th>
                            <th class="text-end">Qtà</th>
                          </tr>
                        </thead>
                        <tbody>
                          @forelse($piattiPerQuantita as $rank => $piatto)
                            @php $pos = $rank + 1; @endphp
                            <tr>
                              <td>
                                <span @class([
                                  'snapshot-rank',
                                  'snapshot-rank--1' => $pos === 1,
                                  'snapshot-rank--2' => $pos === 2,
                                  'snapshot-rank--3' => $pos === 3,
                                  'snapshot-rank--default' => $pos > 3,
                                ])>{{ $pos }}</span>
                              </td>
                              <td>{{ $piatto['nome'] ?? 'Piatto' }}</td>
                              <td class="text-end snapshot-value-qty">{{ number_format((int) ($piatto['quantita'] ?? 0), 0, ',', '.') }}</td>
                            </tr>
                          @empty
                            <tr>
                              <td colspan="3" class="text-muted p-4 text-center">Nessun piatto nello snapshot.</td>
                            </tr>
                          @endforelse
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>

                <div class="col-lg-6">
                  <div class="snapshot-table-panel snapshot-table-panel--incasso">
                    <div class="snapshot-table-panel__header">
                      <i class="bx bx-euro text-primary"></i>
                      <span class="fw-semibold">Più redditizi</span>
                      <span class="text-muted small">per incasso</span>
                    </div>
                    <div class="table-responsive">
                      <table class="table table-sm table-hover snapshot-performance-table">
                        <thead>
                          <tr>
                            <th style="width: 3rem;">#</th>
                            <th>Piatto</th>
                            <th class="text-end">Totale</th>
                          </tr>
                        </thead>
                        <tbody>
                          @forelse($piattiPerIncasso as $rank => $piatto)
                            @php $pos = $rank + 1; @endphp
                            <tr>
                              <td>
                                <span @class([
                                  'snapshot-rank',
                                  'snapshot-rank--1' => $pos === 1,
                                  'snapshot-rank--2' => $pos === 2,
                                  'snapshot-rank--3' => $pos === 3,
                                  'snapshot-rank--default' => $pos > 3,
                                ])>{{ $pos }}</span>
                              </td>
                              <td>{{ $piatto['nome'] ?? 'Piatto' }}</td>
                              <td class="text-end snapshot-value-incasso">€ {{ number_format((float) ($piatto['totale'] ?? 0), 2, ',', '.') }}</td>
                            </tr>
                          @empty
                            <tr>
                              <td colspan="3" class="text-muted p-4 text-center">Nessun piatto nello snapshot.</td>
                            </tr>
                          @endforelse
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          @endforeach
        </div>
      @else
        <div class="text-muted">Nessuna cucina nello snapshot.</div>
      @endif
    </div>
  </div>
@else
  <div class="alert alert-warning">
    Nessuno snapshot salvato per questa chiusura. I totali non erano ancora registrati al momento della chiusura.
  </div>
@endif
@endsection

@section('page-script')
@if($cucineRows->isNotEmpty() && ($heatmapHourLabels ?? collect())->isNotEmpty())
<script>
  document.addEventListener('DOMContentLoaded', function () {
    if (typeof ApexCharts === 'undefined') {
      return;
    }

    const hourLabels = @json($heatmapHourLabels->values()->all());
    const cucineOrario = @json($cucineRows->map(fn ($c) => $c['ordini_per_ora'] ?? [])->values()->all());
    const lineCharts = {};

    function isDarkTheme() {
      const theme = document.documentElement.getAttribute('data-bs-theme');
      if (theme === 'dark') return true;
      if (theme === 'light') return false;
      return window.matchMedia('(prefers-color-scheme: dark)').matches;
    }

    function getThemeColors() {
      const css = getComputedStyle(document.documentElement);
      const cfg = window.config?.colors || {};

      return {
        labelColor: cfg.textMuted || (css.getPropertyValue('--bs-secondary-color') || '#6c757d').trim(),
        borderColor: cfg.borderColor || (css.getPropertyValue('--bs-border-color') || '#e9ecef').trim(),
        lineColor: cfg.warning || (css.getPropertyValue('--bs-warning') || '#ffab1d').trim(),
        fontFamily: window.config?.fontFamily || 'inherit'
      };
    }

    function buildLineOptions(data) {
      const dark = isDarkTheme();
      const colors = getThemeColors();

      return {
        chart: {
          type: 'area',
          height: 260,
          parentHeightOffset: 0,
          toolbar: { show: false },
          foreColor: colors.labelColor,
          zoom: { enabled: false },
          dropShadow: {
            enabled: true,
            top: 8,
            left: 0,
            blur: 3,
            color: colors.lineColor,
            opacity: 0.12
          }
        },
        theme: { mode: dark ? 'dark' : 'light' },
        series: [{
          name: 'Ordinazioni',
          data: data
        }],
        colors: [colors.lineColor],
        fill: {
          type: 'gradient',
          gradient: {
            shadeIntensity: 0.35,
            opacityFrom: dark ? 0.35 : 0.45,
            opacityTo: 0.05,
            stops: [0, 90, 100]
          }
        },
        stroke: {
          curve: 'smooth',
          width: 3
        },
        markers: {
          size: 4,
          strokeWidth: 2,
          strokeColors: colors.lineColor,
          hover: { size: 6 }
        },
        dataLabels: { enabled: false },
        legend: { show: false },
        xaxis: {
          categories: hourLabels,
          labels: {
            style: {
              colors: colors.labelColor,
              fontSize: '12px',
              fontFamily: colors.fontFamily
            }
          },
          axisBorder: { show: false },
          axisTicks: { show: false }
        },
        yaxis: {
          min: 0,
          forceNiceScale: true,
          labels: {
            style: {
              colors: colors.labelColor,
              fontSize: '12px',
              fontFamily: colors.fontFamily
            },
            formatter: function (val) { return Math.round(val); }
          }
        },
        grid: {
          borderColor: colors.borderColor,
          strokeDashArray: 6,
          padding: { top: 0, right: 8, bottom: 0, left: 8 }
        },
        tooltip: {
          theme: dark ? 'dark' : 'light',
          x: { formatter: function (_, opts) { return 'Ore ' + (hourLabels[opts.dataPointIndex] || ''); } },
          y: {
            formatter: function (val) {
              return Number(val || 0).toLocaleString('it-IT') + ' ordinazioni';
            }
          }
        }
      };
    }

    function renderLineChart(index) {
      const el = document.getElementById('chart-affluenza-cucina-' + index);
      if (!el || lineCharts[index]) {
        return;
      }

      const data = cucineOrario[index] || [];
      lineCharts[index] = new ApexCharts(el, buildLineOptions(data));
      lineCharts[index].render();
    }

    function renderVisibleLineCharts() {
      document.querySelectorAll('.tab-pane.active [data-cucina-index]').forEach(function (el) {
        renderLineChart(parseInt(el.getAttribute('data-cucina-index'), 10));
      });
    }

    function refreshLineChartsTheme() {
      Object.keys(lineCharts).forEach(function (key) {
        const idx = parseInt(key, 10);
        if (lineCharts[idx]) {
          lineCharts[idx].destroy();
          delete lineCharts[idx];
        }
      });
      renderVisibleLineCharts();
    }

    renderVisibleLineCharts();

    document.querySelectorAll('[data-bs-toggle="tab"][data-bs-target^="#snapshot-cucina-"]').forEach(function (btn) {
      btn.addEventListener('shown.bs.tab', function (e) {
        const target = e.target.getAttribute('data-bs-target');
        const match = target && target.match(/snapshot-cucina-(\d+)/);
        if (match) {
          renderLineChart(parseInt(match[1], 10));
        }
      });
    });

    const themeObserver = new MutationObserver(refreshLineChartsTheme);
    themeObserver.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['data-bs-theme']
    });
  });
</script>
@endif
@endsection
