<?php
use App\Models\Dispositivo;
use Illuminate\Support\Facades\Auth;
?>
@php
$configData = Helper::appClasses();
$dispositiviByTipo = $dispositiviByTipo ?? [];
$tipiDispositivo = $tipiDispositivo ?? Dispositivo::getTipoDispositivo();
$attivitaList = $attivitaList ?? collect();
$totaleDispositivi = collect($dispositiviByTipo)->flatten(1)->count();
$totaleAttivi = collect($dispositiviByTipo)->flatten(1)->where('is_attivo', true)->count();
$puoModificarePv = Auth::user()->can('edit-punto_vendita');
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Mappa Dispositivi')

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1">
    <i class="bx bx-devices"></i> Mappa dispositivi
  </h4>
  <p class="text-muted small mb-0">Panoramica per tipologia · {{ $totaleDispositivi }} dispositivi · {{ $totaleAttivi }} attivi</p>
</div>
@endsection

@section('content')
@include('_partials.status')

<style>
  .md-device-card {
    transition: box-shadow .15s ease, transform .15s ease;
    height: 100%;
  }
  .md-device-card:hover {
    box-shadow: 0 8px 24px rgba(67, 89, 113, .12);
    transform: translateY(-1px);
  }
  .md-device-card.is-hidden-by-filter {
    display: none !important;
  }
  .md-tab-empty {
    border: 1px dashed rgba(67, 89, 113, .25);
    border-radius: .75rem;
    padding: 2.5rem 1rem;
    text-align: center;
    color: var(--bs-secondary-color);
  }
</style>

<div class="card mb-4">
  <div class="card-body">
    <div class="row g-3 align-items-end">
      <div class="col-md-4">
        <label class="form-label small mb-1" for="mdFilterSearch">Cerca</label>
        <input type="text" class="form-control" id="mdFilterSearch" placeholder="Nome, attività, ubicazione...">
      </div>
      <div class="col-md-3">
        <label class="form-label small mb-1" for="mdFilterAttivita">Attività</label>
        <select class="form-select" id="mdFilterAttivita">
          <option value="all">Tutte</option>
          @foreach($attivitaList as $att)
            <option value="{{ $att->id }}">{{ $att->nome }}</option>
          @endforeach
          <option value="0">Senza attività</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label small mb-1" for="mdFilterStato">Stato</label>
        <select class="form-select" id="mdFilterStato">
          <option value="all">Tutti</option>
          <option value="1">Solo attivi</option>
          <option value="0">Solo non attivi</option>
        </select>
      </div>
      <div class="col-md-2">
        <button type="button" class="btn btn-outline-secondary w-100" id="mdFilterReset">
          <i class="bx bx-refresh me-1"></i> Reset
        </button>
      </div>
    </div>
  </div>
</div>

