import '../bootstrap'
import React from 'react'
import { createRoot } from 'react-dom/client'
import DashboardPage from './DashboardPage'

const rootElement = document.getElementById('dashboard-root')

function parseJsonObject(value) {
  if (!value) {
    return {}
  }

  try {
    const parsed = JSON.parse(value)
    return parsed && typeof parsed === 'object' ? parsed : {}
  } catch {
    return {}
  }
}

if (rootElement) {
  const root = createRoot(rootElement)
  root.render(
    <DashboardPage
      username={rootElement.dataset.username || 'Creator'}
      isCreator={rootElement.dataset.isCreator === '1'}
      level={Number(rootElement.dataset.level || 1)}
      rank={rootElement.dataset.rank || 'Newbie'}
      receivedCommentsCount={Number(rootElement.dataset.receivedCommentsCount || 0)}
      overview={parseJsonObject(rootElement.dataset.overview)}
      preferences={parseJsonObject(rootElement.dataset.preferences)}
    />
  )
}
