import { h } from './react';
import { __ } from './api';
import AuctionList from './screens/AuctionList';
import Settings from './screens/Settings';
import Dashboard from './screens/Dashboard';
import Bidders from './screens/Bidders';

const el = window.wp.element;

/** Show a readable message instead of a blank admin page if a screen crashes. */
class ErrorBoundary extends el.Component {
    constructor(props) { super(props); this.state = { error: null }; }
    static getDerivedStateFromError(error) { return { error }; }
    render() {
        if (this.state.error) {
            return (
                <div className="rt-notice rt-notice--error" role="alert">
                    <span>{__('The auction screen failed to load.')} <code>{String(this.state.error.message || this.state.error)}</code></span>
                </div>
            );
        }
        return this.props.children;
    }
}

const root = document.getElementById('rtapw-app');
if (root) {
    const screens = { dashboard: Dashboard, auctions: AuctionList, bidders: Bidders, settings: Settings };
    const Screen = screens[root.getAttribute('data-view')] || Dashboard;
    const tree = <ErrorBoundary><Screen /></ErrorBoundary>;
    if (el.createRoot) {
        el.createRoot(root).render(tree);
    } else {
        el.render(tree, root);
    }
}
