@php
  $attivitaCorrente = $attivitaCorrente ?? null;
  $dispositiviAttivitaCorrente = $dispositiviAttivitaCorrente ?? ['by_tipo' => [], 'totale' => 0, 'totale_attivi' => 0];
  $tipiDispositivo = $tipiDispositivo ?? collect();
  $byTipo = $dispositiviAttivitaCorrente['by_tipo'] ?? [];
  $totaleAttivita = (int) ($dispositiviAttivitaCorrente['totale'] ?? 0);
  $totaleAttiviAttivita = (int) ($dispositiviAttivitaCorrente['totale_attivi'] ?? 0);
  $puoModificarePv = $puoModificarePv ?? false;
@endphp

@if(!$attivitaCorrente)
  <div class="md-tab-empty">
    <i class="bx bx-building-house fs-2 d-block mb-2"></i>
    <p class="mb-1 fw-semibold">Nessuna attività selezionata</p>
    <p class="small mb-0">Seleziona un'attività dal menu in alto per vedere i suoi dispositivi.</p>
  </div>
@else
  <div class="card mb-3">
    <div class="card-body">
      <div class="row g-3 align-items-end">
        <div class="col-md-8">
          <label class="form-label small mb-1" for="mdSimpleSearch">Cerca dispositivo</label>
          <input
            type="search"
            class="form-control"
            id="mdSimpleSearch"
            placeholder="Nome, ubicazione, tipo..."
            autocomplete="off">
        </div>
        <div class="col-md-4">
          <label class="form-label small mb-1" for="mdSimpleStato">Stato</label>
          <select class="form-select" id="mdSimpleStato">
            <option value="all">Tutti</option>
            <option value="1">Solo attivi</option>
            <option value="0">Solo non attivi</option>
          </select>
        </div>
      </div>
      <div class="mt-3 d-flex flex-wrap gap-2">
        <span class="badge bg-label-primary">{{ $attivitaCorrente->nome }}</span>
        <span class="badge bg-label-secondary">{{ $totaleAttivita }} dispositivi</span>
        <span class="badge bg-label-success">{{ $totaleAttiviAttivita }} attivi</span>
      </div>
    </div>
  </div>

  @php
    $hasDevices = $totaleAttivita > 0;
  @endphp

  @if(!$hasDevices)
    <div class="md-tab-empty" id="mdSimpleEmpty">
      <i class="bx bx-devices fs-2 d-block mb-2"></i>
      Nessun dispositivo configurato per questa attività.
    </div>
  @else
    <div id="mdSimpleSections">
      @foreach($tipiDispositivo as $tipoKey => $tipoMeta)
        @php
          $devices = $byTipo[$tipoKey] ?? [];
        @endphp
        @if(count($devices) > 0)
          <section
            class="mb-4 md-pane-section"
            data-md-simple-section
            data-tipo="{{ $tipoKey }}">
            <div class="d-flex align-items-center gap-2 mb-3">
              <span class="avatar avatar-sm">
                <span class="avatar-initial rounded bg-label-primary">
                  <i class="{{ $tipoMeta['icon'] ?? 'bx bx-devices' }}"></i>
                </span>
              </span>
              <h6 class="mb-0">{{ $tipoMeta['label'] ?? $tipoKey }}</h6>
              <span class="badge bg-label-secondary">{{ count($devices) }}</span>
            </div>
            <div class="row g-3">
              @foreach($devices as $device)
                @include('mappa_dispositivi._partials.device_card', [
                  'device' => $device,
                  'tipoMeta' => $tipoMeta,
                  'puoModificarePv' => $puoModificarePv,
                ])
              @endforeach
            </div>
          </section>
        @endif
      @endforeach

      @php
        $altri = $byTipo['_altro'] ?? [];
      @endphp
      @if(count($altri) > 0)
        <section class="mb-4 md-pane-section" data-md-simple-section data-tipo="_altro">
          <div class="d-flex align-items-center gap-2 mb-3">
            <span class="avatar avatar-sm">
              <span class="avatar-initial rounded bg-label-secondary">
                <i class="bx bx-chip"></i>
              </span>
            </span>
            <h6 class="mb-0">Altri</h6>
            <span class="badge bg-label-secondary">{{ count($altri) }}</span>
          </div>
          <div class="row g-3">
            @foreach($altri as $device)
              @include('mappa_dispositivi._partials.device_card', [
                'device' => $device,
                'tipoMeta' => ['label' => 'Altro', 'icon' => 'bx bx-chip'],
                'puoModificarePv' => $puoModificarePv,
              ])
            @endforeach
          </div>
        </section>
      @endif
    </div>

    <div class="md-tab-empty d-none" id="mdSimpleFilteredEmpty">
      <i class="bx bx-filter-alt fs-2 d-block mb-2"></i>
      Nessun dispositivo corrisponde ai filtri.
    </div>
  @endif
@endif

<script type="module">
  (function () {
    const searchEl = document.getElementById('mdSimpleSearch');
    const statoEl = document.getElementById('mdSimpleStato');
    const cards = Array.from(document.querySelectorAll('#mdPaneSimple .md-device-card'));
    const sections = Array.from(document.querySelectorAll('[data-md-simple-section]'));
    const filteredEmpty = document.getElementById('mdSimpleFilteredEmpty');

    if (!cards.length) return;

    function normalize(value) {
      return (value ?? '').toString().trim().toLowerCase();
    }

    function applySimpleFilters() {
      const query = normalize(searchEl?.value);
      const stato = statoEl?.value ?? 'all';
      let visibleCards = 0;

      cards.forEach((card) => {
        const attivo = card.dataset.attivo ?? '';
        const searchBlob = normalize(card.dataset.search);
        const matchStato = stato === 'all' || attivo === stato;
        const matchSearch = query === '' || searchBlob.includes(query);
        const visible = matchStato && matchSearch;
        card.classList.toggle('is-hidden-by-filter', !visible);
        if (visible) visibleCards += 1;
      });

      sections.forEach((section) => {
        const sectionCards = section.querySelectorAll('.md-device-card');
        const hasVisible = Array.from(sectionCards).some((card) => !card.classList.contains('is-hidden-by-filter'));
        section.classList.toggle('is-hidden-by-filter', !hasVisible);
      });

      if (filteredEmpty) {
        filteredEmpty.classList.toggle('d-none', visibleCards > 0);
      }
    }

    searchEl?.addEventListener('input', applySimpleFilters);
    statoEl?.addEventListener('change', applySimpleFilters);
  })();
</script>
