import React from 'react'
import PropTypes from 'prop-types'

class Page extends React.Component {
    componentDidMount() {
        this.setTitle(this.props.title)
        window.scrollTo?.(0, 0)
    }

    componentDidUpdate(prevProps) {
        if (prevProps.title !== this.props.title) {
            this.setTitle(this.props.title)
        }
    }

    setTitle = (title) => {
        const newTitle = `${title} | ES`
        document.title = newTitle

        if (this.props.title === newTitle) {
            return
        }

        this.props.onTitleChange?.(title)
    }

    render() {
        return this.props.children
    }
}

Page.propTypes = {
    title: PropTypes.string.isRequired,
    children: PropTypes.node,
    onTitleChange: PropTypes.func,
}

export default Page
