function addLine() {
  const tbody = document.querySelector("#lines-table tbody");

  const tr = document.createElement("tr");
  tr.innerHTML = `
    <td><input type="number" class="account-id" /></td>
    <td><input type="number" class="debit" value="0" /></td>
    <td><input type="number" class="credit" value="0" /></td>
    <td><button onclick="this.closest('tr').remove()">削除</button></td>
  `;

  tbody.appendChild(tr);
}

async function submitJournal() {
  const date = document.getElementById("journal-date").value;
  const desc = document.getElementById("description").value;

  if (!date) {
    alert("日付を入力してください");
    return;
  }

  const lines = [];
  document.querySelectorAll("#lines-table tbody tr").forEach((tr) => {
    const accountId = tr.querySelector(".account-id").value;
    const debit = tr.querySelector(".debit").value || 0;
    const credit = tr.querySelector(".credit").value || 0;

    if (!accountId) return;

    lines.push({
      account_id: Number(accountId),
      debit: Number(debit),
      credit: Number(credit),
    });
  });

  if (lines.length < 2) {
    alert("仕訳明細は2行以上必要です");
    return;
  }

  try {
    await fetch(`/journals`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        journal_date: date,
        description: desc,
        lines: lines,
      }),
    }).then(async (res) => {
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || "登録失敗");
      }
    });

    alert("仕訳を登録しました");
    location.href = "index.html";
  } catch (e) {
    alert(e.message);
  }
}
