@extends('layouts.blankLayout')

@section('title', 'Monitor Chiamate Cucina')

@section('content')
  <style>
    :root {
      --bg: #0f172a;
      --panel: #111827;
      --panel-soft: #1f2937;
      --text: #f9fafb;
      --muted: #cbd5e1;
      --accent: #22d3ee;
      --accent-2: #38bdf8;
      --warning: #f59e0b;
      --ok: #10b981;
      --border: #334155;
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      background: radial-gradient(circle at top, #1e293b 0%, var(--bg) 45%);
      color: var(--text);
      font-family: "Segoe UI", Roboto, Arial, sans-serif;
      min-height: 100vh;
    }

    .screen {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      gap: 16px;
      padding: 20px;
    }

    .header {
      border: 1px solid var(--border);
      background: linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(30, 41, 59, 0.95));
      border-radius: 16px;
      padding: 16px 20px;
      display: grid;
      grid-template-columns: auto 1fr;
      align-items: center;
      gap: 16px;
      box-shadow: inset 0 0 0 1px rgba(148, 163, 184, 0.15);
    }

    .brand-left {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 120px;
      max-width: 220px;
      min-height: 70px;
      border: 1px solid rgba(56, 189, 248, 0.35);
      border-radius: 12px;
      background: rgba(15, 23, 42, 0.7);
      padding: 8px 12px;
      text-align: center;
      overflow: hidden;
    }

    .brand-left img {
      max-width: 100%;
      max-height: 54px;
      object-fit: contain;
      display: block;
    }

    .brand-left .brand-name {
      font-size: clamp(12px, 1.2vw, 18px);
      color: #e2e8f0;
      font-weight: 700;
      line-height: 1.2;
      word-break: break-word;
    }

    .header-center {
      text-align: center;
    }

    .title {
      margin: 0;
      font-size: clamp(40px, 6vw, 92px);
      line-height: 1.1;
      letter-spacing: 1px;
      text-transform: uppercase;
      color: #f8fafc;
      text-shadow: 0 2px 10px rgba(0, 0, 0, 0.45);
    }

    .subtitle {
      margin-top: 8px;
      color: #cbd5e1;
      font-size: clamp(14px, 1.4vw, 20px);
      font-weight: 600;
      letter-spacing: 0.4px;
    }

    .subtitle strong {
      color: #facc15;
      text-shadow: 0 1px 8px rgba(0, 0, 0, 0.35);
    }

    .content {
      border: 1px solid var(--border);
      border-radius: 16px;
      padding: 16px;
      background: rgba(17, 24, 39, 0.88);
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 14px;
      min-height: 420px;
    }

    .status-line {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12px;
      color: var(--muted);
      font-size: clamp(12px, 1vw, 16px);
    }

    .badge {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: rgba(56, 189, 248, 0.18);
      color: #e0f2fe;
      border: 1px solid rgba(56, 189, 248, 0.4);
      border-radius: 999px;
      padding: 4px 12px;
      font-weight: 700;
    }

    .orders-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 14px;
      width: 100%;
    }

    .order-card {
      border: 1px solid rgba(16, 185, 129, 0.45);
      border-radius: 14px;
      background: linear-gradient(180deg, rgba(16, 185, 129, 0.18), rgba(17, 24, 39, 0.8));
      min-height: 132px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 8px;
      text-align: center;
      padding: 10px;
      box-shadow: 0 8px 18px rgba(0, 0, 0, 0.22);
      transition: transform 0.15s ease, box-shadow 0.15s ease;
    }

    .order-card:hover {
      transform: translateY(-1px);
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.28);
    }

    .order-card.recent-blink {
      animation: recentBlink 0.65s ease-in-out 10;
      border-color: rgba(250, 204, 21, 0.95);
      box-shadow: 0 0 0 2px rgba(250, 204, 21, 0.22), 0 10px 22px rgba(0, 0, 0, 0.32);
    }

    @keyframes recentBlink {
      0%, 100% {
        filter: brightness(1);
        transform: scale(1);
      }
      50% {
        filter: brightness(1.35);
        transform: scale(1.03);
      }
    }

    .order-number {
      font-size: clamp(42px, 5vw, 74px);
      line-height: 1;
      font-weight: 800;
      letter-spacing: 1px;
      color: #f0fdf4;
    }

    .order-label {
      font-size: clamp(12px, 1.1vw, 16px);
      color: #dcfce7;
      letter-spacing: 0.4px;
      text-transform: uppercase;
    }

    .empty {
      /* border: 1px dashed rgba(148, 163, 184, 0.45); */
      border-radius: 14px;
      min-height: 180px;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      padding: 20px;
      color: var(--muted);
      font-size: clamp(18px, 2vw, 28px);
    }

    .error {
      border: 1px solid rgba(245, 158, 11, 0.45);
      border-radius: 10px;
      background: rgba(245, 158, 11, 0.12);
      color: #fde68a;
      padding: 10px 12px;
      font-size: clamp(12px, 1vw, 15px);
      display: none;
    }

    .corner-badges {
      position: fixed;
      right: 18px;
      bottom: 18px;
      display: flex;
      flex-direction: row;
      gap: 8px;
      z-index: 20;
    }

    .corner-badge {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      border-radius: 999px;
      padding: 5px 10px;
      border: 1px solid rgba(56, 189, 248, 0.4);
      background: rgba(15, 23, 42, 0.92);
      color: #e2e8f0;
      font-size: clamp(10px, 0.85vw, 13px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
      white-space: nowrap;
    }

    .corner-badge strong {
      color: #f8fafc;
      font-weight: 700;
    }
  </style>

  @php
    $cucinaNome = $monitor_has_contenuto->cucina?->nome ?? ('Cucina #'.$monitor_has_contenuto->cucina_id);
    $attivita = $monitor->attivita;
    $attivitaNome = $attivita?->nome ?? 'Attività';
    $attivitaLogoPath = $attivita?->path_logo;
    $attivitaLogoSrc = null;
    if ($attivitaLogoPath) {
      $attivitaLogoSrc = str_starts_with($attivitaLogoPath, 'http') ? $attivitaLogoPath : asset($attivitaLogoPath);
    }
  @endphp

  <div class="screen">
    <header class="header">
      <div class="brand-left">
        @if($attivitaLogoSrc)
          <img src="{{ $attivitaLogoSrc }}" alt="Logo attività" onerror="this.remove(); this.parentElement.innerHTML='<span class=&quot;brand-name&quot;>{{ addslashes($attivitaNome) }}</span>';">
        @else
          <span class="brand-name">{{ $attivitaNome }}</span>
        @endif
      </div>
      <div class="header-center">
        <h1 class="title">{{ $cucinaNome }}</h1>
        <div class="subtitle">Ordini chiamati</div>
      </div>
    </header>

    <section class="content">
      <div class="status-line">
        <div>
          Numeri attualmente chiamati:
          <span class="badge" id="orders-count">0</span>
        </div>
      </div>

      <div class="error" id="error-box"></div>

      <div class="orders-grid" id="orders-grid" aria-live="polite"></div>
      <div class="empty" id="empty-state" style="display: none;"></div>
    </section>
  </div>

  <div class="corner-badges">
    <div class="corner-badge">Monitor: <strong>{{ $monitor->nome ?? ('#'.$monitor->id) }}</strong></div>
    <div class="corner-badge">Aggiornamento: <strong id="last-update">--:--:--</strong></div>
  </div>
@endsection

@section('page-script')
  <script>
    (function () {
      const dispositivoId = @json($monitor->id);
      const attivitaId = @json($monitor->attivita_id);
      const range = '1h';
      const refreshMs = 5000;

      const ordersGrid = document.getElementById('orders-grid');
      const emptyState = document.getElementById('empty-state');
      const countBadge = document.getElementById('orders-count');
      const lastUpdate = document.getElementById('last-update');
      const errorBox = document.getElementById('error-box');
      let previousTopOrderId = null;
      let blinkingOrderId = null;
      let blinkTimer = null;

      function setLastUpdate() {
        lastUpdate.textContent = new Date().toLocaleTimeString('it-IT');
      }

      function showError(message) {
        errorBox.style.display = 'block';
        errorBox.textContent = message;
      }

      function clearError() {
        errorBox.style.display = 'none';
        errorBox.textContent = '';
      }

      function render(rows) {
        const uniqueOrderIds = [];
        rows.forEach((row) => {
          if (!uniqueOrderIds.includes(row.ordine_id)) {
            uniqueOrderIds.push(row.ordine_id);
          }
        });

        countBadge.textContent = String(uniqueOrderIds.length);
        ordersGrid.innerHTML = '';

        const currentTopOrderId = uniqueOrderIds.length > 0 ? uniqueOrderIds[0] : null;
        if (currentTopOrderId !== null && currentTopOrderId !== previousTopOrderId) {
          blinkingOrderId = currentTopOrderId;
          if (blinkTimer) {
            clearTimeout(blinkTimer);
          }
          blinkTimer = setTimeout(() => {
            blinkingOrderId = null;
          }, 7000);
        }
        previousTopOrderId = currentTopOrderId;

        if (uniqueOrderIds.length === 0) {
          emptyState.style.display = 'flex';
          return;
        }

        emptyState.style.display = 'none';

        uniqueOrderIds.forEach((ordineId) => {
          const card = document.createElement('div');
          card.className = 'order-card' + (ordineId === blinkingOrderId ? ' recent-blink' : '');
          card.innerHTML = `
            <div class="order-number">#${ordineId}</div>
            <div class="order-label">Ordine chiamato</div>
          `;
          ordersGrid.appendChild(card);
        });
      }

      function poll() {
        const params = new URLSearchParams({
          dispositivo_id: String(dispositivoId),
          attivita_id: String(attivitaId),
          range: range,
        });

        fetch("{{ route('riga-ordine.lista-chiamate') }}?" + params.toString(), {
          method: "GET",
          headers: { "Accept": "application/json" },
        })
          .then((response) => response.json().then((json) => ({ ok: response.ok, json })))
          .then(({ ok, json }) => {
            if (!ok || !json.success) {
              throw new Error(json.message || 'Impossibile caricare i numeri chiamati');
            }
            clearError();
            render(Array.isArray(json.data) ? json.data : []);
          })
          .catch((error) => {
            showError(error.message || 'Errore chiamata monitor');
          })
          .finally(() => {
            setLastUpdate();
            setTimeout(poll, refreshMs);
          });
      }

      poll();
    })();


    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