import React from 'react';
import {Link, browserHistory} from "react-router";
import $  from "jquery";

let top = 60;

let DocSection = React.createClass({
  componentWillMount(){
    top = top + 20;
    this.setState({top: top});
  },
  componentDidMount(){
    window.addEventListener('scroll', this.handleScroll);
  },
  render() {
    let {children, title, id} = this.props;
    let {top, active} = this.state;
    let linkstyle = active ? {fontWeight: "bold", color: "red"} : null;
    return (
      <div {...this.props}>
        <h2>{title}</h2>
        {children}
        <div style={{position:"fixed",right:20,top:top}}>
          <a style={linkstyle} href={"#"+id}>{title}</a>
        </div>
      </div>
    );
  },
  componentWillUnmount(){
    window.removeEventListener('scroll', this.handleScroll);
    top = top - 20;
  },
  handleScroll: function (e) {
    let obj = $(`#${this.props.id}`);
    let top = obj.offset().top;
    let bottom = top + obj.height();
    let scolltop = $(window).scrollTop();
    if (scolltop >= top && scolltop <= bottom) {
      this.setState({active: true});
    } else {
      this.setState({active: false});
    }
  }
});

export default DocSection;
