class UserList extends HTMLElement {
  constructor() {
    super();
    this.users = [];
  }

  set data(userArray) {
    this.users = userArray;
    this.render();
  }

  formatRelativeTime(timestamp) {
    const now = new Date();
    const msgTime = new Date(timestamp);
    const diffMs = now - msgTime;
    const minutes = Math.floor(diffMs / 60000);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) {
      return `${msgTime.getHours().toString().padStart(2, "0")}:${msgTime.getMinutes().toString().padStart(2, "0")}, ${days} day${days > 1 ? "s" : ""} ago`;
    } else if (hours > 0) {
      return `${msgTime.getHours().toString().padStart(2, "0")}:${msgTime.getMinutes().toString().padStart(2, "0")}, ${hours} hour${hours > 1 ? "s" : ""} ago`;
    } else {
      return `${msgTime.getHours().toString().padStart(2, "0")}:${msgTime.getMinutes().toString().padStart(2, "0")}, ${minutes} min ago`;
    }
  }

  render() {
    this.innerHTML = "";

    this.users.forEach((user) => {
      const html = `
            <div class="user-list__item"
              data-uid="${user.uid}"
              data-color="${user.color}"
              data-user_nick="${user.nick}"
              data-created_at="${user.created_at}"
              data-user_uid="${user.user_uid}">
              
              <a class="user-list__item-avatar" style="background-color: ${user.color}; color: black;" href="/user/${user.uid}.html">
                <img width="40px" height="40px" src="/avatar/${user.uid}.svg" alt="${user.nick}">
              </a>
              
              <div class="user-list__item-content">
                <div class="user-list__item-name" style="color: ${user.color};">${user.nick}</div>
                <div class="user-list__item-time" data-created_at="${user.last_ping}">
                  <a href="/user/${user.uid}.html">profile</a>
                  <a href="/channel/${user.uid}.html">dm</a>
                </div>
              </div>
            </div>
          `;
      this.insertAdjacentHTML("beforeend", html);
    });
  }
}

customElements.define("user-list", UserList);
