import React from 'react';
import MenuItem from './MenuItem';
import { block } from 'bem-cn';

const bHeader = block('header');

import './LogoMenu.css';

export default class extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            visible: props.initialVisible || false
        };

        this._initButton = this._initButton.bind(this);
        this._initPopup = this._initPopup.bind(this);

        this._onButtonClick = this._onButtonClick.bind(this);
        this._onOutsideClick = this._onOutsideClick.bind(this);
    }

    componentDidMount() {
        document.body.addEventListener('click', this._onOutsideClick);
    }

    componentWillUnmount() {
        document.body.removeEventListener('click', this._onOutsideClick);
    }

    _initPopup(element) {
        if (!this._popup) {
            this._popup = element;
        }
    }

    _initButton(element) {
        if (!this._button) {
            this._button = element;
        }
    }

    _onButtonClick() {
        this.setState({
            visible: !this.state.visible
        });
    }

    _onOutsideClick({ target }) {
        let isPopupClick = this._popup && this._popup.contains(target);
        let isButtonClick = this._button && this._button.contains(target);

        if (!isPopupClick && !isButtonClick) {
            this.setState({
                visible: false
            });
        }
    }

    render() {
        let { visible } = this.state;
        let { items } = this.props;

        return (
            <div className={bHeader('logo-menu', {
                active: visible,
                empty: !items || !items.length
            })}>
                <div
                    className={bHeader('logo-menu-button')}
                    onClick={this._onButtonClick}
                    ref={this._initButton}
                />
                {Boolean(items && items.length) &&
                <div
                    className={bHeader('logo-menu-popup')}
                    ref={this._initPopup}
                >
                    <div className={bHeader('logo-menu-scrollpane')}>
                        <div className={bHeader('logo-menu-content')}>
                            {items.map(item => <LogoMenuItem {...item} key={item.slug}/>)}
                        </div>
                    </div>
                </div>}
            </div>
        );
    }
}

const LogoMenuItem = ({ slug, url, icon, name, onClick }) => (
    <MenuItem
        cls={bHeader('logo-menu-item')}
        url={url}
        onClick={onClick}
        id={slug}
    >
        <span
            className={bHeader('logo-menu-item-image')}
            style={icon ? { backgroundImage: `url(${icon})` } : null}
        />
        <span className={bHeader('logo-menu-item-caption')}>
            {name}
        </span>
    </MenuItem>
);
