--!strict
local CorePackages = game:GetService("CorePackages")
local CoreGui = game:GetService("CoreGui")
local LocalizationService = game:GetService("LocalizationService")

local RobloxGui = CoreGui:WaitForChild("RobloxGui")

local renderWithCoreScriptsStyleProvider = require(script.Parent.Common.renderWithCoreScriptsStyleProvider)

local React = require(CorePackages.Packages.React)
local Rodux = require(CorePackages.Packages.Rodux)
local Roact = require(CorePackages.Packages.Roact)
local RoactRodux = require(CorePackages.Packages.RoactRodux)
local CallProtocol = require(CorePackages.Workspace.Packages.CallProtocol)

local Localization = require(CorePackages.Workspace.Packages.InExperienceLocales).Localization
local LocalizationProvider = require(CorePackages.Workspace.Packages.Localization).LocalizationProvider

local ApolloProvider = require(CorePackages.Packages.ApolloClient).ApolloProvider
local ApolloClient = require(RobloxGui.Modules.ApolloClient)

local initCall = require(script.initCall)
local Reducer = require(script.Reducer)
local ContactListApp = require(script.Components.ContactListApp)
local ContactListContext = require(script.Context)
local ContactListAnalytics = require(script.Analytics)

-- Screen should be beneath the in game menu
local CONTACT_LIST_DISPLAY_ORDER = -1

local ContactList = {}
ContactList.__index = ContactList

function ContactList.new()
	local self = setmetatable({}, ContactList)

	local AnalyticsFactory = ContactListAnalytics.Analytics()

	local defaultContextValues = {
		fireAnalyticsEvent = AnalyticsFactory.fireAnalyticsEvent,
	}

	-- Init call
	initCall(CallProtocol.CallProtocol.default :: CallProtocol.CallProtocolModule)

	local renderLocalizationProvider = function(element)
		return React.createElement(LocalizationProvider, {
			localization = Localization.new(LocalizationService.RobloxLocaleId),
		}, {
			App = element,
		})
	end

	-- Mount component
	self.store = Rodux.Store.new(Reducer, nil, {
		Rodux.thunkMiddleware,
	})
	self.root = React.createElement("ScreenGui", {
		AutoLocalize = false,
		DisplayOrder = CONTACT_LIST_DISPLAY_ORDER,
		IgnoreGuiInset = true,
		ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
	}, {
		Content = React.createElement(RoactRodux.StoreProvider, {
			store = self.store,
		}, {
			ThemeProvider = renderWithCoreScriptsStyleProvider({
				ApolloProvider = React.createElement(ApolloProvider, {
					client = ApolloClient,
				}, {
					ContextProvider = Roact.createElement(ContactListContext.Provider, {
						value = defaultContextValues,
					}, {
						ContactListApp = renderLocalizationProvider(React.createElement(ContactListApp)),
					}),
				}),
			}),
		}),
	})

	self.element = Roact.mount(self.root, CoreGui, "ContactList")

	return self
end

return ContactList.new()
