<?php
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
?>
@php
$configData = Helper::appClasses();
$asporti = $asporti ?? collect();
$asportiConsegnati = $asportiConsegnati ?? collect();
$asportiTimeline = $asportiTimeline ?? collect();
$boardSignature = $boardSignature ?? '';
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Asporto · Ritiro')

@section('vendor-style')
@vite([
'resources/assets/vendor/libs/datatables-bs5/datatables.bootstrap5.scss',
'resources/assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.scss',
'resources/assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.scss',
'resources/assets/vendor/libs/flatpickr/flatpickr.scss',
'resources/assets/vendor/libs/@form-validation/form-validation.scss'
])
@endsection

@section('vendor-script')
@vite([
'resources/assets/vendor/libs/moment/moment.js',
'resources/assets/vendor/libs/flatpickr/flatpickr.js',
'resources/assets/vendor/libs/@form-validation/popular.js',
'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
'resources/assets/vendor/libs/@form-validation/auto-focus.js',
'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js'
])
@endsection

@section('pageTitle')
<div class="d-flex flex-column flex-sm-row align-items-sm-center justify-content-sm-between gap-2">
  <div>
    <h4 class="mb-0 text-sm-small mt-md-4 mt-lg-4">
      <i class="bx bx-walk d-none d-md-inline-flex"></i> Ritiro asporto
    </h4>
  </div>
  <a href="{{ route('asporto.dashboard') }}" class="btn btn-sm btn-label-secondary">
    <i class="bx bx-left-arrow-alt"></i> Dashboard
  </a>
</div>
@endsection

@section('content')
@include('_partials.status')
@include('asporto._partials.postazione-style')

@include('asporto.postazione._boards.ritiro', [
  'asporti' => $asporti,
  'asportiConsegnati' => $asportiConsegnati,
  'asportiTimeline' => $asportiTimeline,
])
@endsection

