var MemoryRouter = ReactRouterDOM.MemoryRouter;
var Routes       = ReactRouterDOM.Routes;
var Route        = ReactRouterDOM.Route;
var createRoot   = ReactDOM.createRoot;
var _useEffect_App  = React.useEffect;
var _useRef_App     = React.useRef;

// Route → page title map for GA4 virtual page views
var ROUTE_TITLES = {
    '/':                    'Home',
    '/analysis':            'Scan',
    '/scans':               'Scan History',
    '/reports':             'Reports',
    '/location-details':    'Location Details',
    '/faq':                 'FAQ',
    '/miss-mould':          'Miss Mould',
    '/edu':                 'Mould Edu',
    '/about':               'About Us',
    '/privacy':             'Privacy & Terms',
    '/specialists':         'Find a Professional',
};

function _getPageTitle(pathname) {
    if (ROUTE_TITLES[pathname]) return ROUTE_TITLES[pathname];
    if (pathname.indexOf('/specialists/') === 0 && pathname.split('/').length === 3) return 'Specialist Profile';
    if (pathname.indexOf('/specialists/') === 0 && pathname.indexOf('/contact') !== -1) return 'Contact Professional';
    return pathname;
}

// Inner component that has access to MemoryRouter location
var RouteTracker = function () {
    var location = ReactRouterDOM.useLocation();
    var prevPath = _useRef_App(null);

    _useEffect_App(function () {
        var path = location.pathname;
        // Only fire on genuine route changes
        if (path === prevPath.current) return;
        prevPath.current = path;
        AnalyticsService.pageView(path, _getPageTitle(path));
    }, [location.pathname]);

    return null;
};

var AppRoutes = function () {
    var store = useScanStore();

    if (store.loading) {
        return (
            <div className="max-w-md mx-auto h-[100dvh] flex flex-col items-center justify-center gap-4">
                <div className="w-12 h-12 rounded-full border-4 border-primary/20 border-t-primary animate-spin"></div>
                <p className="text-sm text-muted font-medium">Loading your data...</p>
            </div>
        );
    }

    return (
        <Routes>
            <Route path="/"                          element={<HomePage />} />
            <Route path="/scans"                     element={<ScansPage />} />
            <Route path="/reports"                   element={<ReportsPage />} />
            <Route path="/analysis"                  element={<AnalysisPage />} />
            <Route path="/location-details"          element={<LocationDetails />} />
            <Route path="/scan/:id"                  element={<ScanDetails />} />
            <Route path="/faq"                       element={<MouldFAQ />} />
            {/* Miss Mould unmounts on navigation, which is how its microphone, AudioContext
                and audio buffers get released — see the unmount effect in MissMouldChat. */}
            <Route path="/miss-mould"                element={<MissMouldChat />} />
            <Route path="/edu"                       element={<MouldEdu />} />
            <Route path="/about"                     element={<AboutPage />} />
            <Route path="/privacy"                   element={<PrivacyPolicyPage />} />
            <Route path="/specialists"               element={<SpecialistDirectoryPage />} />
            <Route path="/specialists/:id"           element={<SpecialistProfilePage />} />
            <Route path="/specialists/:id/contact"   element={<ContactSpecialistPage />} />
        </Routes>
    );
};

var App = function () {
    return (
        <ErrorBoundary>
            <ClerkProvider>
                <ScanProvider>
                    <MemoryRouter>
                        <RouteTracker />
                        <AppRoutes />
                    </MemoryRouter>
                </ScanProvider>
            </ClerkProvider>
        </ErrorBoundary>
    );
};

var root = createRoot(document.getElementById('root'));

/**
 * Boot sequence — AI engine pre-loading via AIEngineAdapter.
 *
 * Reads AI_ENGINE flag value and pre-loads models accordingly:
 *   'local'  → LocalCNNService.load()              (full on-device pipeline)
 *   'hybrid' → LocalCNNEnrichmentService.loadForEnrichment()  (enrichment only)
 *   others   → no pre-load needed (cloud APIs)
 *
 * window.__aiEngineStatus is set after boot for diagnostic use:
 *   { active: 'local_cnn' | 'hybrid' | 'cloud_ai' | 'nyckel' | 'none', reason: string }
 */
