import "./styles.css";

import { useEffect, useState } from "react";

import Container from "../../layouts/Container/index.js";
import allData from "../../data/dataFiltered.js";
import levels from "../../data/levels.js";

const Character = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const filterDataByFolder = (folderId) => {
      const filteredData = allData.filter((item) => item.folder === folderId);

      return filteredData.map((item) => {
        const subItems = filterDataByFolder(item._id);
        return {
          ...item,
          subItems,
        };
      });
    };

    const mainFolders = allData.filter((item) => item.folder === null);
    const filteredData = mainFolders.map((item) => {
      const subItems = filterDataByFolder(item._id);
      return {
        ...item,
        subItems,
      };
    });

    setData(filteredData);
  }, [setData]);

  const renderSubItems = (subItems) => {
    if (subItems?.length === 0) {
      return subItems?.length !== 0 ? (
        <div>
          <h4>
            {subItems?._id} - {subItems?.name}
          </h4>
        </div>
      ) : (
        <></>
      );
    } else {
      return subItems?.map((subItem, subId) => {
        return (
          <div key={`subItem-${subId}`} style={{ color: "green" }}>
            {subItems?.length !== 0 ? (
              <div>
                <h5
                  className={
                    subItem?._key === `!folders!${subItem?._id}`
                      ? "selected"
                      : ""
                  }
                >
                  {subItem?._id} - {subItem?.name} - {subItem?.folder}
                </h5>
              </div>
            ) : (
              <></>
            )}
            {renderSubItems(subItem?.subItems)}
          </div>
        );
      });
    }
  };

  return (
    <div className="character">
      <Container>
        <div
          style={{
            display: "flex",
            justifyContent: "space-around",
            flexDirection: "row",
          }}
        >
          {levels.map((item, id) => (
            <div key={`level-${id}`}>
              <h2>{item?.name}</h2>
            </div>
          ))}
        </div>
        {/* {data?.map((item, id) => (
          <div key={`top-${id}`}>
            <div>
              <h3>
                {item?._id} - {item?.name}
              </h3>
            </div>
            {renderSubItems(item?.subItems)}
          </div>
        ))} */}
      </Container>
    </div>
  );
};

export default Character;
