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

<% if(user && user.username === userId) {  %>

  <% let allow = 0 %>

  <div class="main-meny">
    <% if (user) { %>
      <div class="addWish">
              <h1 class="title"><a class="btn">Add new wish</a></h1>
                <form action="/wishlist" class="form hide">
                  <h2>Add an item to wishlist</h2>
                  <label for="itemName">Wish Name</label>
                  <input type="text" name="itemName"/>
                  <label for="description">Description</label>
                  <input type="text" name="description"/>
                  <button href="" class="button">Add To Wishlist Now</button>
                </form>
      </div>

  <% } %>
  <ul class="recipes">
    <% let i = 1; wish.forEach(function(e) { e.wishes.forEach((a) => {  %>
      <li class="recipe" >
        <h2 id="<%= a.itemName %>"><%= i %>. <label id="itemName"><%=a.itemName%></label></h2>
        <h4>Description:</h4>
        <p id="description"><%= 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) { %>
            <div class="buttonPosition">
              <% if (i > 1) { %>
                <button class="btn left">↑</button>
              <% } %>
              <% if (i < e.wishes.length){%>
              <button class="btn right">↓</button>
              <% } %>
            </div>
            <button class="editTHISSHIT botan"> Edit </button>
            <form class="hide formz " id="<%= a._id  %>">
              <h4 >Update Wish</h4>
              <label for="itemName" name="pokoId" class="formfix pokoId">item name</label>
              <input type="text" name="itemName" id="itemName" value="<%=a.itemName%>"/>
              <label for="description" class="formfix">description</label>
              <input type="text" name="description" id="description" value="<%= a.description %>"/>
              <button href="" class="update button">Update Now</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++;}); %>
    <% }); %>
    
  </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) { %>
  <script>
    const form = document.querySelector('form');
  
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      // get values
      const itemName = form.itemName.value;
      const description = form.description.value;
      const username = document.querySelector('.username').innerText
      console.log(itemName, description, username);
      try {
        const res = await fetch('/wishlist', { 
          method: 'POST', 
          body: JSON.stringify({itemName ,description, username }),
          headers: {'Content-Type': 'application/json'}
        });
        const data = await res.json();
        console.log(data);
        if (data) {
          location.assign(`/home/${username}`);
        }
      }
      catch (err) {
        console.log(err);
      }
    });
  </script>

  <script>
    
    //array
    const forms = document.querySelectorAll('.formz')
    const editButtons = document.querySelectorAll(".editTHISSHIT")
    const addWish = document.querySelector('.form')
    const btnAddWish = document.querySelector('.title')

    btnAddWish.addEventListener('click', e => {
      addWish.classList.toggle('hide')
    })
  
   editButtons.forEach((button, index) => {
    button.addEventListener('click', e => {
      const correspondingForm = forms[index];
      correspondingForm.classList.toggle('hide');
    })
  })
  forms.forEach((a) => {
    
    a.addEventListener('submit', async e => {
      e.preventDefault()
      
      let itemName = a.itemName.value
      let description = a.description.value
      let id = a.id
      try {
        const res = await fetch('/updateWish', { 
            method: 'POST', 
            body: JSON.stringify({  id, itemName, description  }),
            headers: {'Content-Type': 'application/json'}
                });
            const data = await res.json()
            location.reload()
    } catch (error) {
      console.log(error);
    }})})
    
  
  </script>
  
  
    <% } %>

<% if (user && user.username === userId ||user && user.admin) { %>
  <script>
    let updatedWishArray = [];
    let currentPosition = 0;
  
    const wishElements = document.querySelectorAll('.recipe');
  
    wishElements.forEach((e) => {
      const itemNameElement = e.querySelector('#itemName').textContent;
      const descriptionElement = e.querySelector('#description').textContent;
      const idElement = e.querySelector('.formz').nextElementSibling.id;
      const usernameElement = e.querySelector('.creatorName').textContent;
      const position = currentPosition;
  
      const moveLeft = (username) => {
        const itemToMove = updatedWishArray.splice(position, 1)[0]; // Remove item at index 'position' and get the removed item
        updatedWishArray.splice(position - 1, 0, itemToMove); // Insert the removed item at index 'position - 1'
        postNewPosition(updatedWishArray, username);
        location.reload()
      };
  
      const moveRight = (username) => {
        const itemToMove = updatedWishArray.splice(position, 1)[0]; // Remove item at index 'position' and get the removed item
        updatedWishArray.splice(position + 1, 0, itemToMove); // Insert the removed item at index 'position + 1'
        postNewPosition(updatedWishArray, username);
        location.reload()
      };
      if (e.querySelector('.left')) {
        const leftButton = e.querySelector('.left').addEventListener('click', () => {
        moveLeft(usernameElement);
      });
      }
      if (e.querySelector('.right')) {
        const rightButton = e.querySelector('.right').addEventListener('click', () => {
        moveRight(usernameElement);
      });
      } 
  
      updatedWishArray.push({ 'itemName': itemNameElement, 'username': usernameElement, '_id': idElement, 'description': descriptionElement });
      currentPosition = currentPosition + 1;
    });
  
    async function postNewPosition(items, username) {
      try {
        const res = await fetch('/updatePosition', {
          method: 'POST',
          body: JSON.stringify({ items, username }),
          headers: { 'Content-Type': 'application/json' }
        });
        const data = await res.json();
        if (data.errors) {
          console.log(data.errors);
        }
      } catch (error) {
        console.log(error);
      }
    }


    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>

<% } %>
<% }else { %>
  <h1>You dont have permissions to view this page</h1>
    <% } %>

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