class GetPrice extends React.Component {
  constructor(props) {
    super(props);
    this.state = { prices: [] };
  }

  componentDidMount() {
    const url = `${window.API_HOST}/api/price?coins=BTC,ETH,XRP,BNB,SOL,DOGE,ADA,TRX`;
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({ prices: data }))
      .catch(error => console.error('Error fetching prices:', error));
  }

  render() {
    return (
      <div className="header-price-box">
        {this.state.prices.map((p, index) => {
          const change = parseFloat(p.change_percentage);
          // const arrow = change > 0 ? '↑' : (change < 0 ? '↓' : '');
          const trendClass = change > 0 ? 'trend-positive' : (change < 0 ? 'trend-negative' : 'trend-neutral');
          return (
            <div className="header-price" key={index}>
              <div className="header-price-coin">{p.coin}</div>
              <div className="header-price-price"><b>${p.last}</b>
              <span className={`header-price-change ${trendClass}`}>
                {change > 0 ? '+' : ''}{change.toFixed(2)}%
              </span>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
}

function TrandContainer() {
  const containerRef = React.useRef(null);
  React.useEffect(() => {
    function reposition() {
      const container = containerRef.current;
      const pageTopMain = document.getElementById('reactTrandCoin');
      const asideTrands = document.querySelector('.trands');
      const currentParent = container.parentNode;

      if (window.innerWidth >= 990) {
        if (asideTrands && currentParent !== asideTrands) {
          asideTrands.appendChild(container);
        }
      } else {
        if (pageTopMain && currentParent !== pageTopMain) {
          pageTopMain.appendChild(container);
        }
      }
    }
    reposition();
    window.addEventListener('resize', reposition);
    return () => window.removeEventListener('resize', reposition);
  }, []);
  return <div id="trand-container" ref={containerRef}><TrandList /></div>;
}

class TrandList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { trands: { gainers: [], losses: [] } };
  }

  componentDidMount() {
    fetch(`${window.API_HOST}/api/trand`)
      .then(response => response.json())
      .then(data => this.setState({ trands: data }))
      .catch(error => console.error("Error fetching trand data:", error));
  }

  render() {
    const { gainers, losses } = this.state.trands;
    return (
      <div className="trands-container">
        <div className="trands-section">
          <b>🚀 Top Gainers</b>
          <ul className="trand-list">
            {gainers.map((item, index) => {
              const change = parseFloat(item.change_percentage);
              const arrow = change > 0 ? '↑' : (change < 0 ? '↓' : '');
              const trendClass = change > 0 ? 'trend-positive' : (change < 0 ? 'trend-negative' : 'trend-neutral');
              return (
                <li key={index} className="trand-item">
                  <span>{index+1}</span> 
                  <span>{item.coin}</span> 
                  <span>${item.last}</span> 
                  <span className={`trand-percent ${trendClass}`}>{item.change_percentage}%</span> 
                </li>
              );
            })}
          </ul>
        </div>
        <div className="trands-section">
          <b>🚨 Top Losers</b>
          <ul className="trand-list">
            {losses.map((item, index) => {
              const change = parseFloat(item.change_percentage);
              const arrow = change > 0 ? '↑' : (change < 0 ? '↓' : '');
              const trendClass = change > 0 ? 'trend-positive' : (change < 0 ? 'trend-negative' : 'trend-neutral');
              return (
                <li key={index} className="trand-item">
                  <span>{index+1}</span> 
                  <span>{item.coin}</span> 
                  <span>${item.last}</span> 
                  <span className={`trand-percent ${trendClass}`}>{item.change_percentage}%</span> 
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    );
  }
}

let trandMount = document.getElementById('trand-mount');
if (!trandMount) {
  trandMount = document.createElement('div');
  trandMount.id = 'trand-mount';
  document.body.appendChild(trandMount);
}

ReactDOM.render(<GetPrice />, document.getElementById('header-price'));
ReactDOM.render(<TrandContainer />, trandMount);
