/* eslint-env browser */
/* eslint no-prototype-builtins: 0 */
/* eslint no-restricted-syntax: 0 */
/* eslint no-unused-vars: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import FlowBoxComponent from '../components/flowbox/FlowBoxComponent';

const defaultOptions = {
  config: {
    container: '.au_flowbox',
    render: 'ul',
  },
  data: {
    mode: 'list',
    source: '.au_flowbox_list',
    headline: 'Overskrift',
    prepend: '',
  },
};

class AUFlowbox {
  constructor(lang, boxes) {
    this.boxes = boxes;
    this.lang = lang;
  }

  static mergeOptions(_box) {
    const box = _box;
    if (!box.hasOwnProperty('config')) {
      box.config = {};
    }

    for (const conf in defaultOptions.config) {
      if (!box.config.hasOwnProperty(conf)) {
        box.config[conf] = defaultOptions.config[conf];
      }
    }

    if (!box.hasOwnProperty('data')) {
      box.data = {};
    }

    for (const data in defaultOptions.data) {
      if (!box.data.hasOwnProperty(data)) {
        box.data[data] = defaultOptions.data[data];
      }
    }
  }

  static parse(box) {
    const getLabelFromLi = (li) => {
      // Primært: TYPO3v10/“p-wrapped” eller global content hvor der kommer en wrapper ind
      const labelEl = li.querySelector(':scope > p')
        || li.querySelector(':scope > div > p')
        || li.querySelector(':scope > div > p > span') // hvis editoren putter spans ind
        || null;

      if (labelEl) {
        return labelEl.innerHTML.trim();
      }

      // Sekundært: mixed content direkte i <li>
      // Ignorer <ul> og <ol>, men behold alle andre nodes inkl. inline elementer
      const html = Array.from(li.childNodes)
        .filter((n) => !(n.nodeType === Node.ELEMENT_NODE
          && (n.tagName === 'UL' || n.tagName === 'OL')))
        .map((n) => (n.nodeType === Node.TEXT_NODE ? n.textContent : n.outerHTML))
        .join('')
        .replace(/\s+/g, ' ')
        .trim();

      return html;
    };

    const parseUl = (data, ulElements) => {
      ulElements.forEach((ul) => {
        const lis = ul.querySelectorAll(':scope > li');
        lis.forEach((li) => {
          const name = getLabelFromLi(li);
          if (!name) return;

          const obj = { name, children: [], parent: data };
          data.children.push(obj);

          const childUls = li.querySelectorAll(':scope > ul');
          if (childUls.length > 0) {
            parseUl(obj, childUls); // Det her skal vi altid gøre
          }
        });
      });
    };

    // Start: find root UL’er fra box.data.source (som før)
    const roots = document.querySelectorAll(box.data.source);
    parseUl(box.item, roots);
  }

  init() {
    for (let i = 0; i < this.boxes.length; i += 1) {
      const box = this.boxes[i];
      AUFlowbox.mergeOptions(box);
      box.id = i;
      box.item = {
        name: box.data.headline,
        children: [],
        parent: null,
      };
      AUFlowbox.parse(box);
      const mountNode = document.querySelector(box.config.container);
      // The page supplies its own global ReactDOM, which may predate createRoot.
      // eslint-disable-next-line react/no-deprecated
      ReactDOM.render(<FlowBoxComponent box={box} lang={this.lang} />, mountNode);
    }
  }
}

window.AUFlowbox = AUFlowbox;
