import { useState, useEffect, useRef } from 'react';
import vis from 'vis-network/standalone/umd/vis-network.min';
import { API_URL } from '../config';

function GraphContainer({ vector }) {
  const [posts, setPosts] = useState([]);
  const networkRef = useRef(null);
  const containerRef = useRef(null);

  useEffect(() => {
    const loadTree = async () => {
      try {
        const response = await fetch(`${API_URL}/posts/tree`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ vector }),
        });
        const data = await response.json();
        
        // Добавлен лог полученных данных
        console.log('Данные, полученные с сервера:', data);
        
        setPosts(data);
      } catch (error) {
        console.error('Tree load error:', error);
      }
    };

    loadTree();
  }, [vector]);

  // Остальной код без изменений
  useEffect(() => {
    if (posts.length > 0 && containerRef.current) {
      const { nodes, edges } = createGraphData(posts);
      
      const options = {
        nodes: {
          borderWidth: 2,
          color: { border: '#800', background: '#F0E0D6' },
          font: { size: 14 }
        },
        edges: {
          color: '#800',
          width: 2,
          arrows: 'to',
          smooth: { type: 'curvedCW' }
        },
        physics: {
          stabilization: true,
          barnesHut: { gravitationalConstant: -2000, springLength: 200 }
        }
      };

      networkRef.current = new vis.Network(
        containerRef.current,
        { nodes, edges },
        options
      );
    }

    return () => {
      if (networkRef.current) {
        networkRef.current.destroy();
      }
    };
  }, [posts]);

  return (
    <div className="graph-container">
      <h2>Ризома мыслительная</h2>
      <div ref={containerRef} style={{ width: '100%', height: '600px', border: '0px solid #800' }} />
    </div>
  );
}

function createGraphData(posts) {
  const nodes = posts.map(post => ({
    id: post.id,
    label: post.text || '[Изображение]',
    image: post.image ? `${API_URL}/${post.image}` : 'https://via.placeholder.com/100',
    shape: 'circularImage',
    size: 25
  }));

  const edges = posts.slice(1).map((post, index) => ({
    from: posts[index].id,
    to: post.id
  }));

  return { nodes, edges };
}

export default GraphContainer;