<html>

<head>
  <title>UA Smash Waiting Screen</title>

  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

  <style>

    body { background-color: rgba(0, 0, 0, 0); margin: 0px auto; overflow: hidden; }

    /* we will explain what these classes do next! */
    .v-enter-active,
    .v-leave-active {
      transition: opacity 1s ease;
    }

    .v-enter-from,
    .v-leave-to {
      opacity: 0;
    }


    .list-move, /* apply transition to moving elements */
    .list-enter-active,
    .list-leave-active {
      transition: all 0.5s ease;
    }

    .list-enter-from,
    .list-leave-to {
      opacity: 0;
      transform: translateX(-30px);
    }

    /* ensure leaving items are taken out of layout flow so that moving
    animations can be calculated correctly. */
    .list-leave-active {
      position: absolute;
    }


    .dark-overlay {
      background-color: rgba(0,0,0,0.7)
    }

    .css-selector {
      background: linear-gradient(225deg, #0098ff, #ff2f00);
      background-size: 400% 400%;
      animation: waitingScreenBackground 31s ease infinite;
    }

    @keyframes waitingScreenBackground {
      0%{background-position:0% 51%}
      50%{background-position:100% 50%}
      100%{background-position:0% 51%}
    }


    .social-media-list-item {
      background-color: rgba(0,0,0,0);
      color: white;
      border-color: rgba(0,0,0,0);
    }


    .fade-out {
      animation-duration: 0.5s;
      animation-name: fadeOut;
    }

    @keyframes fadeOut {
      from {
        opacity: 1;
      }
      to {
        opacity: 0;
      }
    }

    .fade-in {
      animation-duration: 0.5s;
      animation-name: fadeIn;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
      }
      to {
        opacity: 1;
      }
    }

  </style>

  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>

  <script src="https://unpkg.com/vue@3"></script>

  <!-- Load the Twitch embed script -->
  <script src="https://player.twitch.tv/js/embed/v1.js"></script>

</head>

<body>
  <div id="app">

      <div class="container-fluid dark-overlay" style="width: 1920px; height: 1080px;">

          <div class="row bg-dark text-light justify-content-between border-bottom border-secondary mb-3" style="padding-top: 15px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px;">
            <div class="col">
              <h1 class="m-0 pt-1">{{tournamentName}}</h1>
            </div>
            <div class="col" style="text-align: right">
              <img v-if="logoChoice.length > 0" :src="'/data/uploads/' + logoChoice" style="height: 50px;"/>
            </div>
          </div>

          <div class="row row-cols-5" style="padding-left: 50px; padding-right: 50px; padding-top: 15px; padding-bottom: 15px;">
              <div class="col-12">
                <h2 class="text-light mb-3">UP NEXT</h2>
              </div>
              <transition-group name="list">
                <div class="col pb-3 pe-2" v-for="(set, index) in streamQueue" :key="set">

                    <div class="card">
                      <div class="card-header">
                        {{set.eventName}} {{set.phaseName}}
                      </div>
                      <div class="card-body">
                        <h5 class="card-title">{{set.teamOne}} vs. {{set.teamTwo}}</h5>
                        <p class="card-text text-secondary">{{set.fullRoundText}} <br> </p>
                      </div>
                    </div>

                </div>
              </transition-group>
          </div>

          <div class="row justify-content-between" style="padding-left: 50px; padding-right: 50px;">

              <div class="col-3 p-3">
                <h2 class="text-light mb-3">RECENT MATCHES</h2>
                <transition-group name="list">
                  <template v-for="(match, index) in matchList" :key="match">

                    <div class="card mb-3">
                      <div class="card-header">
                        {{match.eventName}} {{match.phaseName}}
                      </div>
                      <div class="card-body">
                        <h5 class="card-title">{{match.score}}</h5>
                        <p class="card-text text-secondary">{{match.fullRoundText}}</p>
                        <small class="text-muted">{{match.stopTime}}</small>
                      </div>
                    </div>

                  </template>
                </transition-group>
              </div>

              <div class="col-3 p-3">
                <h2 class="text-light mb-3">STANDINGS</h2>

                <div v-if="selectedEvent.standings.length > 0" class="card" :class="{'fade-out': fadeOutAnimationEnabled, 'fade-in': fadeInAnimationEnabled}">
                  <div class="card-body">
                    <h5 class="card-title">{{selectedEvent.name}}</h5>
                    <p class="card-text text-secondary" style="font-style: italic;">{{selectedEvent.state}}</p>
                  </div>

                  <ul class="list-group list-group-flush">
                    <li class="list-group-item" style="background-color: rgba(255,255,255,1); border-color: rgba(0,0,0,0);" v-for="(standing, index) in selectedEvent.standings" :key="standing.name">
                      <span class="badge bg-light text-dark me-3" style="font-weight: bold; font-size: 12pt;">{{standing.placement}}</span> {{standing.name}}
                    </li>
                  </ul>
                </div>
              </div>

              <div class="col-6 p-3">
                <h2 class="text-light mb-3">SEASON HIGHLIGHTS</h2>

                <transition>
                  <!-- Add a placeholder for the Twitch embed -->
                  <div id="twitch-embed" v-if="showTwitchEmbed"></div>
                </transition>
              </div>

          </div>

          <div class="row bg-dark text-light fixed-bottom border-top border-secondary" style="padding-top: 15px; padding-bottom: 10px; padding-left: 25px; padding-right: 25px;">
            <div class="col">
              <h4 class="mb-0">CONNECT WITH US!</h4>
              <ul class="list-group list-group-horizontal">
                <li class="list-group-item social-media-list-item" style="font-size: 14pt;"><i class="bi bi-facebook"></i> facebook.com/fsmsmash </li>
                <li class="list-group-item social-media-list-item" style="font-size: 14pt;"><i class="bi bi-discord"></i> bit.ly/fsmsmash </li>
                <li class="list-group-item social-media-list-item" style="font-size: 14pt;"><i class="bi bi-twitch"></i> twitch.tv/uafscs </li>
                <li class="list-group-item social-media-list-item" style="font-size: 14pt;"><i class="bi bi-twitter"></i> twitter.com/fsmsmash </li>
              </ul>
            </div>
            <div class="col" style="text-align: right;">
              <h4 class="mb-1">LOCAL TIME</h4>
              <h4>{{getCurrentTimeAsString}}</h4>
            </div>
          </div>

      </div>

  </div>
