(function () {
  'use strict';

  // Mobile sidebar toggle
  document.querySelectorAll('[data-toggle-sidebar]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      document.querySelector('.sidebar')?.classList.toggle('open');
    });
  });

  // Modal dialogs: [data-modal-open="id"] shows #id, backdrop click / [data-modal-close] / Escape hides it.
  document.querySelectorAll('[data-modal-open]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var modal = document.getElementById(btn.getAttribute('data-modal-open'));
      if (modal) modal.classList.add('open');
    });
  });
  document.querySelectorAll('.modal-overlay').forEach(function (overlay) {
    overlay.addEventListener('click', function (e) {
      if (e.target === overlay) overlay.classList.remove('open');
    });
    overlay.querySelectorAll('[data-modal-close]').forEach(function (btn) {
      btn.addEventListener('click', function () { overlay.classList.remove('open'); });
    });
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
      document.querySelectorAll('.modal-overlay.open').forEach(function (m) { m.classList.remove('open'); });
    }
  });

  // Tab switching (ticket detail: Conversation / Details / Time Log / Attachments / Audit)
  document.querySelectorAll('[data-tabs]').forEach(function (group) {
    var tabs = group.querySelectorAll('.tab');
    var panels = document.querySelectorAll('[data-tab-panel]');
    tabs.forEach(function (tab) {
      tab.addEventListener('click', function (e) {
        e.preventDefault();
        var target = tab.getAttribute('data-tab');
        tabs.forEach(function (t) { t.classList.remove('active'); });
        tab.classList.add('active');
        panels.forEach(function (p) {
          p.style.display = (p.getAttribute('data-tab-panel') === target) ? '' : 'none';
        });
      });
    });
  });

  // FR-SUP-033: confirm before sending the first public reply on a ticket that has an internal note.
  document.querySelectorAll('[data-confirm-public-reply]').forEach(function (form) {
    form.addEventListener('submit', function (e) {
      var hasNotes = form.getAttribute('data-has-internal-notes') === '1';
      if (hasNotes && !form.dataset.confirmed) {
        var ok = window.confirm('This ticket has internal notes. Are you sure this reply is meant to be PUBLIC and visible to the customer?');
        if (!ok) { e.preventDefault(); return; }
        form.dataset.confirmed = '1';
      }
    });
  });

  // Canned response insert
  document.querySelectorAll('[data-canned-select]').forEach(function (select) {
    select.addEventListener('change', function () {
      var body = select.options[select.selectedIndex].getAttribute('data-body');
      var textarea = document.querySelector(select.getAttribute('data-target'));
      if (textarea && body) {
        textarea.value = (textarea.value ? textarea.value + '\n\n' : '') + body;
        textarea.focus();
      }
      select.selectedIndex = 0;
    });
  });

  // KB deflection / quick-insert search (debounced AJAX against /kb/search or /portal/kb-search)
  document.querySelectorAll('[data-kb-search]').forEach(function (input) {
    var endpoint = input.getAttribute('data-kb-search');
    var resultsBox = document.querySelector(input.getAttribute('data-kb-results'));
    var timer = null;

    input.addEventListener('input', function () {
      clearTimeout(timer);
      var q = input.value.trim();
      if (q.length < 3) { resultsBox.innerHTML = ''; resultsBox.style.display = 'none'; return; }
      timer = setTimeout(function () {
        fetch(endpoint + '?q=' + encodeURIComponent(q))
          .then(function (r) { return r.json(); })
          .then(function (items) { renderKbResults(resultsBox, items, input); })
          .catch(function () {});
      }, 300);
    });
  });

  function renderKbResults(box, items, input) {
    if (!items || !items.length) { box.innerHTML = ''; box.style.display = 'none'; return; }
    var mode = input.getAttribute('data-kb-mode') || 'view';
    var html = items.map(function (a) {
      if (mode === 'insert') {
        return '<button type="button" class="kb-suggestion" style="width:100%;text-align:left;cursor:pointer" data-kb-id="' + a.id + '" data-kb-title="' + escapeHtml(a.title) + '">' +
          '<div class="title">' + escapeHtml(a.title) + '</div><div class="excerpt">' + escapeHtml(a.excerpt) + '…</div></button>';
      }
      return '<a class="kb-suggestion" href="' + a.url + '" target="_blank" rel="noopener">' +
        '<div class="title">' + escapeHtml(a.title) + '</div><div class="excerpt">' + escapeHtml(a.excerpt) + '…</div></a>';
    }).join('');
    box.innerHTML = html;
    box.style.display = 'block';

    if (mode === 'insert') {
      box.querySelectorAll('[data-kb-id]').forEach(function (btn) {
        btn.addEventListener('click', function () {
          document.dispatchEvent(new CustomEvent('kb:selected', { detail: { id: btn.getAttribute('data-kb-id'), title: btn.getAttribute('data-kb-title') } }));
        });
      });
    }
  }

  function escapeHtml(str) {
    return String(str || '').replace(/[&<>"']/g, function (c) {
      return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
    });
  }

  // CSAT star picker
  document.querySelectorAll('[data-csat-stars]').forEach(function (group) {
    var input = document.querySelector(group.getAttribute('data-csat-input'));
    var buttons = group.querySelectorAll('button');
    buttons.forEach(function (btn, idx) {
      btn.addEventListener('click', function () {
        input.value = idx + 1;
        buttons.forEach(function (b, i) { b.classList.toggle('selected', i <= idx); });
      });
    });
  });

  // File input: show selected filenames
  document.querySelectorAll('[data-file-preview]').forEach(function (input) {
    var out = document.querySelector(input.getAttribute('data-file-preview'));
    input.addEventListener('change', function () {
      out.textContent = Array.from(input.files).map(function (f) { return f.name; }).join(', ');
    });
  });

  // Auto-dismiss flash alerts
  document.querySelectorAll('[data-flash]').forEach(function (el) {
    setTimeout(function () { el.style.transition = 'opacity .4s'; el.style.opacity = '0'; setTimeout(function () { el.remove(); }, 400); }, 6000);
  });

  // Kanban board drag-and-drop (Ticket Management > List/Board toggle)
  var board = document.getElementById('kanban-board');
  if (board) {
    var urlTemplate = board.getAttribute('data-move-url-template');
    var csrf = board.getAttribute('data-csrf');
    var dragged = null;

    board.querySelectorAll('.kanban-card[draggable="true"]').forEach(function (card) {
      card.addEventListener('dragstart', function () {
        dragged = card;
        card.classList.add('dragging');
      });
      card.addEventListener('dragend', function () {
        card.classList.remove('dragging');
        dragged = null;
      });
    });

    board.querySelectorAll('.kanban-col').forEach(function (col) {
      var droppable = col.getAttribute('data-droppable') === '1';
      if (!droppable) return; // no listeners = native "not allowed" cursor, no drop fires

      col.addEventListener('dragover', function (e) {
        e.preventDefault();
        col.classList.add('drag-over');
      });
      col.addEventListener('dragleave', function () {
        col.classList.remove('drag-over');
      });
      col.addEventListener('drop', function (e) {
        e.preventDefault();
        col.classList.remove('drag-over');
        if (!dragged) return;

        var toStatus = col.getAttribute('data-status');
        var fromStatus = dragged.getAttribute('data-status');
        if (toStatus === fromStatus) return;

        var reason = '';
        if (toStatus === 'ESCALATED') {
          reason = window.prompt('Reason for escalation:', '');
          if (reason === null || reason.trim() === '') return; // cancelled or blank — abort, card stays put
        }

        moveCard(dragged, col, toStatus, reason);
      });
    });

    function moveCard(card, targetCol, toStatus, reason) {
      var ticketId = card.getAttribute('data-ticket-id');
      var url = urlTemplate.replace('__ID__', ticketId);
      var sourceCol = card.closest('.kanban-col');

      fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ _csrf: csrf, to_status: toStatus, reason: reason || '' }).toString(),
      })
        .then(function (r) { return r.json().then(function (data) { return { status: r.status, data: data }; }); })
        .then(function (res) {
          if (!res.data.ok) {
            window.alert(res.data.error || 'Could not move this ticket.');
            return;
          }
          card.setAttribute('data-status', toStatus);
          targetCol.querySelector('.kanban-col-body').appendChild(card);
          updateCount(sourceCol);
          updateCount(targetCol);
        })
        .catch(function () {
          window.alert('Network error — the ticket was not moved.');
        });
    }

    function updateCount(col) {
      var countEl = col.querySelector('.kanban-col-head .count');
      var n = col.querySelectorAll('.kanban-card').length;
      if (countEl) countEl.textContent = n;
      var emptyEl = col.querySelector('.kanban-empty');
      if (n > 0 && emptyEl) emptyEl.remove();
      if (n === 0 && !emptyEl) {
        var div = document.createElement('div');
        div.className = 'kanban-empty';
        div.textContent = 'No tickets';
        col.querySelector('.kanban-col-body').appendChild(div);
      }
    }
  }
})();