<div class="nav-align-top">
  <ul class="nav nav-tabs nav-fill flex-nowrap overflow-auto" role="tablist">
    @foreach($tipiDispositivo as $tipoKey => $tipoMeta)
      @php
        $countTipo = count($dispositiviByTipo[$tipoKey] ?? []);
      @endphp
      <li class="nav-item" role="presentation">
        <button
          type="button"
          class="nav-link {{ $loop->first ? 'active' : '' }}"
          role="tab"
          data-bs-toggle="tab"
          data-bs-target="#md-tab-{{ $tipoKey }}"
          aria-controls="md-tab-{{ $tipoKey }}"
          aria-selected="{{ $loop->first ? 'true' : 'false' }}"
        >
          <i class="{{ $tipoMeta['icon'] ?? 'bx bx-devices' }} me-1"></i>
          {{ $tipoMeta['label'] }}
          <span class="badge bg-label-primary ms-1 md-tab-count" data-tipo="{{ $tipoKey }}">{{ $countTipo }}</span>
        </button>
      </li>
    @endforeach
    @if(!empty($dispositiviByTipo['_altro']))
      <li class="nav-item" role="presentation">
        <button
          type="button"
          class="nav-link"
          role="tab"
          data-bs-toggle="tab"
          data-bs-target="#md-tab-altro"
          aria-controls="md-tab-altro"
          aria-selected="false"
        >
          <i class="bx bx-question-mark me-1"></i>
          Altro
          <span class="badge bg-label-secondary ms-1 md-tab-count" data-tipo="_altro">{{ count($dispositiviByTipo['_altro']) }}</span>
        </button>
      </li>
    @endif
  </ul>

  <div class="tab-content border border-top-0 rounded-bottom p-3 p-md-4 bg-body">
    @foreach($tipiDispositivo as $tipoKey => $tipoMeta)
      @php $devices = $dispositiviByTipo[$tipoKey] ?? []; @endphp
      <div
        class="tab-pane fade {{ $loop->first ? 'show active' : '' }}"
        id="md-tab-{{ $tipoKey }}"
        role="tabpanel"
      >
        @if(count($devices))
          <div class="row g-3 md-device-grid" data-tipo-pane="{{ $tipoKey }}">
            @foreach($devices as $device)
              @include('mappa_dispositivi._partials.device_card', [
                'device' => $device,
                'tipoMeta' => $tipoMeta,
                'puoModificarePv' => $puoModificarePv,
              ])
            @endforeach
          </div>
          <div class="md-tab-empty d-none" data-empty-for="{{ $tipoKey }}">
            <i class="bx bx-filter-alt fs-2 d-block mb-2"></i>
            Nessun dispositivo corrisponde ai filtri.
          </div>
        @else
          <div class="md-tab-empty">
            <i class="{{ $tipoMeta['icon'] ?? 'bx bx-devices' }} fs-2 d-block mb-2"></i>
            Nessun dispositivo di tipo {{ strtolower($tipoMeta['label']) }}.
          </div>
        @endif
      </div>
    @endforeach

    @if(!empty($dispositiviByTipo['_altro']))
      <div class="tab-pane fade" id="md-tab-altro" role="tabpanel">
        <div class="row g-3 md-device-grid" data-tipo-pane="_altro">
          @foreach($dispositiviByTipo['_altro'] as $device)
            @include('mappa_dispositivi._partials.device_card', [
              'device' => $device,
              'tipoMeta' => ['label' => $device['tipo'] ?? 'Sconosciuto', 'icon' => 'bx bx-devices'],
              'puoModificarePv' => $puoModificarePv,
            ])
          @endforeach
        </div>
        <div class="md-tab-empty d-none" data-empty-for="_altro">
          <i class="bx bx-filter-alt fs-2 d-block mb-2"></i>
          Nessun dispositivo corrisponde ai filtri.
        </div>
      </div>
    @endif
  </div>
</div>
@endsection

@section('page-script')
<script type="module">
  const cards = Array.from(document.querySelectorAll('.md-device-card'));
  const elSearch = document.getElementById('mdFilterSearch');
  const elAttivita = document.getElementById('mdFilterAttivita');
  const elStato = document.getElementById('mdFilterStato');
  const btnReset = document.getElementById('mdFilterReset');
  let searchTimer;

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

  function cardMatches(card) {
    const q = normalize(elSearch.value);
    const attivita = elAttivita.value;
    const stato = elStato.value;

    if (attivita !== 'all' && card.dataset.attivitaId !== attivita) {
      return false;
    }
    if (stato !== 'all' && card.dataset.attivo !== stato) {
      return false;
    }
    if (q.length && !normalize(card.dataset.search).includes(q)) {
      return false;
    }
    return true;
  }

  function updateTabCounts() {
    document.querySelectorAll('.md-tab-count').forEach(function(badge) {
      const tipo = badge.dataset.tipo;
      const visible = cards.filter(function(card) {
        return card.dataset.tipo === tipo && !card.classList.contains('is-hidden-by-filter');
      }).length;
      badge.textContent = String(visible);
    });
  }

  function updateEmptyStates() {
    document.querySelectorAll('[data-tipo-pane]').forEach(function(grid) {
      const tipo = grid.dataset.tipoPane;
      const visible = grid.querySelectorAll('.md-device-card:not(.is-hidden-by-filter)').length;
      const emptyEl = document.querySelector('[data-empty-for="' + tipo + '"]');
      if (emptyEl) {
        emptyEl.classList.toggle('d-none', visible > 0);
      }
      grid.classList.toggle('d-none', visible === 0 && grid.children.length > 0);
    });
  }

  function applyFilters() {
    cards.forEach(function(card) {
      card.classList.toggle('is-hidden-by-filter', !cardMatches(card));
    });
    updateTabCounts();
    updateEmptyStates();
  }

  elAttivita.addEventListener('change', applyFilters);
  elStato.addEventListener('change', applyFilters);
  elSearch.addEventListener('input', function() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(applyFilters, 150);
  });
  btnReset.addEventListener('click', function() {
    elSearch.value = '';
    elAttivita.value = 'all';
    elStato.value = 'all';
    applyFilters();
  });
</script>
@endsection
