

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withHashLocation } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideZonelessChangeDetection, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './src/app.component';
import { APP_ROUTES } from './src/app.routes';
import { authInterceptor } from './src/interceptors/auth.interceptor';
import { AuthService } from './src/services/auth.service';
import { UserService } from './src/services/user.service';
import type { UserPreferences } from './src/services/user.service';
import { InstanceService } from './src/services/instance.service';
import { firstValueFrom } from 'rxjs';

function applyTheme(theme?: string | null) {
  const t = theme || 'system';
  try {
    document.documentElement.setAttribute('data-theme', t);
  } catch {}
}

function appInitializerFactory(auth: AuthService, user: UserService, instances: InstanceService) {
  return async () => {
    try {
      // Attempt refresh on startup (if cookies present)
      const ok = await firstValueFrom(auth.refresh());
      if (ok) {
        // Load user profile for header greeting
        try {
          const me = await firstValueFrom(user.loadMe());
          if (me) auth.setCurrentUser(me);
        } catch {}
        const prefs: UserPreferences = await firstValueFrom(user.loadPreferences());
        if (prefs) {
          if (prefs.defaultProvider) instances.setSelectedProvider(prefs.defaultProvider as any);
          if (prefs.region) instances.setRegion(prefs.region);
          applyTheme(prefs.theme);
        }
      }
    } catch {}
  };
}

bootstrapApplication(AppComponent, {
  providers: [
    provideZonelessChangeDetection(),
    provideRouter(APP_ROUTES, withHashLocation()),
    provideHttpClient(withInterceptors([authInterceptor])),
    { provide: APP_INITIALIZER, useFactory: appInitializerFactory, deps: [AuthService, UserService, InstanceService], multi: true },
  ],
}).catch((err) => console.error(err));

// AI Studio always uses an `index.tsx` file for all project types.