/*
    Предрейсовые осмотры - мобильное приложение
    Хук навигации приложения
*/

//---------------------
//Подключение библиотек
//---------------------

const React = require('react'); //React и хуки
const { SCREENS } = require('../config/routes'); //Экраны навигации

//-----------
//Тело модуля
//-----------

//Хук навигации приложения
const useAppNavigation = () => {
    //Начальный экран - AUTH (до определения статуса авторизации)
    const [navigationState, setNavigationState] = React.useState({
        currentScreen: SCREENS.AUTH,
        screenParams: {},
        history: [SCREENS.AUTH]
    });

    //Навигация на экран
    const navigate = React.useCallback((screen, params = {}) => {
        setNavigationState(prev => ({
            currentScreen: screen,
            screenParams: params,
            history: [...prev.history, screen]
        }));
    }, []);

    //Возврат назад
    const goBack = React.useCallback(() => {
        setNavigationState(prev => {
            if (prev.history.length <= 1) {
                return prev;
            }

            const newHistory = [...prev.history];
            newHistory.pop();
            const previousScreen = newHistory[newHistory.length - 1];

            return {
                currentScreen: previousScreen,
                screenParams: {},
                history: newHistory
            };
        });
    }, []);

    //Сброс навигации
    const reset = React.useCallback(() => {
        setNavigationState({
            currentScreen: SCREENS.MAIN,
            screenParams: {},
            history: [SCREENS.MAIN]
        });
    }, []);

    //Установка начального экрана (без добавления в историю)
    const setInitialScreen = React.useCallback((screen, params = {}) => {
        setNavigationState({
            currentScreen: screen,
            screenParams: params,
            history: [screen]
        });
    }, []);

    return {
        SCREENS,
        currentScreen: navigationState.currentScreen,
        screenParams: navigationState.screenParams,
        navigate,
        goBack,
        reset,
        setInitialScreen,
        canGoBack: navigationState.history.length > 1
    };
};

//----------------
//Интерфейс модуля
//----------------

module.exports = useAppNavigation;
