const { connect } = require('preact-redux');
const preact = require('preact');

const actions = require('../actions');

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            account,
            nav,
        } = state;

        function sendInstanceState(instance) {
            return ws.sendInstanceState(instance.id);
        }

        function sendAccountStates() {
            ws.sendEmailState();
            ws.sendSubscriptionState();
        }

        return {
            account,
            nav,

            sendInstanceState,
            sendAccountStates,
        };
    },
    function receiveDispatch(dispatch) {
        function setNav(place) {
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
            dispatch(actions.setCombiner([]));
            dispatch(actions.setReclaiming(false));
            dispatch(actions.setActiveSkill(null));
            dispatch(actions.setActiveConstruct(null));
            dispatch(actions.setInfo(null));
            dispatch(actions.setItemEquip(null));
            dispatch(actions.setItemUnequip([]));
            dispatch(actions.setVboxHighlight([]));

            return dispatch(actions.setNav(place));
        }

        return {
            setNav,
        };
    }
);

function Header(args) {
    const {
        account,
        nav,

        sendAccountStates,
        setNav,
    } = args;

    if (!account) return false;

    function navTo(p) {
        return setNav(p);
    }

    function accountClick() {
        sendAccountStates();
        navTo('account');
    }

    return (
        <header>
            <div class="options">
                <button
                    onClick={() => navTo('play')}
                    class={`login-btn ${nav === 'play' ? 'highlight' : ''}`}>
                    MNML
                </button>
                <button
                    onClick={() => navTo('shop')}
                    class={`login-btn ${nav === 'shop' ? 'highlight' : ''}`}>
                    Shop
                </button>
                <button
                    onClick={accountClick}
                    class={`login-btn ${nav === 'account' ? 'highlight' : ''}`}>
                    ⚙ {account.name}
                </button>
            </div>
        </header>
    );
}

module.exports = addState(Header);