
// Log ASCII welcome message
console.log(CONST.ASCII);

// Helper classes
globalThis.Hooks = Hooks;
globalThis.TextEditor = TextEditor;
globalThis.SortingHelpers = SortingHelpers;

// Default Document sheet registrations
DocumentSheetConfig._registerDefaultSheets();

/**
 * Once the Window has loaded, created and initialize the Game object
 */
window.addEventListener("DOMContentLoaded", async function() {

  // Get the current URL
  const url = new URL(window.location.href);
  const view = url.pathname.split("/").pop();

  // Establish a session
  const cookies = Game.getCookies();
  const sessionId = cookies.session ?? null;
  if ( !sessionId ) return window.location.href = foundry.utils.getRoute("join");
  console.log(`${vtt} | Reestablishing existing session ${sessionId}`);

  // Initialize the asset loader
  const routePrefix = globalThis.ROUTE_PREFIX?.replace(/(^[/]+)|([/]+$)/g, "");
  const basePath = routePrefix ? `${window.location.origin}/${routePrefix}` : window.location.origin;
  await PIXI.Assets.init({basePath, preferences: {defaultAutoPlay: false}});

  // Create the master Game controller
  if ( CONST.SETUP_VIEWS.includes(view) ) game = globalThis.game = await Setup.create(view, sessionId);
  else if ( CONST.GAME_VIEWS.includes(view) ) game = globalThis.game = await Game.create(view, sessionId);
  return globalThis.game.initialize();
}, {once: true, passive: true});

