<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="shortcut icon" href="/favicon.svg" type="image/x-icon" />
    <link rel="stylesheet" href="/style.css" />
    <title>Quebec</title>
  </head>

  <body>
    <a href="/">
      <h1 style="text-align: center">Welcome to Hackable Blog!</h1>
    </a>

    <nav>
      <a href="/">Home</a>
      <a href="/post">Post</a>
    </nav>

    <% for (let i = 0; i < posts.length; i++) { %> <% let post = posts[i] %>
    <div class="post_container">
      <div class="flex_buttons">
        <button class="update" onclick="handleClick(this)">Update</button>

        <div class="delete">
          <form action="/delete/<%= post._id %>" method="POST">
            <input type="submit" value="Delete" />
          </form>
        </div>
      </div>

      <div>
        <p class="status"><%= post.status %></p>

        <div hidden id="update_form_container">
          <form
            action="/update/<%= post._id %>"
            method="post"
            style="display: flex; align-items: center"
          >
            <textarea class="inputs" name="status" style="margin-left: 0">
<%= post.status %></textarea
            >
            <button class="update" type="submit">Done</button>
          </form>
        </div>
      </div>

      <div class="image_container">
        <img width="100%" src="<%= post.image_url %>" alt="Post image" />
      </div>
    </div>
    <% } %>

    <footer>
      <a
        style="font-size: x-large; color: #000"
        href="https://github.com/KhoiUna/cis486-quebec"
      >
        <p style="text-align: center; font-weight: bold">Source code</p>
      </a>
    </footer>
  </body>

  <script type="text/javascript">
    let currentTargetState = {};

    // Only allow editing once at a time
    const handleClick = (target) => {
      if (currentTargetState.targetUpdateButton)
        currentTargetState.targetUpdateButton.hidden = false;
      if (currentTargetState.targetStatusParagraph)
        currentTargetState.targetStatusParagraph.hidden = false;
      if (currentTargetState.targetUpdateForm)
        currentTargetState.targetUpdateForm.hidden = true;

      currentTargetState.targetUpdateButton = target;
      currentTargetState.targetStatusParagraph =
        target.parentNode.parentNode.children[1].children[0];
      currentTargetState.targetUpdateForm =
        target.parentNode.parentNode.children[1].children[1];

      currentTargetState.targetUpdateButton.hidden = true;
      currentTargetState.targetStatusParagraph.hidden = true;
      currentTargetState.targetUpdateForm.hidden = false;
    };
  </script>
</html>
