/* global */
import { render } from 'preact'
import { Component } from '../routing/component.js'
import { Router } from '../routing/router.js'
import h from './h.js'
// import setStyle from './styles.js'
import waitForDomReady from './wait-for-dom-ready.js'
import { isEdit } from './wcm-mode.js'
import hashJump from './hash-jump.js'
import { injectStyles } from './twind.js'
let isReady = false

export async function renderPage () {
  if (isReady) {
    return
  }

  isReady = true

  // Apply CSS.
  injectStyles(document)
  await waitForDomReady()

  // Skip rendering in edit mode.
  if (isEdit) {
    console.log('Skipping page rendering in edit mode.')
    return
  }

  // Prepare the container.
  const container = document.body.children[0] ?? document.body
  container.innerHTML = ''

  // Scroll to hash.
  hashJump()

  render(h(Router), container)
}

export function renderComponent (componentModel, container) {
  render(h(Component, { _componentModel: componentModel, _model: componentModel.model }), container)
  console.log(`Rendered ${componentModel.id}: ${componentModel.organism}`)
}
