(function () {
  function qs(sel, root) { return (root || document).querySelector(sel); }
  function qsa(sel, root) { return Array.from((root || document).querySelectorAll(sel)); }

  window.BarberAdmin = {
    async postForm(url, formData) {
      const res = await fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data.ok === false) {
        throw new Error(data.error || 'Request failed');
      }
      return data;
    },
    toast(msg, isError) {
      let el = qs('#admin-toast');
      if (!el) {
        el = document.createElement('div');
        el.id = 'admin-toast';
        el.style.cssText = 'position:fixed;right:1rem;bottom:1rem;z-index:99;padding:.75rem 1rem;border-radius:8px;font:500 14px IBM Plex Sans,sans-serif';
        document.body.appendChild(el);
      }
      el.textContent = msg;
      el.style.background = isError ? '#5a2222' : '#1e3d2d';
      el.style.color = '#fff';
      el.style.display = 'block';
      clearTimeout(el._t);
      el._t = setTimeout(() => { el.style.display = 'none'; }, 2800);
    },
    initCropUpload(opts) {
      const input = qs(opts.input);
      const modal = qs('#crop-modal');
      const stage = qs('#crop-stage');
      const applyBtn = qs('#crop-apply');
      const cancelBtn = qs('#crop-cancel');
      if (!input || !modal || !window.Cropper) return;

      let cropper = null;
      let pendingFile = null;

      input.addEventListener('change', () => {
        const file = input.files && input.files[0];
        if (!file || !file.type.startsWith('image/')) return;
        pendingFile = file;
        const url = URL.createObjectURL(file);
        stage.innerHTML = '';
        const img = document.createElement('img');
        img.src = url;
        img.style.maxWidth = '100%';
        stage.appendChild(img);
        modal.classList.add('open');
        if (cropper) cropper.destroy();
        cropper = new Cropper(img, {
          aspectRatio: opts.aspectRatio || NaN,
          viewMode: 1,
          autoCropArea: 0.9,
        });
      });

      cancelBtn && cancelBtn.addEventListener('click', () => {
        modal.classList.remove('open');
        input.value = '';
        if (cropper) { cropper.destroy(); cropper = null; }
      });

      applyBtn && applyBtn.addEventListener('click', async () => {
        if (!cropper || !pendingFile) return;
        const data = cropper.getData(true);
        const fd = new FormData();
        fd.append('file', pendingFile);
        fd.append('tag', opts.tag || 'general');
        fd.append('crop_x', String(data.x));
        fd.append('crop_y', String(data.y));
        fd.append('crop_w', String(data.width));
        fd.append('crop_h', String(data.height));
        try {
          const result = await BarberAdmin.postForm(opts.uploadUrl || (window.APP_BASE || '') + '/api/media_upload.php', fd);
          modal.classList.remove('open');
          if (typeof opts.onUploaded === 'function') opts.onUploaded(result);
          BarberAdmin.toast('Image uploaded');
        } catch (e) {
          BarberAdmin.toast(e.message, true);
        } finally {
          input.value = '';
          if (cropper) { cropper.destroy(); cropper = null; }
        }
      });
    }
  };

  // Service drag reorder
  const list = qs('#service-list');
  if (list) {
    let dragEl = null;
    qsa('.service-row', list).forEach((row) => {
      const handle = qs('.drag-handle', row);
      if (!handle) return;
      handle.setAttribute('draggable', 'true');
      handle.addEventListener('dragstart', (e) => {
        dragEl = row;
        row.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
      });
      handle.addEventListener('dragend', async () => {
        row.classList.remove('dragging');
        const ids = qsa('.service-row', list).map((r) => r.dataset.id);
        const fd = new FormData();
        fd.append('order', JSON.stringify(ids));
        try {
          await BarberAdmin.postForm((window.APP_BASE || '') + '/api/services_reorder.php', fd);
          BarberAdmin.toast('Order saved');
        } catch (err) {
          BarberAdmin.toast(err.message, true);
        }
      });
      row.addEventListener('dragover', (e) => {
        e.preventDefault();
        if (!dragEl || dragEl === row) return;
        const rect = row.getBoundingClientRect();
        const after = (e.clientY - rect.top) > rect.height / 2;
        list.insertBefore(dragEl, after ? row.nextSibling : row);
      });
    });
  }
})();
