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

const actions = require('../actions');
const AccountStatus = require('./account.status');

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            account,
            instances,
            team,
            ping,

            game,
        } = state;

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

        return {
            account,
            instances,
            team,
            game,
            ping,
            sendInstanceState,
        };
    },
    function receiveDispatch(dispatch) {
        function setNav(place) {
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
            dispatch(actions.setReclaiming(false));
            dispatch(actions.setActiveSkill(null));
            dispatch(actions.setInfo(null));
            dispatch(actions.setItemUnequip([]));
            dispatch(actions.setVboxHighlight([]));

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

        function hideNav() {
            return dispatch(actions.setShowNav(false));
        }

        return {
            setNav,
            hideNav,
        };
    }
);

function Nav(args) {
    const {
        account,
        instances,
        game,
        team,

        sendInstanceState,

        setNav,
        hideNav,
    } = args;

    if (!account) return false;

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

    function joinInstance(i) {
        sendInstanceState(i);
        if (game) navTo('transition');
        return true;
    }

    const joined = instances.map(i => {
        const score = i.players.find(p => p.id === account.id);
        const phase = i.phase === 'Lobby'
            ? 'Lobby' : i.rounds[i.rounds.length - 1].game_id
                ? 'In game'
                : 'Vbox';
        return <button key={i.id} onClick={() => joinInstance(i)} >{`${phase} ${score.wins} / ${score.losses}`}</button>
    });

    const canJoin = team.some(c => !c);

    return (
        <nav onClick={hideNav} >
            <h1 class="header-title">mnml.gg</h1>
            <AccountStatus />
            <hr />
            <button class="play-btn" disabled={canJoin} onClick={() => navTo('play')}>Play</button>
            <hr />
            {joined}
        </nav>
    );
}

module.exports = addState(Nav);
