/**
 * CSRF-aware fetch для admin API (session + X-CSRF-Token).
 */
(function () {
  'use strict';

  function getCsrfToken() {
    var meta = document.querySelector('meta[name="csrf-token"]');
    return meta ? meta.getAttribute('content') || '' : '';
  }

  function withCsrfHeaders(method, headers) {
    var m = (method || 'GET').toUpperCase();
    var h = headers ? Object.assign({}, headers) : {};
    if (m !== 'GET' && m !== 'HEAD' && m !== 'OPTIONS') {
      var token = getCsrfToken();
      if (token && !h['X-CSRF-Token']) {
        h['X-CSRF-Token'] = token;
      }
    }
    return h;
  }

  window.cascad360CsrfToken = getCsrfToken;

  window.cascad360Fetch = function (url, opts) {
    opts = opts || {};
    opts.credentials = opts.credentials || 'same-origin';
    opts.headers = withCsrfHeaders(opts.method, opts.headers);
    return fetch(url, opts);
  };
})();
