@extends('layouts.blankLayout')

@section('title', 'Monitor Bacheca')

@section('content')
  @php
    $resolveContenutoImageUrl = function ($path) {
      if (empty($path)) {
        return null;
      }

      if (
        str_starts_with($path, 'http://') ||
        str_starts_with($path, 'https://') ||
        str_starts_with($path, '//')
      ) {
        return $path;
      }

      if (str_starts_with($path, '/')) {
        return $path;
      }

      try {
        return \Illuminate\Support\Facades\Storage::disk('contenuti_bacheca')->url(ltrim($path, '/'));
      } catch (\Throwable $e) {
        return asset(ltrim($path, '/'));
      }
    };

    $bacheca = $monitor_has_contenuto->bacheca;
    $bachecaNome = $bacheca?->nome ?? 'Bacheca non configurata';
    $contenuti = collect($bacheca?->contenuti ?? [])->map(function ($contenuto) use ($resolveContenutoImageUrl) {
      $immaginePath = $contenuto->immagine;
      $immagineSrc = $resolveContenutoImageUrl($immaginePath);

      return [
        'id' => $contenuto->id,
        'nome' => $contenuto->nome ?? ('Contenuto #'.$contenuto->id),
        'descrizione' => $contenuto->descrizione ?? '',
        'immagine' => $immagineSrc,
      ];
    })->values();
  @endphp

  <style>
    :root {
      --bg: #0f172a;
      --text: #f8fafc;
      --muted: #cbd5e1;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      background: var(--bg);
      color: var(--text);
      font-family: "Segoe UI", Roboto, Arial, sans-serif;
    }
    .screen {
      min-height: 100vh;
    }
    .content {
      position: relative;
      background: rgba(17, 24, 39, 0.9);
      width: 100vw;
      height: 100vh;
      overflow: hidden;
    }
    .slider-viewport {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    .slider-track {
      display: flex;
      width: 100%;
      height: 100%;
      transition: transform 0.65s ease-in-out;
    }
    .slide {
      min-width: 100%;
      height: 100%;
      display: block;
      background: rgba(17, 24, 39, 1);
    }
    .slide-image-wrap {
      width: 100%;
      height: 100%;
      background: rgba(15, 23, 42, 0.65);
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      position: relative;
    }
    .slide-image-wrap::after {
      content: '';
      position: absolute;
      inset: 0;
      pointer-events: none;
      background: linear-gradient(180deg, rgba(15, 23, 42, 0.06) 0%, rgba(15, 23, 42, 0.18) 100%);
    }
    .slide-image-wrap img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
      transform: scale(1);
    }
    .slide-image-placeholder {
      color: var(--muted);
      font-size: clamp(16px, 1.6vw, 24px);
      text-align: center;
      padding: 24px;
    }
    .slide.is-active .slide-image-wrap img {
      animation: kenBurnsSoft 7s linear forwards;
    }
    @keyframes kenBurnsSoft {
      0% { transform: scale(1.02) translateX(0) translateY(0); }
      100% { transform: scale(1.09) translateX(-1.4%) translateY(-1.1%); }
    }
    .content-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--muted);
      font-size: clamp(16px, 1.8vw, 28px);
      text-align: center;
      padding: 20px;
    }
    .slider-progress {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 4px;
      background: rgba(148, 163, 184, 0.2);
      z-index: 5;
    }
    .slider-progress-fill {
      height: 100%;
      width: 0;
      background: linear-gradient(90deg, #22d3ee, #38bdf8);
      box-shadow: 0 0 10px rgba(56, 189, 248, 0.45);
    }
  </style>

  <div class="screen">
    <section class="content">
      @if($contenuti->count() > 0)
      <div class="slider-viewport">
        <div class="slider-track" id="slider-track">
          @foreach($contenuti as $contenuto)
          <article class="slide">
            <div class="slide-image-wrap">
              @if(!empty($contenuto['immagine']))
              <img src="{{ $contenuto['immagine'] }}" alt="{{ $contenuto['nome'] }}" />
              @else
              <div class="slide-image-placeholder">Nessuna immagine disponibile</div>
              @endif
            </div>
          </article>
          @endforeach
          @if($contenuti->count() > 1)
          @php $firstContenuto = $contenuti->first(); @endphp
          <article class="slide" aria-hidden="true">
            <div class="slide-image-wrap">
              @if(!empty($firstContenuto['immagine']))
              <img src="{{ $firstContenuto['immagine'] }}" alt="{{ $firstContenuto['nome'] }}" />
              @else
              <div class="slide-image-placeholder">Nessuna immagine disponibile</div>
              @endif
            </div>
          </article>
          @endif
        </div>
      </div>
      @if($contenuti->count() > 1)
      <div class="slider-progress" aria-hidden="true">
        <div class="slider-progress-fill" id="slider-progress-fill"></div>
      </div>
      @endif
      @else
      <div class="content-placeholder">
        Nessun contenuto assegnato a questa bacheca.
      </div>
      @endif
    </section>
  </div>
@endsection

@section('page-script')
  <script>
    (function () {
      const contenuti = @json($contenuti);

      if (!Array.isArray(contenuti) || contenuti.length === 0) {
        return;
      }

      const sliderTrack = document.getElementById('slider-track');
      const progressFill = document.getElementById('slider-progress-fill');
      if (!sliderTrack) {
        return;
      }
      let currentIndex = 0;
      const rotationMs = 7000;
      const realSlides = contenuti.length;
      const slides = Array.from(sliderTrack.querySelectorAll('.slide'));

      function setActiveSlide(index) {
        slides.forEach(function (slide, i) {
          if (i === index) {
            slide.classList.add('is-active');
          } else {
            slide.classList.remove('is-active');
          }
        });
      }

      function restartProgress() {
        if (!progressFill) return;
        progressFill.style.transition = 'none';
        progressFill.style.width = '0%';
        progressFill.getBoundingClientRect();
        progressFill.style.transition = 'width ' + rotationMs + 'ms linear';
        progressFill.style.width = '100%';
      }

      function setTrackPosition(withAnimation) {
        sliderTrack.style.transition = withAnimation ? 'transform 0.65s ease-in-out' : 'none';
        sliderTrack.style.transform = 'translateX(-' + (currentIndex * 100) + '%)';
      }

      function nextSlide() {
        currentIndex += 1;
        setTrackPosition(true);
        setActiveSlide(currentIndex);
        restartProgress();
      }

      setTrackPosition(false);
      setActiveSlide(0);
      restartProgress();
      if (realSlides > 1) {
        setInterval(function () {
          nextSlide();
        }, rotationMs);

        sliderTrack.addEventListener('transitionend', function () {
          // When we reach the cloned first slide, jump to real first slide without animation.
          if (currentIndex >= realSlides) {
            currentIndex = 0;
            setTrackPosition(false);
            setActiveSlide(0);
          }
        });
      }
    })();


    function checkReload() {
      $.ajax({
        url: "{{ route('consulta.monitor.check-reload', ['monitor_id' => $monitor->id]) }}",
        type: 'GET',
        data: {
          last_updated_at: "{{ $monitor_has_contenuto->updated_at->format('Y-m-d H:i:s') }}",
          monitor_id: "{{ $monitor->id }}",
        },
        success: function(response) {
          if(response.reload) {
            window.location.reload();
          }
        },
        error: function(xhr) {
          console.log(xhr.responseText);
        }
      });
    }

    setInterval(checkReload, 15000); 

  </script>
@endsection
