import React from 'react';
import './style.less';

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

    this.$refs = {
      iframe: React.createRef(),
    };

    this.state = {
      scrollTop: window.scrollY,
      windowHeight: window.innerHeight,
    };
  }

  get isFixed() {
    return this.state.scrollTop > 60;
  }

  get simulatorStyle() {
    const height = Math.min(640, this.state.windowHeight - 90);
    return {
      height: height + 'px',
    };
  }

  componentDidMount() {
    window.addEventListener('scroll', () => {
      this.setState({
        scrollTop: window.scrollY,
      });
    });
    window.addEventListener('resize', () => {
      this.setState({
        windowHeight: window.innerHeight,
      });
    });

    const iframeWindow = this.$refs.iframe.current.contentWindow;
    if (!iframeWindow) return;

    iframeWindow.addEventListener('hashchange', (event) => {
      window.location.hash = event.newURL.split("/mobile.html")[1];
    })
  }

  render() {
    const { src } = this.props;

    return (
      <div className={this.isFixed ? 'wgoo-doc-simulator wgoo-doc-simulator-fixed' : 'wgoo-doc-simulator'}>
        <iframe ref={this.$refs.iframe} src={src} style={this.simulatorStyle} frameBorder='0' />
      </div>
    );
  }
}

export default Simulator;
