export function setText(node, value) {
  if (!(node instanceof Node)) throw new TypeError('DOM-Ziel fehlt.');
  node.textContent = value == null ? '' : String(value);
  return node;
}

export function createElement(tagName, { className = '', text = '', attributes = {}, children = [] } = {}) {
  if (!/^[a-z][a-z0-9-]*$/i.test(String(tagName))) throw new TypeError('Ungültiger Elementname.');
  const element = document.createElement(tagName);
  if (className) element.className = String(className);
  if (text !== '') setText(element, text);
  for (const [name, value] of Object.entries(attributes)) {
    if (!/^(aria-[a-z-]+|data-[a-z-]+|id|role|title|type|name|value|href|src|alt|tabindex)$/i.test(name)) {
      throw new TypeError(`Attribut ist nicht freigegeben: ${name}`);
    }
    if (['href', 'src'].includes(name.toLowerCase())) {
      const url = new URL(String(value), window.location.origin);
      if (!['http:', 'https:', 'blob:'].includes(url.protocol) || (['http:', 'https:'].includes(url.protocol) && url.origin !== window.location.origin)) {
        throw new TypeError(`Externe oder unsichere URL ist nicht erlaubt: ${name}`);
      }
    }
    element.setAttribute(name, String(value));
  }
  for (const child of children) element.append(child);
  return element;
}
