<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>List Items</title>
  <link rel="stylesheet" href="/list-mvc/style.css">
</head>

<body>
  <div class="container">
    <a href="/list-mvc/">Home</a>
    <h1>
      <%= listName %>
    </h1>
    <p onclick="editDescription('<%= listId %>')">
      <%= listDescription %>
        <span class="edit-description">[click to edit]</span>
    </p>
    <ul class="list-group">
      <% items.forEach(item=> { %>
        <li class="list-item">
          <%= item.content %>
            <a class="remove-btn" href="/list-mvc/list/<%= listId %>/delete-item/<%= item.id %>">remove item</a>
        </li>
        <% }); %>
    </ul>
    <form action="/list-mvc/list/<%= listId %>/add-item" method="POST">
      <input type="text" name="content" placeholder="New item">
      <button type="submit" class="btn">Add Item</button>
      <button id="themeToggle" class="btn">Dark/Light</button>
    </form>
  </div>
</body>

<script>
  function editDescription(listId) {
    const newDescription = prompt("Enter new description");
    if (newDescription) {
      fetch("/list-mvc/list/" + listId + "/edit-description", {
        method: "POST",
        body: JSON.stringify({
          description: newDescription
        }),
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then(res => {
          if (res.ok) return res.json();
        })
        .then(data => {
          window.location.reload(true);
        });
    }
  }

  document.querySelector("input").focus();

  const themeToggle = document.getElementById('themeToggle');
  const currentTheme = localStorage.getItem('theme') || 'light';

  document.documentElement.setAttribute('data-theme', currentTheme);

  themeToggle.addEventListener('click', () => {
    const currentTheme = document.documentElement.getAttribute('data-theme');
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';

    document.documentElement.setAttribute('data-theme', newTheme);
    localStorage.setItem('theme', newTheme);
  });
</script>

</html>
