import {useState, useEffect} from "react";

const STORAGE_STRING = 'todo-app-todos';

export default function App() {
    const [input, setInput] = useState("");
    const [todos, setTodos] = useState(JSON.parse(localStorage.getItem(STORAGE_STRING))||[]);

    useEffect(() => persistTodos(),[todos]);

    function persistTodos() {
        localStorage.setItem(STORAGE_STRING, JSON.stringify(todos));
    }

    function addTodo() {
        if (input.trim() === "") return;
        setTodos([...todos, {id: Date.now(), text: input, erledigt: false}]);
        setInput("");
    }

    function deleteTodo(id) {
        setTodos(todos.filter((todo) => todo.id !== id));
    }

    function toggleTodo(id) {
        setTodos(todos.map((todo) =>
            todo.id === id ? {...todo, erledigt: !todo.erledigt} : todo
        ));
    }

    return (
        <div className="container schatten-farbverlauf">
            <div className="aufgaben-app">
                <h2>Aufgabenliste</h2>
                <div className="input-container">
                    <input type="text" onChange={(e) => setInput(e.target.value)} placeholder="Neue Aufgabe eintragen..."/>
                    <button onClick={() => addTodo()}>Hinzufügen</button>
                </div>
                <ul id="todo-list-container">
                    {todos.map((todo) => (
                        <li key={todo.id}>
                            <label>
                                <input
                                    type="checkbox"
                                    checked={todo.erledigt}
                                    onChange={() => toggleTodo(todo.id)}
                                />{todo.text}
                            </label>
                            <button onClick={() => deleteTodo(todo.id)}>Entfernen</button>
                        </li>))}
                </ul>
            </div>
        </div>
    );
}