// FIXME: This is a temporary solution to make all client classes appear in the generated API docs.
// Remove once we have moved everything to client-esm. Generated by:
//     console.log(await fetch("/scripts/foundry.js")
//       .then(response => response.text())
//       .then(data => `/**\n * @typedef {${[...data.matchAll(/^class\s+(\w+)\b/mg)].map(m => m[1]).sort().join("|")}} _client\n */`))
/**
 * @typedef {AVClient|AVConfig|AVMaster|AVSettings|AbstractBaseFilter|AbstractBaseMaskFilter|AbstractBaseShader|AbstractDarknessLevelRegionShader|AbstractWeatherShader|ActiveEffect|ActiveEffectConfig|Actor|ActorDelta|ActorDirectory|ActorSheet|Actors|AdaptiveBackgroundShader|AdaptiveColorationShader|AdaptiveDarknessShader|AdaptiveIlluminationShader|AdaptiveLightingShader|AdaptiveVisionShader|AdjustDarknessLevelRegionShader|Adventure|AdventureExporter|AdventureImporter|AlertPing|AlphaBlurFilter|AlphaBlurFilterPass|AmbientLight|AmbientLightDocument|AmbientSound|AmbientSoundDocument|AmplificationBackgroundVisionShader|AmplificationSamplerShader|Application|ArrowPing|AsyncWorker|AutumnLeavesWeatherEffect|BackgroundVisionShader|BasePlaceableHUD|BaseSamplerShader|BaseSheet|BaselineIlluminationSamplerShader|BatchRenderer|BatchShaderGenerator|BewitchingWaveColorationShader|BewitchingWaveIlluminationShader|BlackHoleDarknessShader|CachedContainer|CameraPopoutAppWrapper|CameraViews|Canvas|CanvasAnimation|CanvasBackgroundAlterationEffects|CanvasColorationEffects|CanvasDarknessEffects|CanvasDepthMask|CanvasIlluminationEffects|CanvasLayer|CanvasOcclusionMask|CanvasQuadtree|CanvasTour|CanvasVisibility|CanvasVisionMask|Card|CardConfig|CardStacks|Cards|CardsConfig|CardsDirectory|CardsHand|CardsPile|ChatBubbles|ChatLog|ChatMessage|ChatPopout|ChevronPing|ChromaColorationShader|ClientIssues|ClientKeybindings|ClientSettings|ClipboardHelper|ClockwiseSweepPolygon|ColorAdjustmentsSamplerShader|ColorationVisionShader|Combat|CombatEncounters|CombatTracker|CombatTrackerConfig|Combatant|CombatantConfig|Compendium|CompendiumCollection|CompendiumDirectory|CompendiumFolderCollection|CompendiumPacks|ContextMenu|ControlIcon|ControlsLayer|Cursor|DarknessLevelContainer|DefaultSheetsConfig|DefaultTokenConfig|DependencyResolution|DepthSamplerShader|DetectionMode|DetectionModeAll|DetectionModeBasicSight|DetectionModeInvisibility|DetectionModeLightPerception|DetectionModeTremor|Dialog|DiceConfig|DocumentCollection|DocumentDirectory|DocumentIndex|DocumentOwnershipConfig|DocumentSheet|DocumentSheetConfig|DoorControl|DragDrop|Draggable|Drawing|DrawingConfig|DrawingDocument|DrawingHUD|DrawingsLayer|EffectsCanvasGroup|EmanationColorationShader|EnergyFieldColorationShader|EnvironmentCanvasGroup|FairyLightColorationShader|FairyLightIlluminationShader|FilePicker|FlameColorationShader|FlameIlluminationShader|FogColorationShader|FogExploration|FogExplorations|FogManager|FogSamplerShader|FogShader|Folder|FolderConfig|FolderExport|Folders|FontConfig|ForceGridColorationShader|FormApplication|FormDataExtended|FrameViewer|FramebufferSnapshot|FullCanvasContainer|Game|GameTime|GamepadManager|GhostLightColorationShader|GhostLightIlluminationShader|GlowOverlayFilter|GridConfig|GridHighlight|GridLayer|GridMesh|GridShader|HTMLSecret|HandlebarsHelpers|HeadsUpDisplay|HexaDomeColorationShader|HiddenCanvasGroup|HighlightRegionShader|Hooks|Hotbar|IlluminationDarknessLevelRegionShader|IlluminationVisionShader|ImageHelper|ImagePopout|InteractionLayer|InterfaceCanvasGroup|InvisibilityFilter|InvitationLinks|Item|ItemDirectory|ItemSheet|Items|Journal|JournalDirectory|JournalEntry|JournalEntryPage|JournalImagePageSheet|JournalPDFPageSheet|JournalPageSheet|JournalSheet|JournalTextPageSheet|JournalTextTinyMCESheet|JournalVideoPageSheet|KeybindingsConfig|KeyboardManager|LightDomeColorationShader|LightingLayer|LimitedAnglePolygon|Localization|Macro|MacroConfig|MacroDirectory|Macros|MagicalGloomDarknessShader|MainMenu|MarkdownJournalPageSheet|MeasuredTemplate|MeasuredTemplateConfig|MeasuredTemplateDocument|Messages|Module|ModuleManagement|MouseInteractionManager|MouseManager|NewUserExperience|Note|NoteConfig|NoteDocument|NotesLayer|Notifications|ObservableTransform|OccludableSamplerShader|OutlineOverlayFilter|OverlayCanvasGroup|PackageConfiguration|ParticleEffect|Pause|PerceptionManager|Ping|PlaceableObject|PlaceablesLayer|PlayerList|Playlist|PlaylistConfig|PlaylistDirectory|PlaylistSound|PlaylistSoundConfig|Playlists|PointSourceMesh|PointSourcePolygon|PolygonMesher|PreciseText|PrimaryBaseSamplerShader|PrimaryCanvasGroup|PrimaryCanvasGroupAmbienceFilter|PrimaryGraphics|PrimarySpriteMesh|ProseMirrorEditor|PulseColorationShader|PulseIlluminationShader|PulsePing|QuadMesh|Quadtree|RadialRainbowColorationShader|RainShader|Ray|Region|RegionBehavior|RegionDocument|RegionLayer|RegionShader|RenderFlags|RenderedCanvasGroup|ResizeHandle|RevolvingColorationShader|RoilingDarknessShader|RollTable|RollTableConfig|RollTableDirectory|RollTables|Ruler|Scene|SceneConfig|SceneControls|SceneDirectory|SceneNavigation|Scenes|SearchFilter|Setting|Settings|SettingsConfig|SetupTour|ShaderField|Sidebar|SidebarTab|SidebarTour|SimplePeerAVClient|SirenColorationShader|SirenIlluminationShader|SmokePatchColorationShader|SmokePatchIlluminationShader|SmoothNoise|SnowShader|SocketInterface|SortingHelpers|SoundsLayer|SpriteMesh|StarLightColorationShader|SunburstColorationShader|SunburstIlluminationShader|SupportDetails|SwirlingRainbowColorationShader|System|TableResult|Tabs|TemplateLayer|TextEditor|TextureCompressor|TextureExtractor|TextureLoader|TextureTransitionFilter|Tile|TileConfig|TileDocument|TileHUD|TilesLayer|Token|TokenConfig|TokenDocument|TokenHUD|TokenLayer|TokenRingSamplerShader|TooltipManager|TorchColorationShader|TorchIlluminationShader|Tour|Tours|ToursManagement|UnboundContainer|UnboundTransform|User|UserTargets|Users|VideoHelper|VisibilityFilter|VisionMaskFilter|VisionMode|VisualEffectsMaskingFilter|VoidFilter|VortexColorationShader|VortexIlluminationShader|Wall|WallConfig|WallDocument|WallsLayer|WaveBackgroundVisionShader|WaveColorationShader|WaveColorationVisionShader|WaveIlluminationShader|WeatherEffects|WeatherOcclusionMaskFilter|WeatherShaderEffect|WeilerAthertonClipper|WorkerManager|World|WorldCollection|WorldConfig|WorldSettings} _client
 */
