import './Experiences.css';
import SingleExperience from '../SingleExperience/SingleExperience.jsx';
import React, {useEffect, useState} from "react";

function Experiences() {
    const [experiences, setExperiences] = useState([]);
    const [experienceTasks, setExperienceTasks] = useState([]);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchExperiencesAndTasks = async () => {
            try {
                let response = await fetch('/api/experiences/');
                if (!response.ok) {
                    throw new Error(`Erreur HTTP: ${response.status}`);
                }
                let data = await response.json();
                setExperiences(data.data);

                response = await fetch('/api/experienceTasks/');
                if (!response.ok) {
                    throw new Error(`Erreur HTTP: ${response.status}`);
                }
                data = await response.json();
                setExperienceTasks(data.data);
            } catch (err) {
                setError(err.message);
            }
        };
        fetchExperiencesAndTasks();
    }, []);

    if (error) {
        return <div>Error retrieving data: {error}</div>;
    }

    return (
        <section id="experiences-section">
            <h1 className="section-title">Experiences</h1>
            <div className="experiences-container">
                {experiences.map((exp) => (
                    <SingleExperience experience={exp} tasks={experienceTasks.filter(task => task.experience_id === exp.id)}/>
                ))}
            </div>
        </section>
    );
}

export default Experiences;