</body>

<script type="module">
  import StartGGAPI from '/javascripts/StartGGAPI.js'
  import QueueManager from '/javascripts/QueueManager.js'
  import OverlayDataManager from '/javascripts/OverlayDataManager.js'
  const { createApp } = Vue

  // Create a Twitch.Player object. This will render within the placeholder div
  new Twitch.Player("twitch-embed", {
    width: 854,
    height: 480,
    autoplay: true,
    muted: true,
    collection: "vtjKNGXLFRfY1Q",
    allowfullscreen: true,
  });

  const waitingApp = createApp({
    data() {
      return {
        slug: '',
        tournamentName: '',
        eventList: [],
        previousMatchList: {},
        matchList: [],
        streamQueue: [],
        selectedEvent: { name: '', state: '', standings: [] },
        selectedEventIndex: 0,
        fadeOutAnimationEnabled: false,
        fadeInAnimationEnabled: false,
        currentTime: new Date(),
        showTwitchEmbed: false,
        apiKey: '',
        type: 0,
        slug: null,
        room: null,
        logoChoice: '',
      }
    },
    mounted() {

      const urlParams = new URLSearchParams(window.location.search)
      const type = urlParams.get('type')
      const key = urlParams.get('key')
      const startgg_key = urlParams.get('startgg_key')

      if(type != null) {
        this.type = type
      }
      if(key != null) {
        this.room = key
      }
      if(startgg_key != null) {
        this.apiKey = startgg_key
      }

      if(this.room != null){

        OverlayDataManager.importOverlaySettings(window.location.origin,this.room).then((data) => {

          if(data.settings != null) {

            this.slug = data.settings.slug
            this.logoChoice = data.settings.logoChoice

            try {

              if(this.apiKey != null && this.slug != null){

                this.fetchTournamentDataAndSave().then(() => {
                  waitingApp.reloadStandingsData()
                })

                setInterval(function() { 
                  waitingApp.fetchTournamentDataAndSave() 
                }, 10000)

              } else {
                alert("Required URL parameters missing.")
              } 

            } catch(e) {
              alert(e)
            }

          } else {
            alert("Unable to load configuration settings or required URL parameters missing.")
          }

        })

      } else {

        this.slug = urlParams.get('slug')

        if(this.slug != null && this.apiKey != null) {

          this.fetchTournamentDataAndSave().then(() => {
            waitingApp.reloadStandingsData()
          })

          setInterval(function() { 
            waitingApp.fetchTournamentDataAndSave() 
          }, 10000)

        } else {
          alert("Required URL parameters missing.")
        }

      }


      setTimeout(function() {
        waitingApp.showTwitchEmbed = true
      }, 1000) // Fade in the video content after a second. Otherwise, it's a bit jarring.

      setInterval(function() {
        waitingApp.currentTime = new Date()
      }, 1000)


      setInterval(function () {
        waitingApp.selectedEventIndex++;
        if(waitingApp.selectedEventIndex >= waitingApp.eventList.length){
          waitingApp.selectedEventIndex = 0
        }

        waitingApp.reloadStandingsData()

      }, 15000)


    },
    methods : {
      async fetchTournamentDataAndSave() {
        const data = await StartGGAPI.queryEventInformation(this.apiKey,this.slug)

        this.tournamentName = data.tournamentName
        this.eventList = data.tournamentStandings

        //this.streamQueue = data.tournamentStreamQueue
        if(data.tournamentStreamQueue.length == 0) {
          this.streamQueue = []
        } else {

          QueueManager.refreshQueue(this.streamQueue,data.tournamentStreamQueue)

        }

        for(var i = data.tournamentMatches.length-1; i >= 0; i--){
          const newMatch = data.tournamentMatches[i]
          const match = this.previousMatchList[newMatch.id]
 
          if(match == null) {
            this.matchList.splice(0,0,newMatch)
            this.previousMatchList[newMatch.id] = newMatch

            if(this.matchList.length > 3){
              this.matchList.pop()
            }
          } else {
            match.stopTime = newMatch.stopTime
          }
        }

        // TODO: Save to session data?

        /*
        data.tournamentMatches = [
          {teamOne: 'Illidan', teamTwo: 'Phantom', eventName: '', phaseName: 'Ultimate Singles Bracket', fullRoundText: 'Losers Final', score: 'Illidan 1 - Phantom - 3', stopTime: '5 minutes ago'},
          {teamOne: 'LumaDooma', teamTwo: 'Brit', eventName: '', phaseName: 'Ultimate Singles Bracket', fullRoundText: 'Losers Quarter-Final', score: 'LumaDooma 1 - Brit - 3', stopTime: '5 minutes ago'},
          {teamOne: 'KingIBC', teamTwo: 'TopHatTitan', eventName: '', phaseName: 'Ultimate Singles Bracket', fullRoundText: 'Losers Semi-Final', score: 'KingIBC 1 - TopHatTitan - 3', stopTime: '5 minutes ago'},
          {teamOne: 'SAW', teamTwo: 'The Professor', eventName: '', phaseName: 'Ultimate Singles Bracket', fullRoundText: 'Losers Round 4', score: 'SAW 1 - The Professor - 3', stopTime: '5 minutes ago'},
        ]
        this.streamQueue = [{eventName: 'Ultimate Singles', phaseName: 'Bracket', fullRoundText: 'Grand Final', teamOne: 'Phantom', teamTwo: 'Illidan'},]

        this.eventList = [
          {name: 'Melee Singles', state: 'COMPLETED', standings: [{ name: 'Jojo', placement: '1'},{ name: 'TopHatTitan', placement: '2'},{ name: 'Naruto', placement: '3'}]},
          {name: 'Ultimate Singles', state: 'ACTIVE', standings: [{ name: 'Illidan', placement: '1'},{ name: 'The Professor', placement: '2'},{ name: 'Phantom', placement: '3'}]}
        ]*/

      },
      reloadStandingsData() {
        if(this.eventList.length > 0) {

          this.fadeOutAnimationEnabled = true
          setTimeout(() => {
            this.selectedEvent = this.eventList[this.selectedEventIndex]
            this.fadeOutAnimationEnabled = false

            this.fadeInAnimationEnabled = true
            setTimeout(() => {
              this.fadeInAnimationEnabled = false
            }, 500)

          }, 500)

        }
      }
    },
    computed: {
      getCurrentTimeAsString() {
        const dateString =
        this.currentTime.getHours().toString().padStart(2, '0') + ":" +
        this.currentTime.getMinutes().toString().padStart(2, '0') + ":" +
        this.currentTime.getSeconds().toString().padStart(2, '0')
        return dateString
      }
    },
    components: {

    }
  }).mount('#app')

</script>

</html>
