<?php
use App\Models\Role;
use App\Models\Cucina;
use App\Models\Piatto;
use App\Models\SaltacodaOrdine;
use Illuminate\Support\Facades\Auth;
?>
@php
$configData = Helper::appClasses();
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Saltacoda')

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-0 text-sm-small mt-md-4 mt-lg-4">
    <i class="bx bxs-user-badge d-none d-md-inline-flex d-lg-inline-flex"></i>
    Saltacoda
    <span class="text-muted text-primary fs-6 fw-normal d-none d-md-inline-flex d-lg-inline-flex"> di {{ $attivita->nome }}</span>
  </h4>
  <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block d-lg-block">
    <ol class="breadcrumb breadcrumb-custom-icon">
      <li class="breadcrumb-item">
        <a href="{{ route('dispositivo.index') }}">Dispositivi</a>
        <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
      </li>
      <li class="breadcrumb-item active text-primary">
        <a href="{{ route('saltacoda.index') }}">Saltacoda</a>
      </li>
    </ol>
  </nav>
</div>
@endsection

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

@if(isset($saltacoda))
@php
  $clienteUrl = route('cliente.saltacoda.show', ['attivita_id' => $attivita->id]);
  $stats = [
    'pre_ordini_in_coda' => SaltacodaOrdine::query()
      ->where('attivita_id', $attivita->id)
      ->where('stato', SaltacodaOrdine::PRE_ORDINE)
      ->count(),
    'cucine_attive' => Cucina::query()
      ->where('attivita_id', $attivita->id)
      ->where('is_attiva', true)
      ->count(),
    'piatti_attivi' => Piatto::query()
      ->where('attivita_id', $attivita->id)
      ->where('is_attivo', true)
      ->count(),
  ];

  $istruzioniData = \App\Models\Saltacoda::normalizeIstruzioni(
    old('istruzioni') !== null ? old('istruzioni') : $saltacoda->istruzioni
  );
@endphp
<div class="nav-align-top">
  <ul class="nav nav-tabs nav-fill" role="tablist">
    <li class="nav-item" role="presentation">
      <button
        type="button"
        class="nav-link active"
        role="tab"
        data-bs-toggle="tab"
        data-bs-target="#sc-tab-riepilogo"
        aria-controls="sc-tab-riepilogo"
        aria-selected="true"
      >
        <i class="bx bx-list-ul me-1"></i>Riepilogo
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button
        type="button"
        class="nav-link"
        role="tab"
        data-bs-toggle="tab"
        data-bs-target="#sc-tab-generali"
        aria-controls="sc-tab-generali"
        aria-selected="false"
      >
        <i class="bx bx-cog me-1"></i>Generali
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button
        type="button"
        class="nav-link"
        role="tab"
        data-bs-toggle="tab"
        data-bs-target="#sc-tab-campi"
        aria-controls="sc-tab-campi"
        aria-selected="false"
      >
        <i class="bx bx-notepad me-1"></i>Campi cliente
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button
        type="button"
        class="nav-link"
        role="tab"
        data-bs-toggle="tab"
        data-bs-target="#sc-tab-istruzioni"
        aria-controls="sc-tab-istruzioni"
        aria-selected="false"
      >
        <i class="bx bx-message-square-detail me-1"></i>Istruzioni
      </button>
    </li>
  </ul>

  <form
    id="saltacodaConfigForm"
    action="{{ route('saltacoda.store', ['attivita' => $attivita->id]) }}"
    method="POST"
  >
    @csrf
    <input type="hidden" name="attivita_id" value="{{ $attivita->id }}">

    <div class="tab-content">
      <div class="tab-pane fade show active" id="sc-tab-riepilogo" role="tabpanel">
        @include('saltacoda._partials.tab-riepilogo')
      </div>

      <div class="tab-pane fade" id="sc-tab-generali" role="tabpanel">
        @include('saltacoda._partials.tab-generali')
      </div>

      <div class="tab-pane fade" id="sc-tab-campi" role="tabpanel">
        @include('saltacoda._partials.tab-campi-cliente')
      </div>

      <div class="tab-pane fade" id="sc-tab-istruzioni" role="tabpanel">
        @include('saltacoda._partials.tab-istruzioni')
      </div>
    </div>

    <div class="d-flex justify-content-end gap-2 mt-3 px-1">
      <button type="submit" class="btn btn-primary">
        <i class="bx bx-save me-1"></i> Salva impostazioni
      </button>
    </div>
  </form>
