/**
 * Полифиллы для старых браузеров
 */

// Intersection Observer
if (!('IntersectionObserver' in window)) {
  import('intersection-observer');
}

// Резервный вариант для fetch
if (!window.fetch) {
  window.fetch = async (url, options = {}) => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open(options.method || 'GET', url);

      Object.keys(options.headers || {}).forEach(key => {
        xhr.setRequestHeader(key, options.headers[key]);
      });

      xhr.onload = () => {
        resolve({
          ok: xhr.status >= 200 && xhr.status < 300,
          status: xhr.status,
          statusText: xhr.statusText,
          json: () => Promise.resolve(JSON.parse(xhr.responseText)),
          text: () => Promise.resolve(xhr.responseText)
        });
      };

      xhr.onerror = () => reject(new Error('Network Error'));
      xhr.send(options.body);
    });
  };
}

// Object.assign полифилл
if (typeof Object.assign !== 'function') {
  Object.assign = function (target, ...sources) {
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }

    const to = Object(target);

    sources.forEach(source => {
      if (source != null) {
        for (const key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            to[key] = source[key];
          }
        }
      }
    });

    return to;
  };
}

// Array.from полифилл
if (!Array.from) {
  Array.from = function (arrayLike, mapFn, thisArg) {
    const C = this;
    const items = Object(arrayLike);
    const len = parseInt(items.length) || 0;
    const A = typeof C === 'function' ? Object(new C(len)) : new Array(len);

    let k = 0;
    while (k < len) {
      const kValue = items[k];
      if (mapFn) {
        A[k] =
          typeof thisArg === 'undefined'
            ? mapFn(kValue, k)
            : mapFn.call(thisArg, kValue, k);
      } else {
        A[k] = kValue;
      }
      k += 1;
    }

    A.length = len;
    return A;
  };
}
