<template>
  <nav class="navbar navbar-expand-md navbar-dark fixed-top">
    <div class="container">
      <button aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler"
              data-bs-target="#mainNav" data-bs-toggle="collapse" type="button">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div id="mainNav" class="collapse navbar-collapse navbar-nav justify-content-between">
        <ul class="list-unstyled">
          <li class="nav-item">
            <router-link class="navbar-brand" to="/" @click="closeNav">
              CSGO<span class="text-up text-white fw-bold">WTF</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/explore" @click="closeNav">
              Explore
            </router-link>
          </li>
        </ul>
        <form class="d-flex" @keydown.enter.prevent="parseSearch">
          <label for="search">
            <i class="fas fa-search"></i>
          </label>

          <input id="search" v-model="data.searchInput" aria-label="Search"
                 class="form-control bg-transparent border-0"
                 placeholder="SteamID64, Profile Link or Custom URL"
                 title="SteamID64, Profile Link or Custom URL"
                 type="search">
          <button
              class="btn border-2 btn-outline-info"
              type="button"
              @click="parseSearch"
          >
            Search!
          </button>
          <div v-if="data.error" class="alert alert-warning" role="alert">
            {{ data.error }}
          </div>
        </form>
      </div>

    </div>
  </nav>
</template>

<script>
import {reactive} from "vue";
import {useStore} from 'vuex'
import {GetUser, GoToPlayer} from '../utils'

export default {
  name: 'Nav',
  setup() {
    const store = useStore()
    const data = reactive({
      searchInput: '',
      error: ''
    })

    const closeNav = () => {
      const nav = document.querySelector('#mainNav')
      if (nav.classList.contains('show'))
        nav.classList.remove('show')
    }

    const parseSearch = async () => {
      const input = data.searchInput
      const customUrlPattern = 'https://steamcommunity.com/id/'
      const profileUrlPattern = 'https://steamcommunity.com/profiles/'
      const id64Pattern = /^\d{17}$/
      const vanityPattern = /^[A-Za-z0-9-_]{3,32}$/

      store.commit({
        type: 'changeVanityUrl',
        id: ''
      })
      store.commit({
        type: 'changeId64',
        id: ''
      })

      if (data.searchInput !== '') {
        if (id64Pattern.test(input)) {
          store.commit({
            type: 'changeId64',
            id: input
          })
        } else if (input.match(customUrlPattern)) {
          store.commit({
            type: 'changeVanityUrl',
            id: input.split('/')[4].split('?')[0]
          })
        } else if (input.match(profileUrlPattern)) {
          const tmp = input.split('/')[4].split('?')[0]
          if (id64Pattern.test(tmp)) {
            store.commit({
              type: 'changeId64',
              id: tmp
            })
          }
        } else {
          store.commit({
            type: 'changeVanityUrl',
            id: input
          })
        }

        if (vanityPattern.test(store.state.vanityUrl)) {
          store.commit({
            type: 'changeVanityUrl',
            id: input
          })
        } else {
          data.error = 'Only alphanumeric symbols, "_", and "-", between 3-32 characters'
          store.commit({
            type: 'changeVanityUrl',
            id: ''
          })
        }

        if (store.state.id64 !== '' || store.state.vanityUrl !== '') {
          const [res, resData] = await GetUser(store.state.vanityUrl || store.state.id64)

          if (res === 200) {
            data.searchInput = ''
            document.activeElement.blur()

            store.commit({
              type: 'changePlayerDetails',
              data: resData
            })

            if (store.state.vanityUrl) {
              closeNav()
              GoToPlayer(store.state.vanityUrl)
            } else if (store.state.id64) {
              closeNav()
              GoToPlayer(store.state.id64)
            }

          } else if (res === 404) {
            data.searchInput = ''
            data.error = `${resData} - Try again`
            // TODO: needs 404
          } else if (res === 502) {
            data.searchInput = ''
            data.error = 'Server not available'
          } else {
            console.log(res, resData)
            // TODO: needs 404
          }
        }

        setTimeout(() => {
          data.error = ''
        }, 5000)
      }
    }

    document.addEventListener('click', () => {
      closeNav()
    })


    return {
      data, parseSearch, closeNav
    }
  }
}
</script>

