const prompt = require('prompt-sync')({ sigint: true });
const fs = require('fs');
const filePath = 'todolist.txt';

console.log("Welcome to Tiffy's to-do list!");

const name = prompt("What is your name? ");
console.log(`Hello, ${name}!`);

const instruction = `You can: 
(1) Add items to the to-do list 
(2) Remove items from the to-do list
(3) Show the to-do list
(4) Exit the to-do list`;
console.log(instruction);

function loadToDoList() {
    const data = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : '';
    return data ? data.split('\n').filter(item => item.trim() !== '') : [];
}

let todoList = loadToDoList();

while (true) {
    const todo = prompt("Would you like to add, remove, show, or exit? ").toLowerCase();

    switch (todo) {
        case "add":
            let condition_add = true;
            while (condition_add) {
                const add1 = prompt("What would you like to add to the to-do list? ");
                if (add1.toLowerCase() === "stop") {
                    condition_add = false;
                }
                    todoList.push(add1);
                    console.log(`You have added "${add1}" to Tiffy's to-do list!`);
                    console.log(`Type \"stop\" to return to the main menu.`);
            }
            fs.writeFileSync(filePath, todoList.join('\n'), 'utf-8');
            break;

        case "remove":
            let condition_remove = true;
            while (condition_remove) {               
                const remove1 = prompt("What would you like to remove from the to-do list? (Input the number on the list) ");
                if (remove1.toLowerCase() === "stop") {
                    condition_remove = false;
                }
                    const index = parseInt(remove1) - 1;
                    const removedTask = todoList.splice(index, 1);
                    console.log(`You have removed "${removedTask}" from Tiffy's to-do list!`);
                    console.log(`Type \"stop\" to return to the main menu.`);
            }
            fs.writeFileSync(filePath, todoList.join('\n'), 'utf-8');
            break;

        case "show":
            console.log("Tiffy's to-do list:");
            todoList.forEach((task, index) => console.log(`${index + 1}. ${task}`));
            break;

        case "exit":
            console.log("Thank you for using Tiffy's to-do list.");
            return;

        default:
            console.log("Hey! Tiffy doesn't know what you mean!");
            break;
    }
}
