// INSTANCE_LABEL drives a loud warning ribbon with exactly one job: no
// screen in a non-production environment can pass for the real thing. It is
// NOT a branding slot — a named instance's product identity (SPEC, DAEMON,
// CRM + acronym) lives in window.__PRODUCT__ / src/data/product.js and shows
// in Settings instead. Only labels that actually mean "this isn't
// production" render the ribbon; anything else (e.g. a box mislabeled with
// its product name) is silently ignored rather than drawing a false-alarm
// banner over real tenant data (found live 2026-08-19 on the SPEC instance).
const WARNING_LABELS = new Set(['STAGING']);

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 label = instanceLabel && WARNING_LABELS.has(instanceLabel) ? instanceLabel : null;
    const ribbon = label ? <div className="instance-ribbon">{label}</div> : null;

    const app = !currentUser
        ? <LoginScreen onLogin={handleLogin} />
        : <MainApp currentUser={currentUser} onLogout={handleLogout} appVersion={appVersion} />;

    // Full-width top strip, not the app content — a fixed-corner ribbon has
    // nowhere to sit that doesn't cross the topbar's Settings/Sign-out icons
    // (found live 2026-08-18: the ribbon was drawn right over "Sign out").
    if (!ribbon) return app;
    return (
        <div className="instance-shell">
            {ribbon}
            <div className="instance-body">{app}</div>
        </div>
    );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
// ConfirmHost is mounted beside the app, not inside it: confirmAction() is
// callable from any handler in any view (and from the login screen), so its
// dialog host must exist regardless of auth state.
root.render(React.createElement(React.Fragment, null,
    React.createElement(CRMApp),
    React.createElement(ConfirmHost)));
