import $ from 'jquery';
import {createHeader} from "../../components/header/HeaderComponent";
import {createFooter} from "../../components/footer/FooterComponent";
import {createPageDetails} from "../../components/page-details/PageDetailsComponent";
import IHKSidebar from "./sidebar";

export function createElement(tag, classes = [], content = '', parentElement = null, styles = null) {
  const el = document.createElement(tag);
  el.innerHTML = content;
  if (styles) {
    el.style = styles;
  }
  classes.map((c) => {
    el.classList.add(c);
  })
  if (parentElement) {
    parentElement.appendChild(el);
  }
  return el;
}

export function createImage(src = '', width = 0, height = 0, alt = '', classes = [], parentElement = null, loading = 'lazy') {
  const img = new Image();
  img.src = src;
  img.width = width;
  img.height = height;
  img.loading = loading;
  img.classList.add('loading');
  classes.map((c) => {
    img.classList.add(c);
  });
  if (parentElement) {
    parentElement.appendChild(img);
  }
  img.addEventListener('load', (e) => {
    img.classList.add('loaded');
    img.classList.remove('loading');
  });
  return img;
}

export const createSidebarPage = ({
  addPageDetails = true,
  breadcrumb = ['Start', 'Beratung und Service', 'Finanzierung digitaler Projekte'],
}) => {
  const page = createElement('div', ['page']);
  const header = createHeader({});
  const wrapper = createElement('div', ['page-wrapper'], null, page);
  const pageContent = createElement('div', ['page-content', 'has-sidebar'], null, wrapper);
  const container = createElement('div', ['container'], null, pageContent);
  const row = createElement('div', ['row'], null, container);
  const main = createElement('main', ['main-col'], null, row);
  const aside = createElement('aside', ['sidebar'], null, row);
  const footer = createFooter({});

  if (addPageDetails) {
    const pageDetails = createPageDetails({breadcrumb: breadcrumb});
    wrapper.insertBefore(pageDetails, pageContent);
  }

  page.insertBefore(header, wrapper);
  page.appendChild(footer);

  main.id = 'main';
  main.role = 'main';
  aside.id = 'sidebar';
  aside.role = 'complementary';

  new IHKSidebar($(aside));

  return {
    page: page,
    main: main,
    aside: aside,
  }
}

export function getUrlVars(url = window.location.href) {
  let vars = {};
  url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
    vars[key] = value;
  });
  return vars;
}

export function getUrlParam(key) {
  let url = new URL(window.location);
  return url.searchParams.get(key);
}

export function formatNumber(num, decimals) {
  return new Intl.NumberFormat('de-DE',{
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  }).format(num);
}
