export const initialAppState = {
  accounts: [],
  workspaces: [],
  accountId: "",
  workspaceId: "",
  session: null,
  chatTransition: null,
  tab: "threads",
  settingsReturnTab: null,
  newChatOpen: false,
  contextLoaded: false,
  bootStatus: "loading",
  error: ""
};

export function reduceAppState(state, action) {
  if (action.type === "bootstrap.ready") return { ...state, bootStatus: "ready" };
  if (action.type === "chat.transition.started") return {
    ...state,
    tab: "chat",
    newChatOpen: false,
    chatTransition: { requestId: action.requestId, status: "loading", label: action.label, target: action.target, error: "" }
  };
  if (action.type === "chat.transition.failed") {
    if (state.chatTransition?.requestId !== action.requestId) return state;
    return { ...state, chatTransition: { ...state.chatTransition, status: "failed", error: action.error } };
  }
  if (action.type === "chat.transition.canceled") return state.tab === "settings"
    ? { ...state, settingsReturnTab: "threads", chatTransition: null }
    : { ...state, tab: "threads", chatTransition: null };
  if (action.type === "context.loaded") {
    const initialContext = resolveInitialContext(action);
    return {
      ...state,
      accounts: action.accounts,
      workspaces: action.workspaces,
      accountId: initialContext.accountId,
      workspaceId: initialContext.workspaceId,
      contextLoaded: true,
      error: action.error || ""
    };
  }
  if (action.type === "session.opened") {
    if (action.requestId != null && state.chatTransition?.requestId !== action.requestId) return state;
    return {
      ...state,
      session: action.session,
      chatTransition: null,
      workspaceId: action.session.workspaceId || "",
      tab: action.reveal || state.tab !== "settings" ? "chat" : "settings",
      settingsReturnTab: action.reveal ? null : state.settingsReturnTab,
      newChatOpen: false
    };
  }
  if (action.type === "session.restored") {
    if (action.restoreSessionId && state.session?.id && state.session.id !== action.restoreSessionId) return state;
    return {
      ...state,
      session: action.session,
      workspaceId: action.session.workspaceId || "",
      tab: state.tab === "settings" ? "settings" : action.tab === "chat" ? "chat" : action.tab === "new" ? "threads" : state.tab,
      newChatOpen: state.tab === "settings" ? state.newChatOpen : action.tab === "new"
    };
  }
  if (action.type === "session.restore.failed" && action.restoreSessionId && state.session?.id && state.session.id !== action.restoreSessionId) return state;
  if (action.type === "session.restore.failed") return state.tab === "settings"
    ? { ...state, session: null, chatTransition: null, settingsReturnTab: "threads" }
    : { ...state, session: null, chatTransition: null, tab: "threads" };
  if (action.type === "account.selected") return { ...state, accountId: action.accountId };
  if (action.type === "accounts.replaced") {
    const preferredId = action.preferredId;
    const nextId = preferredId && action.accounts.some((item) => item.id === preferredId)
      ? preferredId
      : action.accounts.some((item) => item.id === state.accountId)
        ? state.accountId
        : action.accounts[0]?.id ?? "";
    return { ...state, accounts: action.accounts, accountId: nextId };
  }
  if (action.type === "workspaces.replaced") {
    const preferredId = action.preferredId;
    const nextId = preferredId && action.workspaces.some((item) => item.id === preferredId)
      ? preferredId
      : action.workspaces.some((item) => item.id === state.workspaceId)
        ? state.workspaceId
        : action.workspaces[0]?.id ?? "";
    return { ...state, workspaces: action.workspaces, workspaceId: nextId };
  }
  if (action.type === "workspace.selected") return { ...state, workspaceId: action.workspaceId };
  if (action.type === "new-chat.selected") return { ...state, tab: "threads", newChatOpen: true };
  if (action.type === "new-chat.dismissed") return { ...state, newChatOpen: false };
  if (action.type === "settings.opened") {
    if (state.tab === "settings") return state;
    return { ...state, tab: "settings", settingsReturnTab: state.tab };
  }
  if (action.type === "settings.dismissed") {
    const returnTab = state.settingsReturnTab && state.settingsReturnTab !== "settings"
      ? state.settingsReturnTab
      : "threads";
    return { ...state, tab: returnTab, settingsReturnTab: null };
  }
  if (action.type === "view.restored") return state.tab === "settings"
    ? state
    : action.tab === "new"
    ? { ...state, tab: "threads", newChatOpen: true }
    : { ...state, tab: action.tab === "settings" ? "settings" : "threads", settingsReturnTab: action.tab === "settings" ? "threads" : null, newChatOpen: false };
  if (action.type === "tab.selected") return { ...state, tab: action.tab, settingsReturnTab: null, newChatOpen: false };
  if (action.type === "session.updated") return { ...state, session: action.session, workspaceId: action.session.workspaceId || state.workspaceId };
  if (action.type === "context.failed") return { ...state, bootStatus: "ready", error: action.error };
  return state;
}

export function resolveInitialContext({ accounts = [], workspaces = [], savedContext = null, accountsLoaded = true, workspacesLoaded = true }) {
  const accountId = !accountsLoaded
    ? savedContext?.accountId ?? ""
    : accounts.some((item) => item.id === savedContext?.accountId)
    ? savedContext.accountId
    : accounts[0]?.id ?? "";
  const workspaceId = !workspacesLoaded
    ? savedContext?.workspaceId ?? ""
    : workspaces.some((item) => item.id === savedContext?.workspaceId)
    ? savedContext.workspaceId
    : workspaces[0]?.id ?? "";
  return { accountId, workspaceId };
}
