(function () {
  const config = window.WEMOMENTS_CONFIG || {};

  function headers() {
    return { 'X-CSRF-Token': config.csrfToken || '', 'Content-Type': 'application/json' };
  }

  async function api(method, url, data) {
    const res = await window.axios({ method, url, data, headers: headers() });
    if (!res.data.success) throw new Error(res.data.message || '请求失败');
    return res.data.data;
  }

  function values(form) {
    const out = {};
    new FormData(form).forEach((value, key) => {
      if (value === 'true') out[key] = true;
      else if (value === 'false') out[key] = false;
      else if (/^\d+$/.test(value) && key.includes('_mb')) out[key] = Number(value);
      else out[key] = value;
    });
    return out;
  }

  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-bootstrap-form]').forEach((form) => {
      form.addEventListener('submit', async (event) => {
        event.preventDefault();
        try {
          await api('post', '/admin/api/bootstrap', values(form));
          location.href = '/admin';
        } catch (error) {
          alert(error.message);
        }
      });
    });

    document.querySelectorAll('[data-admin-settings-form]').forEach((form) => {
      form.addEventListener('submit', async (event) => {
        event.preventDefault();
        try {
          await api('post', '/admin/api/settings', values(form));
          location.reload();
        } catch (error) {
          alert(error.message);
        }
      });
    });

    document.querySelectorAll('[data-admin-link-form]').forEach((form) => {
      form.addEventListener('submit', async (event) => {
        event.preventDefault();
        try {
          await api('post', '/admin/api/links', values(form));
          location.reload();
        } catch (error) {
          alert(error.message);
        }
      });
    });

    document.addEventListener('change', async (event) => {
      const role = event.target.closest('[data-admin-user-role]');
      if (!role) return;
      const row = role.closest('[data-user-id]');
      if (!row) return;
      await api('post', '/admin/api/users/' + row.dataset.userId + '/role', { role: role.value });
    });

    document.addEventListener('click', async (event) => {
      const action = event.target.closest('[data-admin-action]');
      if (!action) return;
      const name = action.getAttribute('data-admin-action');
      try {
        if (name === 'ban-user') {
          const row = action.closest('[data-user-id]');
          await api('post', '/admin/api/users/' + row.dataset.userId + '/ban');
          location.reload();
        }
        if (name === 'bulk-posts') {
          const ids = Array.from(document.querySelectorAll('[data-post-check]:checked')).map((input) => input.value);
          const bulkAction = document.querySelector('[data-bulk-action]').value;
          if (ids.length) await api('post', '/admin/api/posts/bulk', { ids, action: bulkAction });
          location.reload();
        }
        if (name === 'approve-comment' || name === 'trash-comment') {
          const row = action.closest('[data-comment-id]');
          await api('post', '/admin/api/comments/' + row.dataset.commentId + '/status', { status: name === 'approve-comment' ? 'approved' : 'trash' });
          location.reload();
        }
        if (name === 'delete-link') {
          const row = action.closest('[data-link-id]');
          await api('delete', '/admin/api/links/' + row.dataset.linkId);
          location.reload();
        }
      } catch (error) {
        alert(error.message);
      }
    });

    document.querySelectorAll('[data-check-all]').forEach((box) => {
      box.addEventListener('change', () => {
        document.querySelectorAll('[data-post-check]').forEach((input) => {
          input.checked = box.checked;
        });
      });
    });
  });
})();
