// 입력 요소 가져오기
const dateInput = document.getElementById("date");
const typeInput = document.getElementById("type");
const categoryInput = document.getElementById("category");
const contentInput = document.getElementById("content");
const amountInput = document.getElementById("amount");

const addButton = document.getElementById("addButton");
const transactionList = document.getElementById("transactionList");


// 처음에는 오늘 날짜 자동 입력
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, "0");
const day = String(today.getDate()).padStart(2, "0");

dateInput.value = `${year}-${month}-${day}`;


// 처음에는 "아직 내역이 없어요" 표시
showEmptyMessage();


// 내용 입력칸에 커서
contentInput.focus();


// 카테고리별 이모지
const categoryEmoji = {
    "식비": "🍚",
    "교통": "🚌",
    "쇼핑": "🛍️",
    "생활": "🏠",
    "기타": "📌"
};


// 추가 버튼 클릭
addButton.addEventListener("click", function() {

    const date = dateInput.value;
    const type = typeInput.value;
    const category = categoryInput.value;
    const content = contentInput.value;
    const amount = amountInput.value;


    // 하나라도 비어 있으면 추가하지 않음
    if (
        date === "" ||
        type === "" ||
        category === "" ||
        content === "" ||
        amount === ""
    ) {
        alert("모든 항목을 입력해주세요.");
        return;
    }


    // 내역이 없다는 메시지 삭제
    const emptyMessage = document.querySelector(".empty-message");

    if (emptyMessage) {
        emptyMessage.remove();
    }


    // 표가 없으면 표 만들기
    let table = document.querySelector(".transaction-table");

    if (!table) {
        table = document.createElement("table");
        table.className = "transaction-table";

        table.innerHTML = `
            <thead>
                <tr>
                    <th>날짜</th>
                    <th>구분</th>
                    <th>카테고리</th>
                    <th>내용</th>
                    <th>금액</th>
                </tr>
            </thead>
            <tbody></tbody>
        `;

        transactionList.appendChild(table);
    }


    // 표의 tbody 가져오기
    const tbody = table.querySelector("tbody");

    // 새로운 행 만들기
    const row = document.createElement("tr");


    // 수입 / 지출 텍스트
    let typeText = "";

    if (type === "income") {
        typeText = "수입";
    } else {
        typeText = "지출";
    }


    // 카테고리 이모지
    const categoryText =
        `${categoryEmoji[category] || "📌"} ${category}`;


    // 금액에 쉼표 넣기
    const formattedAmount =
        Number(amount).toLocaleString() + "원";


    // 수입은 파란색, 지출은 빨간색
    const amountClass = type;


    row.innerHTML = `
        <td>${date}</td>
        <td>${typeText}</td>
        <td>${categoryText}</td>
        <td>${content}</td>
        <td class="${amountClass}">
            ${formattedAmount}
        </td>
    `;


    // 날짜가 최신인 내역이 위로 오도록 추가
    const rows = Array.from(tbody.querySelectorAll("tr"));

    let inserted = false;

    for (const existingRow of rows) {

        const existingDate = existingRow.cells[0].textContent;

        if (date > existingDate) {
            tbody.insertBefore(row, existingRow);
            inserted = true;
            break;
        }
    }


    // 가장 오래된 내역이면 맨 아래에 추가
    if (!inserted) {
        tbody.appendChild(row);
    }


    // 내용과 금액 입력칸 초기화
    contentInput.value = "";
    amountInput.value = "";


    // 내용 입력칸에 커서 이동
    contentInput.focus();

});


// 내역이 없을 때 메시지를 보여주는 함수
function showEmptyMessage() {

    transactionList.innerHTML = `
        <div class="empty-message">
            아직 내역이 없어요
        </div>
    `;

}