<style lang="scss" scoped>
nav {
  .nav-link {
    text-decoration: none;
    color: white !important;

    .router-link-exact-active {
      box-shadow: 0 4px 2px -2px var(--bs-warning);
    }

    &:hover {
      color: #bdbdbd !important;
      transition: 250ms ease-in-out;
      cursor: pointer;
      box-shadow: 0 4px 2px -2px var(--bs-warning);
    }
  }

  max-width: 100vw;
  height: 70px;
  width: 100vw;
  background: rgba(16, 18, 26, 1);
  z-index: 2;

  ul {
    display: flex;

    li, .navbar-brand {
      font-size: 1.5rem;
      font-weight: lighter;
      margin: 22px 0 0 10px;
      cursor: pointer;
      transition: 100ms ease-in-out;

      .text-up {
        font-size: 40%;
        vertical-align: top;
      }
    }

    .navbar-brand {
      color: var(--bs-warning);
      font-size: 2rem;
      font-weight: bold;
      margin-top: 17px;
      margin-left: 0;

      &:hover {
        color: var(--bs-warning);
      }
    }
  }

  form {
    position: relative;

    svg {
      width: 24px;
      height: 24px;
      fill: currentColor;
    }

    label {
      padding-top: 6px;
      font-size: 1.4rem;
    }

    input[type="search"] {
      min-width: 300px;
      max-width: 300px;

      &:focus {
        box-shadow: 0 4px 2px -2px rgba(95, 120, 146, 0.59);
        transition: .2s ease-in-out;
        transform: scale(.975);
      }

      &::placeholder {
        color: #aaa;
      }
    }

    .alert {
      position: absolute;
      right: 0;
      top: 55px;
    }
  }
}

@media screen and (max-width: 410px) {
  form {
    margin-left: auto !important;
    margin-right: auto !important;

    input[type="search"] {
      margin-left: 0 !important;
      max-width: 60vw !important;
      min-width: 60vw !important;
    }
  }
}

@media screen and (max-width: 455px) and (min-width: 410px) {
  form {
    margin-left: auto !important;
    margin-right: auto !important;

    input[type="search"] {
      margin-left: 0 !important;
      max-width: 65vw !important;
      min-width: 65vw !important;
    }
  }
}

@media screen and (max-width: 610px) and (min-width: 456px) {
  form {
    margin-left: auto !important;
    margin-right: auto !important;

    input[type="search"] {
      margin-left: 0 !important;
      max-width: 68vw !important;
      min-width: 68vw !important;
    }
  }
}

@media screen and (max-width: 768px) {
  nav {
    button {
      outline: 1px solid var(--bs-primary);
      margin-left: auto;
      float: right;

      &:focus {
        box-shadow: none;
        outline: 1px solid var(--bs-primary);
      }
    }

    .navbar-collapse {
      background: var(--bs-secondary);
      border-radius: 5px;
      border: 1px solid var(--bs-primary)
    }

    #mainNav {
      ul {
        display: flex;
        flex-direction: column;
        text-align: center;
        width: 100%;

        li {
          line-height: 1;
          padding: 0 0 20px 0;
          border-bottom: 1px solid rgba(255, 255, 255, .1);
        }
      }

      form {
        max-width: 87vw;
        margin-left: -40px;

        label {
          display: none;
        }

        input[type="search"] {
          margin-bottom: 15px;
          margin-left: 37px;
          max-width: 400px;
          min-width: 400px;
          font-size: 1rem;

          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;

          &::placeholder {
            background: var(--bs-body-bg);
          }
        }

        button {
          margin-left: 10px;
          display: block;
          margin-top: -2px;
          height: 40px;
        }
      }
    }
  }
}
</style>
