<%- include('partials/header'); -%>

<% let allow = 0 %>


<div class="main-meny">
<ul class="recipes">
  <% let i = 1; wish.forEach(function(a) { if (a.itemName !== undefined) { %>
    <li class="recipe" >
      <h2 id="<%= a.itemName %>"> <%=a.itemName%></h2>
      <h4>Description:</h4>
      <p><%= a.description %></p>
      <form >
          <!-- Your form fields go here -->
          <label for="">made by</label>
          <button type="submit" id="<%= a.username %>" class="creatorName btn btnUsername"><%= a.username %></button>
        </form>

      <% if (user && user.username === a.username || user && user.admin) { allow = 1%>
        <button class="delete button" id="<%= a._id %>"><a href="">Delte Wish</a></button>
        <% } %>

        
    </li>
    <% i = i +1}}); %>
  
</div>



<script>
  
  const search = document.querySelectorAll('.btnUsername')
  
  for (let i = 0; i < search.length; i++) {
    search[i].addEventListener("click", (e) => {
      e.preventDefault()
          search[i].style.color="blue";
          location.assign(`/user/${search[i].id}`);
      
      })}
</script>

  <% if (user ||user && user.admin) { %>
    <script>
      const btnDelete = document.querySelectorAll('.delete') 
        for (let i = 0; i < btnDelete.length; i++) {
       btnDelete[i].addEventListener("click", function() {
         btnDelete[i].style.color="blue";
         plsWRKFFS(btnDelete[i].id)
        
        })}
      
        async function plsWRKFFS(e) {
          try  {
              const res = await fetch('/deleteWish', { 
              method: 'POST', 
              body: JSON.stringify({  id: e }),
              headers: {'Content-Type': 'application/json'}
                  });
              const data = await res.json()
              if (data.errors) {
                  console.log(data.errors);
              }
  
  
          } catch (error) {
              console.log(error);
          }
       }
  
  
    </script>
  
  <% } %>

<%- include('partials/footer') -%>