const preact = require('preact');

const VboxContainer = require('./vbox.container');
const InfoContainer = require('./info.container');
const InstanceCrypsContainer = require('./instance.cryps');
const EquipmentContainer = require('./instance.equip');

function InstanceComponent(args) {
    const {
        instance,
        player,
        quit,
        sendInstanceReady,

        vboxHidden,
        setVboxHidden,
    } = args;

    if (!instance) return <div>...</div>;

    function toggleVbox(e) {
        setVboxHidden(!vboxHidden);
        e.stopPropagation();
    }

    const vboxBtn = (
        <button
            className="instance-btn instance-ui-btn nav-btn left"
            onClick={toggleVbox}>
            vBox
        </button>
    );

    const teamBtn = (
        <button
            className="instance-btn instance-ui-btn nav-btn right"
            onClick={toggleVbox}>
            team
        </button>
    );

    const navBtn = vboxHidden
        ? vboxBtn
        : teamBtn;

    const menuBtn = (
        <button
            className="instance-btn instance-ui-btn menu-btn left"
            onClick={quit}>
            menu
        </button>
    );

    const rdyClasses = `instance-btn instance-ui-btn ready-btn ${player.ready ? 'ready' : ''}`;
    const readyBtn = (
        <button
            className={rdyClasses}
            onClick={() => sendInstanceReady()}>
            Ready
        </button>
    );

    const actionBtn = player
        ? readyBtn
        : null;

    // TIMER
    const zero = Date.parse(instance.phase_end) - (1000 * 120);
    const now = Date.now();
    const end = Date.parse(instance.phase_end);
    const timerPct = ((now - zero) / (end - zero) * 100);
    const timerStyles = {
        width: `${timerPct < 100 ? timerPct : 0}%`,
        background: player.ready ? 'forestgreen' : 'whitesmoke',
    };

    const timer = (
        <div className="timer-container">
            <div className="timer" style={timerStyles} >&nbsp;</div>
        </div>
    );

    return (
        <section className="instance" >
            <div className="instance-hdr">
                {navBtn}
                {menuBtn}
                <div className="spacer">
                    <div>&nbsp;</div>
                </div>
                {actionBtn}
                {timer}
            </div>
            <VboxContainer />
            <InstanceCrypsContainer />
            <EquipmentContainer />
            <InfoContainer />
        </section>
    );
}

module.exports = InstanceComponent;