</div>
@else
<div class="row justify-content-center">
  <div class="col-xxl mb-4 mt-2">
    <div class="card">
      <div class="card-body text-center py-5">
        <div class="avatar avatar-lg mx-auto mb-3">
          <span class="avatar-initial rounded-circle bg-label-warning">
            <i class="bx bxs-user-badge bx-lg"></i>
          </span>
        </div>
        <h4 class="mb-1">Saltacoda non ancora configurato</h4>
        <p class="text-muted mb-4">Abilita il servizio per permettere ai clienti di inviare pre-ordini dall'app.</p>
        <a href="{{ route('saltacoda.attiva', ['attivita_id' => $attivita->id]) }}" class="btn btn-primary">
          <i class="bx bx-play me-1"></i> Abilita Saltacoda
        </a>
      </div>
    </div>
  </div>
</div>
@endif

@endsection

@section('page-script')
@if(isset($saltacoda))
<script>
  document.addEventListener('DOMContentLoaded', function () {
    const allowedFieldTypes = ['text', 'boolean', 'time'];

    function slugifyKey(label) {
      let key = (label || '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .replace(/\s+/g, '_')
        .replace(/[^a-z0-9_]/g, '')
        .replace(/_+/g, '_')
        .replace(/^_+|_+$/g, '');

      if (!key) {
        key = 'campo';
      }

      if (/^\d/.test(key)) {
        key = `campo_${key}`;
      }

      return key;
    }

    function getUniqueKey(baseKey, usedKeys) {
      if (!usedKeys.has(baseKey)) {
        usedKeys.add(baseKey);
        return baseKey;
      }

      let suffix = 2;
      let candidate = `${baseKey}_${suffix}`;
      while (usedKeys.has(candidate)) {
        suffix += 1;
        candidate = `${baseKey}_${suffix}`;
      }
      usedKeys.add(candidate);
      return candidate;
    }

    // --- Campi cliente (info) ---
    const fieldTypeMeta = {
      text: { label: 'Testo', icon: 'bx-text' },
      boolean: { label: 'Si / No', icon: 'bx-check-square' },
      time: { label: 'Orario', icon: 'bx-time' },
    };

    let info = {};
    @if(old('info', $saltacoda->info ?? false))
      try {
        info = JSON.parse(@json(old('info', $saltacoda->info ?? '')));
      } catch (e) {
        info = {};
      }
    @endif

    const infoContainer = document.getElementById('user-friendly-info-fields');
    const infoInput = document.getElementById('info');
    const addCampoBtn = document.getElementById('sc-add-campo-btn');
    const newCampoLabelEl = document.getElementById('sc-new-campo-label');
    const newCampoTypeEl = document.getElementById('sc-new-campo-type');
    const newCampoKeyPreviewEl = document.getElementById('sc-new-campo-key-preview');
    const campiCountEl = document.getElementById('sc-campi-count');
    const campiPreviewEl = document.getElementById('sc-campi-preview-fields');
    const campiRoot = document.querySelector('.sc-campi-wrap');

    function updateNewCampoKeyPreview() {
      const label = (newCampoLabelEl.value || '').trim();
      if (!label) {
        newCampoKeyPreviewEl.textContent = '—';
        return;
      }
      const usedKeys = new Set(Object.keys(readInfoFromDom()));
      newCampoKeyPreviewEl.textContent = getUniqueKey(slugifyKey(label), usedKeys);
    }

    function readInfoFromDom() {
      const newInfo = {};
      const usedKeys = new Set();

      infoContainer.querySelectorAll('[data-row-id]').forEach((rowEl) => {
        const labelInputEl = rowEl.querySelector('input[data-label-idx]');
        const keyPreviewEl = rowEl.querySelector('[data-key-preview]');
        const typeSelectEl = rowEl.querySelector('select[data-type-idx]');
        const requiredInputEl = rowEl.querySelector('input[data-required-idx]');
        const label = (labelInputEl.value || '').trim();

        if (!label) {
          keyPreviewEl.textContent = '—';
          return;
        }

        const finalKey = getUniqueKey(slugifyKey(label), usedKeys);
        const type = allowedFieldTypes.includes(typeSelectEl.value) ? typeSelectEl.value : 'text';
        keyPreviewEl.textContent = finalKey;
        newInfo[finalKey] = {
          label,
          type,
          required: !!requiredInputEl.checked,
        };
      });

      return newInfo;
    }

    function syncInfoJson() {
      info = readInfoFromDom();
      infoInput.value = Object.keys(info).length > 0 ? JSON.stringify(info) : '';
    }

    function renderCampiPreview() {
      const fields = Object.entries(info);
      campiCountEl.textContent = String(fields.length);

      if (fields.length === 0) {
        campiPreviewEl.innerHTML = '<p class="text-muted small mb-0 fst-italic">Aggiungi un campo per vedere l\'anteprima.</p>';
        return;
      }

      campiPreviewEl.innerHTML = fields.map(([key, field]) => {
        const requiredMark = field.required ? '<span class="text-danger ms-1">*</span>' : '';
        const label = field.label || key;

        if (field.type === 'boolean') {
          return `
            <div class="mb-3">
              <label class="form-label">${label}${requiredMark}</label>
              <select class="form-select" disabled>
                <option selected>Seleziona...</option>
                <option>Si</option>
                <option>No</option>
              </select>
            </div>
          `;
        }

        if (field.type === 'time') {
          return `
            <div class="mb-3">
              <label class="form-label">${label}${requiredMark}</label>
              <input type="time" class="form-control" disabled>
            </div>
          `;
        }

        return `
          <div class="mb-3">
            <label class="form-label">${label}${requiredMark}</label>
            <input type="text" class="form-control" placeholder="${label}" disabled>
          </div>
        `;
      }).join('');
    }

    function renderCampiEmptyState() {
      infoContainer.innerHTML = `
        <div class="card" data-sc-campi-empty>
          <div class="card-body text-center text-muted py-5">
            <i class="bx bx-folder-open d-block mb-2 bx-md"></i>
            <div class="fw-medium text-body mb-1">Nessun campo configurato</div>
            <div class="small">Usa il modulo sopra per aggiungere i dati da chiedere al cliente.</div>
          </div>
        </div>
      `;
    }

    function refreshCampiUi() {
      syncInfoJson();
      renderCampiPreview();
      updateNewCampoKeyPreview();
    }

    function addInfoRow(labelValue, typeValue, requiredValue) {
      if (infoContainer.querySelector('[data-sc-campi-empty]')) {
        infoContainer.innerHTML = '';
      }

      const idx = Date.now() + Math.random();
      const typeValueSafe = allowedFieldTypes.includes(typeValue) ? typeValue : 'text';
      const typeMeta = fieldTypeMeta[typeValueSafe];
      const article = document.createElement('div');
      article.className = 'card mb-0';
      article.setAttribute('data-row-id', idx);
      article.innerHTML = `
        <div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
          <div class="d-flex align-items-center gap-2">
            <span class="avatar avatar-sm">
              <span class="avatar-initial rounded bg-label-primary">
                <i class="bx ${typeMeta.icon}" data-type-icon></i>
              </span>
            </span>
            <div>
              <h6 class="card-title mb-0">Campo cliente</h6>
              <small class="text-muted">Chiave: <code data-key-preview>—</code></small>
            </div>
          </div>
          <div class="d-flex align-items-center gap-2">
            <div class="form-check form-switch mb-0">
              <input class="form-check-input" type="checkbox" role="switch" id="campo-required-${idx}" data-required-idx="${idx}" ${requiredValue ? 'checked' : ''}>
              <label class="form-check-label" for="campo-required-${idx}">Obbligatorio</label>
            </div>
            <button type="button" class="btn btn-sm btn-icon btn-label-danger" data-remove-info-idx="${idx}" title="Rimuovi campo">
              <i class="bx bx-trash"></i>
            </button>
          </div>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-7">
              <label class="form-label">Etichetta</label>
              <input type="text" class="form-control" placeholder="Es. Nome, Tavolo, Telefono..." data-label-idx="${idx}" value="">
            </div>
            <div class="col-md-5">
              <label class="form-label">Tipo</label>
              <select class="form-select" data-type-idx="${idx}">
                <option value="text">Testo</option>
                <option value="boolean">Si / No</option>
                <option value="time">Orario</option>
              </select>
            </div>
          </div>
        </div>
      `;

      article.querySelector('input[data-label-idx]').value = labelValue || '';
      article.querySelector('select[data-type-idx]').value = typeValueSafe;
      infoContainer.appendChild(article);
      refreshCampiUi();
    }

    function renderInfoFields() {
      infoContainer.innerHTML = '';
      const fields = Object.entries(info).map(([k, v]) => {
        if (typeof v === 'string') {
          return { label: v.trim() !== '' ? v : k, type: 'text', required: false };
        }
        if (v && typeof v === 'object') {
          return {
            label: typeof v.label === 'string' && v.label.trim() !== '' ? v.label : k,
            type: allowedFieldTypes.includes(v.type) ? v.type : 'text',
            required: !!v.required,
          };
        }
        return { label: k, type: 'text', required: false };
      });

      if (fields.length === 0) {
        renderCampiEmptyState();
      } else {
        fields.forEach((field) => addInfoRow(field.label, field.type, field.required));
      }

      refreshCampiUi();
    }

    function addCampoFromComposer(label, type) {
      const cleanLabel = (label || '').trim();
      if (!cleanLabel) {
        newCampoLabelEl.focus();
        return;
      }

      addInfoRow(cleanLabel, type || 'text', false);
      newCampoLabelEl.value = '';
      newCampoTypeEl.value = 'text';
      updateNewCampoKeyPreview();
    }

    addCampoBtn.addEventListener('click', function () {
      addCampoFromComposer(newCampoLabelEl.value, newCampoTypeEl.value);
    });

    newCampoLabelEl.addEventListener('input', updateNewCampoKeyPreview);
    newCampoTypeEl.addEventListener('change', updateNewCampoKeyPreview);

    newCampoLabelEl.addEventListener('keydown', function (event) {
      if (event.key === 'Enter') {
        event.preventDefault();
        addCampoFromComposer(newCampoLabelEl.value, newCampoTypeEl.value);
      }
    });

    campiRoot.addEventListener('click', function (event) {
      const suggestBtn = event.target.closest('[data-sc-campo-suggest]');
      if (suggestBtn) {
        newCampoLabelEl.value = suggestBtn.getAttribute('data-sc-campo-suggest') || '';
        newCampoTypeEl.value = suggestBtn.getAttribute('data-sc-campo-type-suggest') || 'text';
        updateNewCampoKeyPreview();
        newCampoLabelEl.focus();
        return;
      }

      const removeBtn = event.target.closest('[data-remove-info-idx]');
      if (!removeBtn) {
        return;
      }

      removeBtn.closest('[data-row-id]')?.remove();
      if (infoContainer.querySelectorAll('[data-row-id]').length === 0) {
        renderCampiEmptyState();
      }
      refreshCampiUi();
    });

    infoContainer.addEventListener('input', function (event) {
      if (
        event.target.matches('input[data-label-idx]') ||
        event.target.matches('select[data-type-idx]') ||
        event.target.matches('input[data-required-idx]')
      ) {
        if (event.target.matches('select[data-type-idx]')) {
          const rowEl = event.target.closest('[data-row-id]');
          const iconEl = rowEl?.querySelector('[data-type-icon]');
          const typeMeta = fieldTypeMeta[event.target.value] || fieldTypeMeta.text;
          if (iconEl) {
            iconEl.className = `bx ${typeMeta.icon}`;
          }
        }
        refreshCampiUi();
      }
    });

    infoContainer.addEventListener('change', function (event) {
      if (event.target.matches('input[data-required-idx]')) {
        refreshCampiUi();
      }
    });

    renderInfoFields();

    // --- Istruzioni cliente (JSON: apertura, chiusura, pre_invio, post_invio) ---
    const istruzioniSlots = @json(\App\Models\Saltacoda::ISTRUZIONE_SLOTS);
    const istruzioniInput = document.getElementById('istruzioni');
    const istruzioniRoot = document.getElementById('saltacoda-istruzioni-slots');

    function readIstruzioniFromDom() {
      const payload = {};
      istruzioniSlots.forEach((slot) => {
        const attivoEl = istruzioniRoot.querySelector(`[data-sc-istruzione-attivo="${slot}"]`);
        const titoloEl = istruzioniRoot.querySelector(`[data-sc-istruzione-titolo="${slot}"]`);
        const testoEl = istruzioniRoot.querySelector(`[data-sc-istruzione-testo="${slot}"]`);
        payload[slot] = {
          attivo: !!(attivoEl && attivoEl.checked),
          titolo: (titoloEl?.value || '').trim(),
          testo: (testoEl?.value || '').trim(),
        };
      });
      return payload;
    }

    function syncIstruzioniJson() {
      istruzioniInput.value = JSON.stringify(readIstruzioniFromDom());
    }

    function refreshIstruzioniUi() {
      const data = readIstruzioniFromDom();

      istruzioniSlots.forEach((slot) => {
        const card = istruzioniRoot.querySelector(`[data-sc-istruzione-card="${slot}"]`);
        const statusBadge = istruzioniRoot.querySelector(`[data-sc-istruzione-status="${slot}"]`);
        const previewTitle = istruzioniRoot.querySelector(`[data-sc-preview-title="${slot}"]`);
        const previewText = istruzioniRoot.querySelector(`[data-sc-preview-text="${slot}"]`);
        const fieldsEl = card?.querySelector('.sc-istruzione-card-fields');
        const slotData = data[slot] || {};
        const isActive = !!slotData.attivo;
        const titolo = slotData.titolo || '';
        const testo = slotData.testo || '';

        if (card) {
          card.classList.toggle('border-secondary', !isActive);
          card.classList.toggle('border-opacity-25', !isActive);
        }

        if (fieldsEl) {
          fieldsEl.classList.toggle('opacity-50', !isActive);
        }

        if (statusBadge) {
          statusBadge.textContent = isActive ? 'Attivo' : 'Inattivo';
          statusBadge.classList.toggle('bg-label-success', isActive);
          statusBadge.classList.toggle('bg-label-secondary', !isActive);
        }

        if (previewTitle) {
          previewTitle.textContent = titolo || 'Titolo anteprima';
        }

        if (previewText) {
          if (testo) {
            previewText.textContent = testo;
          } else {
            previewText.innerHTML = '<span class="fst-italic">L\'anteprima apparirà mentre scrivi il messaggio.</span>';
          }
        }
      });

      syncIstruzioniJson();
    }

    istruzioniRoot.addEventListener('input', refreshIstruzioniUi);
    istruzioniRoot.addEventListener('change', refreshIstruzioniUi);
    refreshIstruzioniUi();

    // --- Navigazione rapida tra tab ---
    document.querySelectorAll('[data-sc-go-tab]').forEach((button) => {
      button.addEventListener('click', function () {
        const target = document.querySelector(button.getAttribute('data-sc-go-tab'));
        if (!target) {
          return;
        }
        const tabTrigger = document.querySelector(`[data-bs-target="${button.getAttribute('data-sc-go-tab')}"]`);
        if (tabTrigger && window.bootstrap?.Tab) {
          window.bootstrap.Tab.getOrCreateInstance(tabTrigger).show();
        }
      });
    });

    // --- Copia link cliente ---
    const copyBtn = document.getElementById('sc-copy-cliente-url');
    const urlInput = document.getElementById('sc-cliente-url');
    if (copyBtn && urlInput) {
      copyBtn.addEventListener('click', async function () {
        try {
          await navigator.clipboard.writeText(urlInput.value);
          copyBtn.innerHTML = '<i class="bx bx-check me-1"></i> Copiato';
          setTimeout(() => {
            copyBtn.innerHTML = '<i class="bx bx-copy me-1"></i> Copia';
          }, 2000);
        } catch (e) {
          urlInput.select();
          document.execCommand('copy');
        }
      });
    }

    document.getElementById('saltacodaConfigForm').addEventListener('submit', function () {
      refreshCampiUi();
      refreshIstruzioniUi();
    });
  });
</script>
@endif
@endsection