function _logEngineStatus(active, reason) {
    window.__aiEngineStatus = { active: active, reason: reason };
    console.info('[AI Engine] Active engine:', active, '|', reason);
}

function _preloadEngines() {
    var aiEngine = FeatureFlags.getValue('AI_ENGINE') || 'nyckel';

    if (aiEngine === 'hybrid') {
        console.info('[AI Engine] HYBRID mode — pre-loading Local CNN enrichment models...');
        return LocalCNNEnrichmentService.loadForEnrichment(function (msg) {
            var splashMsg = document.getElementById('splash-msg');
            if (splashMsg) { splashMsg.textContent = msg; }
        })
        .then(function () {
            _logEngineStatus('hybrid', 'Nyckel + Local CNN enrichment models loaded.');
            return false;
        })
        ['catch'](function (err) {
            console.warn('[AI Engine] Hybrid enrichment pre-load failed — Nyckel will run without enrichment:', err.message);
            return false;
        });
    }

    if (aiEngine === 'local') {
        console.info('[AI Engine] LOCAL mode — pre-loading full Local CNN pipeline...');
        return LocalCNNService.load(function (msg) {
            var splashMsg = document.getElementById('splash-msg');
            if (splashMsg) { splashMsg.textContent = msg; }
        })
        .then(function () {
            _logEngineStatus('local_cnn', 'On-device TF.js model loaded and warmed up during splash.');
            return true;
        })
        ['catch'](function (err) {
            console.error('[AI Engine] LOCAL_CNN pre-load failed:', err.message);
            return false;
        });
    }

    // cloud / nyckel / none — no pre-load needed
    console.info('[AI Engine] AI_ENGINE=' + aiEngine + '. No model pre-load required.');
    return Promise.resolve(false);
}

function _resolveActiveEngine(localCNNLoaded) {
    if (localCNNLoaded) return; // local_cnn already logged in _preloadEngines

    var aiEngine = FeatureFlags.getValue('AI_ENGINE') || 'nyckel';

    if (aiEngine === 'cloud') {
        _logEngineStatus('cloud_ai', 'AI_ENGINE=cloud. Bespoke cloud CNN selected (falls through to Nyckel until implemented).');
        return;
    }
    if (aiEngine === 'hybrid') {
        _logEngineStatus('hybrid', 'AI_ENGINE=hybrid. Nyckel verdict + Local CNN enrichment active.');
        return;
    }
    if (aiEngine === 'nyckel') {
        _logEngineStatus('nyckel', 'AI_ENGINE=nyckel. Nyckel API active.');
        return;
    }
    if (aiEngine === 'none') {
        _logEngineStatus('none', 'AI_ENGINE=none. All engines disabled.');
        return;
    }
    _logEngineStatus('none', 'AI_ENGINE value unrecognised: ' + aiEngine);
    console.warn('[AI Engine] Unrecognised AI_ENGINE value:', aiEngine);
}

// Boot: init flags → pre-load engines in parallel with splash → render app
FeatureFlags.init()
    .then(function () {
        return _preloadEngines();
    })
    .then(function (localCNNLoaded) {
        _resolveActiveEngine(localCNNLoaded);
        var activeEngine = (window.__aiEngineStatus && window.__aiEngineStatus.active) || 'unknown';
        AnalyticsService.init({ aiEngine: activeEngine, userType: 'guest' });
        root.render(<App />);
    })
    ['catch'](function (err) {
        console.error('[Boot] FeatureFlags.init() failed:', err.message, '— rendering with flag defaults.');
        _logEngineStatus('nyckel', 'FeatureFlags failed to load. Defaulting to Nyckel.');
        root.render(<App />);
    });
