/* ==========================================================================
   BLOOM IRIS AGENCY — ADMIN JS
   Dependency-free. Sidebar, confirm-delete, filters, image preview, slug.
   ========================================================================== */
(function () {
  'use strict';

  document.addEventListener('DOMContentLoaded', function () {
    initSidebar();
    initConfirms();
    initLiveSearch();
    initImagePreview();
    initUploadFields();
    initSlugify();
    initRepeater();
    autoDismiss();
  });

  /* ---------------------------------------------------------------------- */
  function initSidebar() {
    var toggle = document.querySelector('.menu-toggle');
    var sidebar = document.querySelector('.sidebar');
    if (!toggle || !sidebar) return;
    toggle.addEventListener('click', function () {
      sidebar.classList.toggle('open');
    });
    document.addEventListener('click', function (e) {
      if (window.innerWidth <= 760 &&
          !sidebar.contains(e.target) && !toggle.contains(e.target)) {
        sidebar.classList.remove('open');
      }
    });
  }

  /* Confirm before destructive actions ---------------------------------- */
  function initConfirms() {
    document.addEventListener('click', function (e) {
      var el = e.target.closest('[data-confirm]');
      if (!el) return;
      if (!window.confirm(el.getAttribute('data-confirm'))) {
        e.preventDefault();
        e.stopPropagation();
      }
    });
  }

  /* Live table filtering ------------------------------------------------- */
  function initLiveSearch() {
    var input = document.querySelector('[data-table-search]');
    if (!input) return;
    var tableSel = input.getAttribute('data-table-search');
    var table = document.querySelector(tableSel);
    if (!table) return;
    input.addEventListener('input', function () {
      var q = input.value.toLowerCase().trim();
      table.querySelectorAll('tbody tr').forEach(function (tr) {
        tr.style.display = tr.textContent.toLowerCase().indexOf(q) > -1 ? '' : 'none';
      });
    });
  }

  /* Image file preview --------------------------------------------------- */
  function initImagePreview() {
    document.querySelectorAll('input[type=file][data-preview]').forEach(function (input) {
      input.addEventListener('change', function () {
        var target = document.querySelector(input.getAttribute('data-preview'));
        if (!target || !input.files || !input.files[0]) return;
        var reader = new FileReader();
        reader.onload = function (ev) {
          target.src = ev.target.result;
          target.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
      });
    });
  }

  /* Custom upload controls — show the chosen filename ----------------- */
  function initUploadFields() {
    document.querySelectorAll('.upload-field').forEach(function (field) {
      var input = field.querySelector('.upload-input');
      var nameEl = field.querySelector('[data-upload-name]');
      if (!input || !nameEl) return;

      input.addEventListener('change', function () {
        var files = input.files;
        if (!files || files.length === 0) {
          nameEl.textContent = 'No file selected';
          field.classList.remove('is-filled');
          return;
        }
        if (files.length === 1) {
          nameEl.textContent = files[0].name;
        } else {
          nameEl.textContent = files.length + ' files selected';
        }
        field.classList.add('is-filled');
      });
    });
  }

  /* Auto-generate slug from a title field ------------------------------- */
  function initSlugify() {
    var source = document.querySelector('[data-slug-source]');
    var target = document.querySelector('[data-slug-target]');
    if (!source || !target) return;
    // only auto-fill when the slug field is empty / untouched
    if (target.value.trim() !== '') return;
    source.addEventListener('input', function () {
      target.value = source.value.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
    });
  }

  /* Simple repeatable field rows (process steps, etc.) ------------------ */
  function initRepeater() {
    document.querySelectorAll('[data-repeater]').forEach(function (rep) {
      var list = rep.querySelector('[data-repeater-list]');
      var tpl = rep.querySelector('[data-repeater-template]');
      var addBtn = rep.querySelector('[data-repeater-add]');
      if (!list || !tpl || !addBtn) return;

      addBtn.addEventListener('click', function () {
        var clone = tpl.content.cloneNode(true);
        list.appendChild(clone);
      });
      list.addEventListener('click', function (e) {
        var rm = e.target.closest('[data-repeater-remove]');
        if (rm) rm.closest('[data-repeater-row]').remove();
      });
    });
  }

  /* Auto-dismiss flash alerts ------------------------------------------- */
  function autoDismiss() {
    document.querySelectorAll('.alert').forEach(function (a) {
      setTimeout(function () {
        a.style.transition = 'opacity .4s ease';
        a.style.opacity = '0';
        setTimeout(function () { a.remove(); }, 400);
      }, 5000);
    });
  }
})();
