'use strict';

(function () {
  const wizardEl = document.getElementById('wizard-md-stampanti');
  if (!wizardEl || typeof Stepper === 'undefined') {
    return;
  }

  const STEP_ENDPOINT = parseInt(wizardEl.dataset.stepEndpoint || '2', 10);
  const ENDPOINT_POLL_MS = 10000;
  const startStepDefault = parseInt(wizardEl.dataset.startStep || '0', 10);
  const stepper = new Stepper(wizardEl, { linear: false });

  let currentStepIndex = 0;
  let endpointPollInterval = null;
  let endpointAutoAdvanced = false;

  function waitForFestAgentApi(maxMs = 8000) {
    return new Promise((resolve) => {
      if (typeof window.fetchFestAgentStatus === 'function') {
        resolve();
        return;
      }
      const started = Date.now();
      const timer = setInterval(() => {
        if (typeof window.fetchFestAgentStatus === 'function' || Date.now() - started > maxMs) {
          clearInterval(timer);
          resolve();
        }
      }, 100);
    });
  }

  function stopEndpointPoll() {
    if (endpointPollInterval) {
      clearInterval(endpointPollInterval);
      endpointPollInterval = null;
    }
  }

  function renderSetupFestAgentStatus(status) {
    const el = document.getElementById('mdSetupFestAgentStatus');
    if (typeof window.renderFestAgentStatus === 'function') {
      window.renderFestAgentStatus(el, status);
    }
  }

  function checkFestAgentOnline() {
    if (typeof window.fetchFestAgentStatus !== 'function') {
      return Promise.resolve(false);
    }
    return window.fetchFestAgentStatus()
      .then((status) => {
        renderSetupFestAgentStatus(status);
        return status.online;
      })
      .catch(() => {
        renderSetupFestAgentStatus({ online: false, endpointId: null });
        return false;
      });
  }

  function advanceFromEndpointIfActive() {
    if (endpointAutoAdvanced || currentStepIndex !== STEP_ENDPOINT) {
      return;
    }
    endpointAutoAdvanced = true;
    stopEndpointPoll();
    stepper.next();
    if (typeof notyf !== 'undefined') {
      notyf.success('FestAgent attivo — vai al passo successivo');
    }
  }

  function pollEndpointFestAgentStatus() {
    checkFestAgentOnline().then((online) => {
      if (online) {
        advanceFromEndpointIfActive();
      }
    });
  }

  function startEndpointPoll() {
    stopEndpointPoll();
    endpointAutoAdvanced = false;
    waitForFestAgentApi().then(() => {
      pollEndpointFestAgentStatus();
      endpointPollInterval = setInterval(pollEndpointFestAgentStatus, ENDPOINT_POLL_MS);
    });
  }

  async function jumpToEndpointIfFestAgentActive() {
    if (currentStepIndex > STEP_ENDPOINT) {
      return;
    }
    const online = await checkFestAgentOnline();
    if (online && currentStepIndex < STEP_ENDPOINT) {
      stepper.to(STEP_ENDPOINT + 1);
    }
  }

  async function onSetupTabVisible() {
    await waitForFestAgentApi();
    await jumpToEndpointIfFestAgentActive();
  }

  const setupTabBtn = document.getElementById('md-tab-setup');
  const setupPane = document.getElementById('mdPaneSetup');

  setupTabBtn?.addEventListener('shown.bs.tab', onSetupTabVisible);

  waitForFestAgentApi().then(() => {
    if (setupPane?.classList.contains('active') || setupPane?.classList.contains('show')) {
      onSetupTabVisible();
    }
  });

  if (startStepDefault > 0) {
    stepper.to(startStepDefault + 1);
  }

  wizardEl.querySelectorAll('.btn-next').forEach((btn) => {
    btn.addEventListener('click', () => stepper.next());
  });
  wizardEl.querySelectorAll('.btn-prev').forEach((btn) => {
    btn.addEventListener('click', () => stepper.previous());
  });

  wizardEl.addEventListener('shown.bs-stepper', (event) => {
    const idx = event.detail.indexStep;
    currentStepIndex = idx;
    wizardEl.querySelectorAll('.btn-prev').forEach((btn) => {
      btn.disabled = idx === 0;
    });

    stopEndpointPoll();
    if (idx === STEP_ENDPOINT) {
      startEndpointPoll();
    }
  });

  const pcSiPanel = document.getElementById('mdSetupPcSiPanel');
  const pcNoPanel = document.getElementById('mdSetupPcNoPanel');

  function showPcChoice(choice) {
    pcSiPanel?.classList.toggle('d-none', choice !== 'si');
    pcNoPanel?.classList.toggle('d-none', choice !== 'no');
  }

  document.getElementById('mdSetupPcSi')?.addEventListener('click', () => showPcChoice('si'));
  document.getElementById('mdSetupPcNo')?.addEventListener('click', () => showPcChoice('no'));

  const quizAnswers = { rete: null, casse: null };
  const quizResultEl = document.getElementById('mdSetupQuizResult');

  function setQuizOption(btn) {
    const q = btn.dataset.q;
    const v = btn.dataset.v;
    if (!q || !v) return;

    quizAnswers[q] = v;
    document.querySelectorAll(`.md-setup-quiz-opt[data-q="${q}"]`).forEach((el) => {
      el.classList.remove('active', 'btn-primary');
      el.classList.add(el.dataset.v === 'ns' ? 'btn-outline-secondary' : 'btn-outline-primary');
    });
    btn.classList.add('active', 'btn-primary');
    btn.classList.remove('btn-outline-primary', 'btn-outline-secondary');
    updateSetupQuizResult();
  }

  function updateSetupQuizResult() {
    if (!quizResultEl) return;

    const { rete, casse } = quizAnswers;
    if (!rete || !casse) {
      quizResultEl.classList.add('d-none');
      return;
    }

    let html = '';

    if (rete === 'si' && casse === 'no') {
      html =
        '<p class="fw-semibold mb-1"><i class="bx bx-check-circle me-1 text-success"></i>Consiglio: <strong>un solo PC</strong></p>' +
        '<p class="mb-0">Metti tutte le stampanti su <strong>un computer</strong> e FestAgent solo lì. Con la rete che copre tutto, è la scelta più facile.</p>';
      quizResultEl.className = 'alert alert-success py-2 px-3 small mb-0';
    } else if (rete === 'si' && casse === 'si') {
      html =
        '<p class="fw-semibold mb-1"><i class="bx bx-info-circle me-1"></i>Consiglio: <strong>un PC per cassa</strong></p>' +
        '<p class="mb-0">Hai già PC e stampante per bancone: installa FestAgent <strong>su ogni PC-cassa</strong>, con le stampanti che usa lì.</p>';
      quizResultEl.className = 'alert alert-primary py-2 px-3 small mb-0';
    } else if (rete === 'no') {
      html =
        '<p class="fw-semibold mb-1"><i class="bx bx-info-circle me-1"></i>Consiglio: <strong>PC vicino alla stampante</strong></p>' +
        '<p class="mb-0">Rete debole? Meglio FestAgent sul PC <strong>accanto</strong> a ogni stampante (cavo USB o rete corta).</p>';
      quizResultEl.className = 'alert alert-primary py-2 px-3 small mb-0';
    } else {
      html =
        '<p class="fw-semibold mb-1"><i class="bx bx-help-circle me-1"></i>Non sei sicuro?</p>' +
        '<p class="mb-0">Chiedi a chi gestisce la rete. Oppure usa il PC <strong>accanto alla stampante</strong> — funziona sempre.</p>';
      quizResultEl.className = 'alert alert-secondary py-2 px-3 small mb-0';
    }

    quizResultEl.innerHTML = html;
    quizResultEl.classList.remove('d-none');
  }

  document.querySelectorAll('.md-setup-quiz-opt').forEach((btn) => {
    btn.addEventListener('click', () => setQuizOption(btn));
  });

  document.getElementById('mdSetupGoTree')?.addEventListener('click', () => {
    sessionStorage.setItem('fest.mappa_dispositivi.active_tab', '#mdPaneTree');
    const trigger = document.getElementById('md-tab-tree');
    if (trigger && typeof bootstrap !== 'undefined') {
      bootstrap.Tab.getOrCreateInstance(trigger).show();
    }
  });

  const modalEl = document.getElementById('mdSetupModal');
  const modalTitle = document.getElementById('mdSetupModalTitle');
  const modalBody = document.getElementById('mdSetupModalBody');
  const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;

  function openSetupModal(title, html) {
    if (!modalEl || !modalTitle || !modalBody || typeof bootstrap === 'undefined') {
      return;
    }
    modalTitle.innerHTML = title;
    modalBody.innerHTML = html;
    bootstrap.Modal.getOrCreateInstance(modalEl).show();
  }

  function loadSetupModal(title, url) {
    if (!modalEl || !modalTitle || !modalBody || typeof bootstrap === 'undefined') {
      return;
    }
    modalTitle.innerHTML = title;
    modalBody.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>';
    bootstrap.Modal.getOrCreateInstance(modalEl).show();
    fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
      .then((response) => response.text())
      .then((html) => { modalBody.innerHTML = html; })
      .catch(() => {
        modalBody.innerHTML = '<div class="alert alert-danger mb-0">Errore nel caricamento.</div>';
      });
  }

  document.getElementById('mdSetupIstruzioni')?.addEventListener('click', () => {
    loadSetupModal(
      '<i class="bx bx-help-circle me-1"></i> Aiuto FestAgent',
      wizardEl.dataset.urlIstruzioni || ''
    );
  });

  document.getElementById('mdSetupProductKey')?.addEventListener('click', () => {
    loadSetupModal('Codice manuale', wizardEl.dataset.urlProductKey || '');
  });

  document.getElementById('mdSetupCollegaPc')?.addEventListener('click', async () => {
    const btn = document.getElementById('mdSetupCollegaPc');
    if (!btn) return;
    btn.disabled = true;
    try {
      const response = await fetch(wizardEl.dataset.urlCollegaPc || '', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'X-CSRF-TOKEN': csrfToken,
          'X-Requested-With': 'XMLHttpRequest',
        },
      });
      const payload = await response.json();
      if (!response.ok || !payload.url) {
        throw new Error(payload.message || 'Collegamento non riuscito');
      }
      window.open(payload.url, '_blank');
      openSetupModal(
        'FestAgent si sta aprendo',
        '<div class="alert alert-info mb-2">Segui le istruzioni nel programma FestAgent:</div><ol class="mb-0 ps-3 small"><li>Dai un nome alla postazione</li><li>Scegli le stampanti</li><li>Clicca Registra stampanti e Avvia worker</li></ol><p class="small text-muted mt-3 mb-0">Appena FestAgent è attivo passeremo al passo successivo.</p>'
      );
      if (currentStepIndex === STEP_ENDPOINT) {
        startEndpointPoll();
      }
    } catch (error) {
      if (typeof notyf !== 'undefined') {
        notyf.error(error.message || 'Non sono riuscito a collegare il computer. Riprova.');
      } else {
        alert(error.message || 'Non sono riuscito a collegare il computer. Riprova.');
      }
    } finally {
      btn.disabled = false;
    }
  });
})();
