import { useEffect } from 'react'
import { wtEvent } from '../../functions/Watchtower'
import { setTitle } from '../../functions/Route'
import './styles/Text.css'

import HeaderMessage from '../layout/HeaderMessage'
import HeaderError from '../layout/HeaderError'

/**
 * Load article from index.html using the 'include-article' placeholder
 */

interface PropsForViewText {
    id: string
}

export default function ViewText({ id }: PropsForViewText) {
    const template = document.head.querySelectorAll('template.article')
    const relevant = [...template].find((e) => e.id === id)

    useEffect(() => {
        const t = Date.now()
        return () => {
            wtEvent('view_article', { id, duration: Date.now() - t })
        }
    }, [])

    if (!relevant) {
        return <HeaderError reason="Unknown Article" />
    }

    setTitle(`Article: ${id}`)
    return (
        <>
            <HeaderMessage label={`Article <ID: ${id}>`} />
            <article className="view-document" dangerouslySetInnerHTML={{ __html: relevant.innerHTML }} />
        </>
    )
}
