let container = document.getElementById('page_slots_demo');

let fieldset = container.querySelector('fieldset');
let iframe = container.querySelector('iframe');
let stylesheets = Array.from(document.querySelectorAll("link[rel=stylesheet][href^='/dist/']"))
  .map(i => i.outerHTML)
  .join('\n');
let includes = `${stylesheets}
  <script src="/dist/webawesome.loader.js" type="module"></script>
  <link rel="stylesheet" href="./demo-page.css">`;

async function render() {
  await customElements.whenDefined('wa-checkbox');

  // Let checkboxes update their "state"
  await Promise.allSettled(
    Array.from(fieldset.querySelectorAll('wa-checkbox[name=slot]')).map(checkbox => {
      return checkbox.updateComplete;
    }),
  );

  let slots = Array.from(fieldset.querySelectorAll('wa-checkbox[name=slot]:state(checked)'));
  let slotsHTML = slots
    .map(slot => {
      let name = slot.getAttribute('value');
      let description = slot.getAttribute('data-description');

      let tag = 'div';
      if (name.endsWith('header')) {
        tag = 'header';
      }
      if (name.endsWith('footer')) {
        tag = 'footer';
      }

      return `<${tag} class="slot-content" slot="${name}">
		<strong>${name || 'main <em>(default)</em>'}</strong>
		<p>${description}</p>
	</${tag}>`;
    })
    .join('\n');
  let page = iframe.contentDocument?.querySelector('wa-page');

  if (page) {
    page.innerHTML = slotsHTML;
  } else {
    iframe.srcdoc = `${includes}<wa-page>${slotsHTML}</wa-page>`;
  }
}
await render();
fieldset?.addEventListener('input', render);
