const { useState, useEffect } = React;

const App = () => {
    const [currentPage, setCurrentPage] = useState('landing');

    useEffect(() => {
        const handlePopState = (event) => {
            if (event.state && event.state.page) {
                setCurrentPage(event.state.page);
            } else {
                setCurrentPage('landing');
            }
        };

        window.addEventListener('popstate', handlePopState);
        window.history.replaceState({ page: 'landing' }, '');

        return () => window.removeEventListener('popstate', handlePopState);
    }, []);

    const navigate = (page) => {
        if (page !== currentPage) {
            window.history.pushState({ page }, '');
            setCurrentPage(page);
            window.scrollTo(0, 0);
        }
    };

    // Register global logout handler so authenticated playground components
    // can navigate back to the landing page without knowing about app state
    useEffect(() => {
        window.onORFlowLogout = () => navigate('landing');
        return () => { window.onORFlowLogout = null; };
    }, [currentPage]);

    const isInApp = currentPage === 'playground' || currentPage === 'playground31';

    return (
        <div className="app-container">
            {/* Hide public navbar on mobile inside authenticated views */}
            <div className={isInApp ? 'public-nav-desktop-only' : ''}>
                <Navbar onNavigate={navigate} activePage={currentPage} />
            </div>
            
            <main>
                {currentPage === 'landing' && (
                    <>
                        <Hero onNavigate={navigate} />
                        <Features />
                    </>
                )}
                {currentPage === 'playground' && <Playground />}
                {currentPage === 'playground31' && <Playground31 />}
            </main>

            {!isInApp && (
                <footer className="footer">
                    <div style={{ marginBottom: '2rem' }}>
                        <BrandLogo />
                    </div>
                    <div style={{ display: 'flex', gap: '2rem', justifyContent: 'center', marginBottom: '2rem' }}>
                        <span className="nav-link">About</span>
                        <span className="nav-link">Security</span>
                        <span className="nav-link">Privacy</span>
                        <span className="nav-link">Contact</span>
                    </div>
                    <p>© 2026 OR Flow Efficiency Platform. All rights reserved.</p>
                </footer>
            )}
        </div>
    );
};

// Render
const rootElement = document.getElementById('root');
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