@section('page-script')
@include('asporto._partials.h_timeline_script')
@include('asporto._partials.board_poll_script')
<script>
window.AsportoPickStation = (function () {
  let abort = null;

  function escapeHtml(str) {
    return String(str ?? '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }

  function notify(type, message) {
    if (typeof Notyf === 'undefined') {
      alert(message);
      return;
    }
    new Notyf({ duration: 3500, position: { x: 'right', y: 'top' } })[type](message);
  }

  function selectedId() {
    const active = document.querySelector('[data-asporto-card].is-active');
    return active ? active.getAttribute('data-asporto-id') : null;
  }

  function replaceBoard(html) {
    const board = document.getElementById('asportoBoard');
    if (!board) return;
    const keepId = selectedId();
    const wrap = document.createElement('div');
    wrap.innerHTML = String(html || '').trim();
    const next = wrap.firstElementChild;
    if (!next) return;
    board.replaceWith(next);
    mount({ selectedId: keepId });
  }

  function mount(opts) {
    opts = opts || {};
    if (abort) abort.abort();
    abort = new AbortController();
    const signal = abort.signal;

    const badge = document.getElementById('badge-pick');
    const badgeDone = document.getElementById('badge-done');
    const lane = document.getElementById('lane-pick');
    const laneDone = document.getElementById('lane-done');
    const detail = document.querySelector('#asportoBoard .asporto-prep-detail');
    const placeholder = document.querySelector('[data-pick-placeholder]');
    if (!lane || !detail) return;

    const cards = function () { return lane.querySelectorAll('[data-asporto-card]'); };
    const panels = function () { return detail.querySelectorAll('[data-pick-panel]'); };

    if (window.AsportoTimeline) {
      window.AsportoTimeline.reset();
      window.AsportoTimeline.init();
    }

    function syncEmptyState() {
      const list = cards();
      if (badge) badge.textContent = String(list.length);

      let empty = lane.querySelector('[data-pick-empty]');
      if (list.length === 0) {
        if (!empty) {
          empty = document.createElement('div');
          empty.className = 'text-muted text-center py-5';
          empty.setAttribute('data-pick-empty', '');
          empty.textContent = 'Nessun ordine in ritiro';
          lane.appendChild(empty);
        }
        if (placeholder) placeholder.hidden = false;
      } else if (empty) {
        empty.remove();
      }
    }

    function prependDoneCard(data) {
      if (!laneDone || !data) return;

      const empty = laneDone.querySelector('[data-done-empty]');
      if (empty) empty.remove();

      const diffMin = data.diff_min;
      let diffLabel = '';
      let diffLevel = '';
      if (typeof diffMin === 'number') {
        if (diffMin > 0) {
          diffLabel = 'Consegnato in ritardo di ' + diffMin + ' min';
          diffLevel = 'late';
        } else if (diffMin < 0) {
          diffLabel = 'Consegnato in anticipo di ' + Math.abs(diffMin) + ' min';
          diffLevel = 'early';
        } else {
          diffLabel = 'Consegnato in orario';
          diffLevel = 'ok';
        }
      }

      const el = document.createElement('div');
      el.className = 'asporto-done-card';
      el.setAttribute('data-done-id', data.id || '');
      if (diffLevel) el.setAttribute('data-diff-level', diffLevel);

      let meta = '';
      if (data.orario) {
        meta += '<span class="asporto-done-card__ora" title="Orario ritiro">' + escapeHtml(data.orario) + '</span>';
      }
      if (data.consegnato_at) {
        meta += '<span class="asporto-done-card__upd" title="Consegnato alle">' + escapeHtml(data.consegnato_at) + '</span>';
      }
      if (diffLabel) {
        meta += '<span class="asporto-done-card__diff">' + escapeHtml(diffLabel) + '</span>';
      }

      el.innerHTML =
        '<div class="asporto-done-card__top">' +
          '<span class="asporto-done-card__code">' + escapeHtml(data.codice || '') + '</span>' +
          '<span class="asporto-done-card__cliente" title="' + escapeHtml(data.cliente || '') + '">' + escapeHtml(data.cliente || '') + '</span>' +
        '</div>' +
        (meta ? '<div class="asporto-done-card__meta">' + meta + '</div>' : '');

      laneDone.prepend(el);

      if (badgeDone) {
        badgeDone.textContent = String(laneDone.querySelectorAll('.asporto-done-card').length);
      }
    }

    function selectAsporto(id) {
      cards().forEach(function (card) {
        card.classList.toggle('is-active', String(card.getAttribute('data-asporto-id')) === String(id));
      });

      panels().forEach(function (panel) {
        const active = String(panel.getAttribute('data-asporto-id')) === String(id);
        panel.classList.toggle('is-visible', active);
        panel.hidden = !active;
        if (active && window.AsportoTimeline) {
          window.AsportoTimeline.applyTiming(panel);
        }
      });

      if (placeholder) placeholder.hidden = true;
    }

    function bindPanel(panel) {
      const btn = panel.querySelector('[data-pick-continua]');
      if (!btn) return;

      btn.addEventListener('click', function () {
        const id = panel.getAttribute('data-asporto-id');
        const codice = panel.getAttribute('data-asporto-codice') || id;
        const url = panel.getAttribute('data-completa-url');
        if (!id || !url || btn.disabled) return;

        btn.disabled = true;
        if (window.AsportoBoardPoll) window.AsportoBoardPoll.pause();

        fetch(url, {
          method: 'POST',
          headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
          },
          body: JSON.stringify({})
        })
          .then(function (res) {
            return res.json().then(function (data) {
              return { ok: res.ok, data: data };
            });
          })
          .then(function (result) {
            if (!result.ok || !result.data?.success) {
              throw new Error(result.data?.message || 'Errore aggiornamento stato');
            }

            const card = lane.querySelector('[data-asporto-card][data-asporto-id="' + id + '"]');
            if (card) card.remove();
            panel.remove();

            prependDoneCard(result.data?.data || { id: id, codice: codice });

            if (window.AsportoTimeline) {
              window.AsportoTimeline.markConsegnato(id);
              window.AsportoTimeline.scrollToFocus(true);
            }

            const remaining = cards();
            if (remaining.length) {
              selectAsporto(remaining[0].getAttribute('data-asporto-id'));
            } else if (placeholder) {
              placeholder.hidden = false;
            }

            notify('success', 'Ordine ' + codice + ' consegnato. Ritira lo scontrino.');
            syncEmptyState();
            if (window.AsportoBoardPoll) {
              window.AsportoBoardPoll.resume();
              window.AsportoBoardPoll.tick();
            }
          })
          .catch(function (err) {
            notify('error', err.message || 'Errore aggiornamento stato');
            btn.disabled = false;
            if (window.AsportoBoardPoll) window.AsportoBoardPoll.resume();
          });
      }, { signal: signal });
    }

    lane.addEventListener('click', function (e) {
      const card = e.target.closest('[data-select-asporto]');
      if (!card) return;
      selectAsporto(card.getAttribute('data-select-asporto'));
    }, { signal: signal });

    panels().forEach(bindPanel);

    const prefer = opts.selectedId;
    const first = cards()[0];
    const pick = prefer && lane.querySelector('[data-asporto-card][data-asporto-id="' + prefer + '"]')
      ? prefer
      : (first ? first.getAttribute('data-asporto-id') : null);

    if (pick) selectAsporto(pick);
    else if (placeholder) placeholder.hidden = false;
  }

  return {
    mount: mount,
    replaceBoard: replaceBoard,
    selectedId: selectedId
  };
})();

document.addEventListener('DOMContentLoaded', function () {
  window.AsportoPickStation.mount();

  if (window.AsportoBoardPoll) {
    window.AsportoBoardPoll.start({
      url: @json(route('asporto.postazione.sync', ['stazione' => 'ritiro'])),
      signature: @json($boardSignature),
      intervalMs: 20000,
      onUpdate: function (html) {
        window.AsportoPickStation.replaceBoard(html);
      }
    });
  }
});
</script>
@endsection
