import React from 'react';
import ReactDOM from 'react-dom';

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
            modified: null,
            rendered: null,
            slug: null,
            source: null,
            title: null,
        };
    }

    componentDidMount() {
        if (!window.location.hash) {
            window.location.hash = "#index";
        }
        const loc = window.location.hash.substring(1);
        fetch(`/p/${loc}`, {headers: {'Accept': 'application/json'}})
            .then(res => res.json())
            .then(
                (res) => {
                    console.log(res);
                    this.setState({
                        loaded: true,
                        modified: res.modified,
                        rendered: res.rendered,
                        slug: res.slug,
                        source: res.source,
                        title: res.title,
                    });
                },
                (error) => {
                    this.setState({
                        rendered: "not found",
                    });
                }
            );
    }

    render() {
        if (this.state.loaded) {
            return <div className="page" dangerouslySetInnerHTML={{__html: this.state.rendered}} />;
        } else {
            return <div className="page">Loading...</div>;
        }
    }
}

const Sidebar = () => {
    return (
        <div className="sidebar"><img src="/static/baba-yaga-sidebar-plain.svg"/></div>
    );
};

const Board = () => {
    return (
        <div className="board">
          <Sidebar/>
          <Page/>
        </div>
    );
};

ReactDOM.render(<Board/>, document.getElementById('root'));
