const CRMApp = () => {
    const [currentUser, setCurrentUser] = React.useState(null);
    const [authChecking, setAuthChecking] = React.useState(true);
    // Environment ribbon ("STAGING") — served by /api/health when the box
    // sets INSTANCE_LABEL. Rendered on login AND in-app: the whole point is
    // that no screen in a labeled environment can pass for production.
    const [instanceLabel, setInstanceLabel] = React.useState(null);
    // Deployed version from the same health probe — shown in the top nav so
    // "what version are you on?" never needs a trip to the What's New modal.
    const [appVersion, setAppVersion] = React.useState(null);

    React.useEffect(() => {
        fetch('/api/health')
            .then(r => r.json())
            .then(h => {
                setInstanceLabel(h.instance_label || null);
                setAppVersion(h.version || null);
            })
            .catch(() => {}); // no label is the normal case, never an error
    }, []);

    React.useEffect(() => {
        const token = getToken();
        if (!token) { setAuthChecking(false); return; }
        api.me()
            .then(data => { setCurrentUser(data.user); })
            .catch(() => { clearToken(); })
            .finally(() => setAuthChecking(false));
    }, []);

    const handleLogin  = (user) => setCurrentUser(user);
    const handleLogout = () => { clearToken(); setCurrentUser(null); };

    if (authChecking) {
        return (
            <div className="login-screen">
                <div style={{ color: 'white', fontSize: '1rem', display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                    <i className="fas fa-spinner fa-spin"></i> Loading…
                </div>
            </div>
        );
    }

    const ribbon = instanceLabel ? <div className="instance-ribbon">{instanceLabel}</div> : null;

    if (!currentUser) return <>{ribbon}<LoginScreen onLogin={handleLogin} /></>;

    return <>{ribbon}<MainApp currentUser={currentUser} onLogout={handleLogout} appVersion={appVersion} /></>;
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(CRMApp));
