<script setup lang="ts">
import { useHead } from '@unhead/vue';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { graphicsSettingsReplicant, playersReplicant, scoreboardReplicant } from '../../browser_shared/replicants';
import { resolveCountryCode } from '../../shared/countries';
import type { Schemas } from '../../types';

useHead({ title: 'Scoreboard' });

const defaultScoreboard: Schemas.Scoreboard = {
  leftPlayerId: '',
  rightPlayerId: '',
  leftNameOverride: '',
  rightNameOverride: '',
  leftTeamOverride: '',
  rightTeamOverride: '',
  leftCountryOverride: '',
  rightCountryOverride: '',
  leftCharacter: '',
  rightCharacter: '',
  leftScore: 0,
  rightScore: 0,
  round: '',
  game: '',
};

const players = computed<Schemas.Players>(() => playersReplicant?.data ?? {});
const scoreboard = computed<Schemas.Scoreboard>(() => scoreboardReplicant?.data ?? defaultScoreboard);
const scoreboardSkin = computed(() => graphicsSettingsReplicant?.data?.scoreboardSkin ?? 'scoreboard/main.html');

watch(
  scoreboardSkin,
  (skin) => {
    if (skin !== 'scoreboard/main.html') {
      const targetUrl = new URL('../scoreboard-2xko/main.html', window.location.href).toString();
      if (window.location.href !== targetUrl) {
        window.location.replace(targetUrl);
      }
    }
  },
  { immediate: true },
);

const leftName = computed(() => {
  if (scoreboard.value.leftNameOverride) {
    return scoreboard.value.leftNameOverride;
  }
  const player = players.value[scoreboard.value.leftPlayerId];
  return player?.gamertag || 'Player 1';
});

const rightName = computed(() => {
  if (scoreboard.value.rightNameOverride) {
    return scoreboard.value.rightNameOverride;
  }
  const player = players.value[scoreboard.value.rightPlayerId];
  return player?.gamertag || 'Player 2';
});

const leftTeam = computed(() => scoreboard.value.leftTeamOverride || '');

const rightTeam = computed(() => scoreboard.value.rightTeamOverride || '');

const flagModules = import.meta.glob('/node_modules/flag-icons/flags/4x3/*.svg', {
  import: 'default',
  query: '?url',
}) as Record<string, () => Promise<string>>;

const flagUrlCache: Record<string, string> = {};

const leftFlagUrl = ref('');
const rightFlagUrl = ref('');

const loadFlagUrl = async (country: string | undefined) => {
  const code = resolveCountryCode(country)?.toLowerCase();
  if (!code) {
    return '';
  }

  const cached = flagUrlCache[code];
  if (cached) {
    return cached;
  }

  const moduleLoader = flagModules[`/node_modules/flag-icons/flags/4x3/${code}.svg`];
  if (!moduleLoader) {
    return '';
  }

  const url = await moduleLoader();
  flagUrlCache[code] = url;
  return url;
};

watch(
  () => scoreboard.value.leftCountryOverride,
  async (country) => {
    leftFlagUrl.value = await loadFlagUrl(country);
  },
  { immediate: true },
);

watch(
  () => scoreboard.value.rightCountryOverride,
  async (country) => {
    rightFlagUrl.value = await loadFlagUrl(country);
  },
  { immediate: true },
);

const roundText = computed(() => scoreboard.value.round || 'Round');

const progressTextWrapperRef = ref<HTMLElement | null>(null);
const progressTextRef = ref<HTMLElement | null>(null);
const p1NameTextWrapperRef = ref<HTMLElement | null>(null);
const p1NameTextRef = ref<HTMLElement | null>(null);
const p2NameTextWrapperRef = ref<HTMLElement | null>(null);
const p2NameTextRef = ref<HTMLElement | null>(null);
const p1ScoreWrapperRef = ref<HTMLElement | null>(null);
const p1ScoreTextRef = ref<HTMLElement | null>(null);
const p2ScoreWrapperRef = ref<HTMLElement | null>(null);
const p2ScoreTextRef = ref<HTMLElement | null>(null);

const fitText = (container: HTMLElement | null, textElement: HTMLElement | null, maxSize: number, minSize = 1) => {
  if (!container || !textElement) {
    return;
  }

  let size = maxSize;
  textElement.style.fontSize = `${size}px`;

  while (size > minSize) {
    const overflowsWidth = textElement.scrollWidth > container.clientWidth;
    const overflowsHeight = textElement.scrollHeight > container.clientHeight;
    if (!overflowsWidth && !overflowsHeight) {
      break;
    }

    size -= 1;
    textElement.style.fontSize = `${size}px`;
  }
};

const refitText = () => {
  fitText(progressTextWrapperRef.value, progressTextRef.value, 35);
  fitText(p1NameTextWrapperRef.value, p1NameTextRef.value, 45);
  fitText(p2NameTextWrapperRef.value, p2NameTextRef.value, 45);
  fitText(p1ScoreWrapperRef.value, p1ScoreTextRef.value, 55);
  fitText(p2ScoreWrapperRef.value, p2ScoreTextRef.value, 55);
};

const scheduleRefit = () => {
  void nextTick(() => {
    refitText();
  });
};

onMounted(() => {
  window.addEventListener('resize', refitText);
  scheduleRefit();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', refitText);
});

watch(
  () => [
    roundText.value,
    leftTeam.value,
    rightTeam.value,
    leftName.value,
    rightName.value,
    scoreboard.value.leftScore,
    scoreboard.value.rightScore,
  ],
  () => {
    scheduleRefit();
  },
  { immediate: true },
);
</script>

<template>
  <div id="scoreboard">
    <div id="back-panel-wrapper">
      <img
        id="back-panel"
        src="./img/back.svg"
        alt=""
      >
    </div>

    <div id="main-panel-wrapper">
      <img
        id="main-panel"
        src="./img/main.svg"
        alt=""
      >

      <div
        id="progress-text-wrapper"
        ref="progressTextWrapperRef"
      >
        <div
          id="progress-text"
          ref="progressTextRef"
        >
          {{ roundText }}
        </div>
      </div>

      <div
        id="p1-games-text-wrapper"
        ref="p1ScoreWrapperRef"
        class="games-text-wrapper"
      >
        <div
          ref="p1ScoreTextRef"
          class="games-text"
        >
          {{ scoreboard.leftScore }}
        </div>
      </div>

      <div
        id="p2-games-text-wrapper"
        ref="p2ScoreWrapperRef"
        class="games-text-wrapper"
      >
        <div
          ref="p2ScoreTextRef"
          class="games-text"
        >
          {{ scoreboard.rightScore }}
        </div>
      </div>

      <div
        id="p1-name-wrapper"
        class="name-wrapper"
      >
        <img
          src="./img/name1.svg"
          alt=""
        >

        <div
          id="p1-name-text-wrapper"
          ref="p1NameTextWrapperRef"
          class="name-text-wrapper"
        >
          <div ref="p1NameTextRef">
            <span
              v-if="leftTeam"
              class="team-text"
            >
              {{ leftTeam }}
            </span>
            <span class="gamertag-text">
              {{ leftName }}
            </span>
          </div>
        </div>

        <div
          v-if="leftFlagUrl"
          id="p1-flag-wrapper"
          class="flag-wrapper"
        >
          <div class="flag-mask">
            <img
              class="flag"
              :src="leftFlagUrl"
              alt=""
            >
          </div>
        </div>
      </div>

      <div
        id="p2-name-wrapper"
        class="name-wrapper"
      >
        <img
          src="./img/name2.svg"
          alt=""
        >

        <div
          id="p2-name-text-wrapper"
          ref="p2NameTextWrapperRef"
          class="name-text-wrapper"
        >
          <div ref="p2NameTextRef">
            <span
              v-if="rightTeam"
              class="team-text"
            >
              {{ rightTeam }}
            </span>
            <span class="gamertag-text">
              {{ rightName }}
            </span>
          </div>
        </div>

        <div
          v-if="rightFlagUrl"
          id="p2-flag-wrapper"
          class="flag-wrapper"
        >
          <div class="flag-mask">
            <img
              class="flag"
              :src="rightFlagUrl"
              alt=""
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* ==== SVG ELEMENTS COLOR SETTINGS ==== */

/* == Player Plaques == */

/* Gradient for background/fill - Player 1 */
#linear-gradient-p1-noimg,
#linear-gradient-p1-full {
	--gradient-stop-1: #15bcba; /* 15bcba */
	--gradient-stop-2: #19c2a4; /* 19c2a4 */
	--gradient-stop-3: #1ecb8b; /* 1ecb8b */
}
/* Gradient for background/fill - Player 2 */
#linear-gradient-p2-noimg,
#linear-gradient-p2-full {
	--gradient-stop-1: #15bcba; /* 15bcba */
	--gradient-stop-2: #19c2a4; /* 19c2a4 */
	--gradient-stop-3: #1ecb8b; /* 1ecb8b */
}

/* Stroke color - Player 1 */
#P1_bg_stroke_noimg polygon,
#P1_diag_noimg line,
#P1_vert_noimg line,
#P1_bg_stroke polygon,
#P1_diag line,
#P1_vert line {
	stroke: #232323; /* 232323 */
}
/* Stroke color - Player 2 */
#P2_bg_stroke_noimg polygon,
#P2_diag_noimg line,
#P2_vert_noimg line,
#P2_bg_stroke polygon,
#P2_diag line,
#P2_vert line {
	stroke: #232323; /* 232323 */
}

/* Faint outer glow effect on stroke - Player 1 */
#coloredGlow_p1 {
	--glow-color: #232323; /* 232323 */
	--glow-opacity: 1;
}
/* Faint outer glow effect on stroke - Player 2 */
#coloredGlow_p2 {
	--glow-color: #232323; /* 232323 */
	--glow-opacity: 1;
}

/* Drop shadow */
.playerPlaque {
	filter: drop-shadow(rgba(0, 0, 0, 0.2) 0px 0px 0.2rem);
}

/* == Team Plaques == */

/* Background color - Team 1 */
#T1_noimg_bg,
#T1_full_bg {
	fill: #000000; /* 000000 */
	opacity: 0.9; /* 0.9 */
}
/* Background color - Team 2 */
#T2_noimg_bg,
#T2_full_bg {
	fill: #000000; /* 000000 */
	opacity: 0.9; /* 0.9 */
}

/* Line color - Team 1 */
#T1_noimg_line line,
#T1_full_line line {
	stroke: #ffffff; /* ffffff */
}
/* Line color - Team 2 */
#T2_noimg_line line,
#T2_full_line line {
	stroke: #ffffff; /* ffffff */
}

/* Drop shadow */
#T1_noimg_bg,
#T1_full_bg,
#T2_noimg_bg,
#T2_full_bg {
	filter: drop-shadow(rgba(0, 0, 0, 0.4) 0px 0px 0.3rem);
}

/* == Top Row == */

/* Drop shadow */
#topRowShadow {
	fill: #000000; /* 000000 */
	opacity: 0.8; /* 0.8 */
}
/* Element body */
#topRowBody {
	stroke: #000000; /* 000000 */
	fill: #000000; /* 000000 */
	opacity: 0.9; /* 0.9 */
}

/* ==== END OF SVG ELEMENTS COLOR SETTINGS ==== */



@font-face {
	font-family: 'Shapiro 115 Plus Ext';
	src: url('fonts/Shapiro-115-Plus-Extd.otf');
	font-weight: normal;
	font-style: normal;
}

@font-face {
	font-family: 'Shapiro 55 Middle Ext';
	src: url('fonts/Shapiro 55 Middle Extd.otf');
	font-weight: normal;
	font-style: normal;
}

@font-face {
	font-family: 'Shapiro 45 Welter Text';
	src: url('fonts/Shapiro 45 Welter Text.otf');
	font-weight: normal;
	font-style: normal;
}

body {
	margin: 0;
	font-family: 'Titillium Web', sans-serif; /*<--- Default placeholder font*/
	font-family: 'Akko Pro', sans-serif;
	color: white;
	background: transparent;
}
.debug {
	background-color: var(--debug-bg-color, black) !important; 
	/* border: solid 1px red;*/
}

.debug-bg-container {
	position: fixed;
	width: 1920px;
	height: 1080px;
	overflow: hidden;
}

.debug-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	object-fit: cover; /* keep aspect ratio while filling space */
	z-index: 0;
}

.bg-img {
	z-index: 0;
}

.scoreboardContainer {
	display: flex;
	justify-content: center;
	align-items: flex-start;
	height: 54px;
	padding: 0 20px;
	background-color: transparent;
	position: relative;
	z-index: 1;
}

.nameBlock {
	background-color: transparent;
	width: 334px;
	height: 36px;
	padding: 0px 5px 0px 5px;
	align-content: center;
	text-align: center;
	text-shadow: 0 0 10px black, 2px 0 black, -2px 0 black, 0 2px black, 0 -2px black, 1px 1px black, -1px -1px black, 1px -1px black, -1px 1px black;
}

.name {
	font-family: 'Shapiro 55 Middle Ext';
	font-size: 20px;
	white-space: nowrap;
	text-align: center;
	color: #ffffff;
}

#nameBlockP1 {
	margin: 0px 0px 0px 0px;
}

#nameBlockP2 {
	margin: 0px 0px 0px 0px;
}

.scoreBlock {
	background-color: transparent;
	padding: 0px;
	width: 58px;
	height: 36px;
	align-content: center;
	text-align: center;
	align-items: center;
	text-shadow: 0 0 4px black, 2px 0 black, -2px 0 black, 0 2px black, 0 -2px black, 1px 1px black, -1px -1px black, 1px -1px black, -1px 1px black, 0px 5px 0px black;
}

.score {
	font-family: 'Shapiro 115 Plus Ext';
	font-size: 24px;
	text-align: center;
	color: #ffffff;
}

.centerPanel {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4px;
	margin: 0px 0px;
}

.infoRow {
	background-color: transparent;
	display: flex;
	width: 582px;
	justify-content: center;
}

.infoBar {
	background-color: transparent;
	text-align: center;
	align-content: center;
	padding: 2px 10px;
	margin: 0px 0px;
	color: #ffffff;
}

#topText {
	width: 240px;
	height: 50px;
	font-size: 20px;
	font-family: 'Shapiro 45 Welter Text';
	padding: 2px 0px;
	line-height: 1.2;
}

#stageText, #matchTypeText {
	width: 170px;
	height: 32px;
	font-family: 'Shapiro 45 Welter Text';
	font-size: 16px;
	padding-left: 0px;
	padding-right: 0px;
    padding-bottom: 4px;
}

.imgBlock {
	min-width: 65px;
	height: 49px;
	vertical-align: middle;
	align-items: center;
	display: flex;
	justify-content: center;
	margin-top: 14px;
}

.playerImg {
	vertical-align: middle;
}

.flag-style {
	height: 34.5px;
	width: 46px;
}

.custom-image-style {
	max-height: 34.5px;
	max-width: 46px;
}

.team-custom-image-style {
	max-height: 29px;
	max-width: 39px;
}

.teamsContainer {
	position: absolute;
	display: flex;
	justify-content: center;
	width: 100%;
	margin-top: -13px;
}

#teamsDivider {
	width: 348px;
}

.team {
	display: flex;
	min-width: 276px;
	min-height: 28px;
	align-items: center;
	padding-top: 1px;
}

.team-left {
	justify-content: flex-end;
}

.team-right {
	justify-content: flex-start;
}

.teamText {
	display: flex;
	gap: 0px;
}

#team1Name,
#team2Name {
	width: 236px;
	height: 28px;
	display: inline-flex;
	justify-content: center;
	align-items: center;
	font-size: 16px;
	font-family: 'Shapiro 55 Middle Ext';
}

#team1Score,
#team2Score {
	height: 28px;
	width: 40px;
	display: inline-flex;
	justify-content: center;
	align-items: center;
	font-size: 16px;
	font-family: 'Shapiro 55 Middle Ext';
}

.teamImg {
	width: 39px;
	height: 29px;
	object-fit: contain;
}

:root {
	--fade-duration: 500ms;
}

.fade {
	opacity: 1;
	transition: opacity var(--fade-duration) ease-in-out;
}

.fade-hidden {
	opacity: 0;
}

[data-anim] {
	opacity: 0;
	will-change: transform, opacity;
	--delay: 0ms;
	--dur: 500ms;
}

/* After the entrance animations finish, keep everything visible and prevent any replays */
body.post-entrance [data-anim] {
	opacity: 1;
	transform: none;
	animation: none !important;
}

/* Types of animations */
body.anim-start [data-anim="fade"]  { animation: fade-in         var(--dur) ease-out var(--delay) both; }
body.anim-start [data-anim="up"]    { animation: slide-up-fade   var(--dur) ease-out var(--delay) both; }
body.anim-start [data-anim="down"]  { animation: slide-down-fade var(--dur) ease-out var(--delay) both; }
body.anim-start [data-anim="left"]  { animation: slide-left-fade var(--dur) ease-out var(--delay) both; }
body.anim-start [data-anim="right"] { animation: slide-right-fade var(--dur) ease-out var(--delay) both; }

.bg-img[data-anim] { pointer-events: none; }

/* Overlay animation keyframes */
@keyframes fade-in {
	from { opacity: 0 }
	to   { opacity: 1 }
}

@keyframes slide-up-fade {
	from { transform: translateY(24px); opacity: 0 }
	to   { transform: none;             opacity: 1 }
}

@keyframes slide-down-fade {
	from { transform: translateY(-24px); opacity: 0 }
	to   { transform: none;             opacity: 1 }
}

@keyframes slide-left-fade {
	from { transform: translateX(50px); opacity: 0 }
	to   { transform: none;             opacity: 1 }
}

@keyframes slide-right-fade {
	from { transform: translateX(-50px); opacity: 0 }
	to   { transform: none;              opacity: 1 }
}
</style>

<style scoped>
:global(:root) {
  --main-panel-height: 60px;
  --main-panel-width: 409.28px;

  --back-panel-height: 50px;
  --back-panel-width: 596.6px;

  --name-panel-height: 50px;
  --name-panel-width: 499.19px;
  --name-panel-offset: calc(var(--name-panel-width) * 0.95 * -1);

  --name-text-width: calc(var(--name-panel-width) * 0.845);
  --name-text-height: calc(var(--name-panel-height) * 0.8);
  --name-text-offset-x: calc(var(--name-panel-width) * 0.325);
  --name-text-offset-y: calc(
    var(--name-panel-height) * 0.5 - (var(--name-text-height) * 0.5)
  );

  --flag-height: 50px;
  --flag-width: 120px;
  --flag-offset-x: calc(var(--flag-width) * (0.25 + 0.01));

  --games-text-width: calc(var(--main-panel-width) * 0.11);
  --games-text-height: calc(var(--main-panel-height) * 0.8);
  --games-text-offset-x: calc(var(--main-panel-width) * 0.04);
  --games-text-offset-y: calc(
    var(--main-panel-height) * 0.5 - (var(--games-text-height) * 0.5)
  );

  --progress-text-width: calc(var(--main-panel-width) * 0.65);
  --progress-text-height: calc(var(--main-panel-height) * 0.55);
  --progress-text-offset-x: calc(var(--main-panel-width) * 0.5);
  --progress-text-offset-y: calc(
    var(--main-panel-height) * 0.35 - (var(--progress-text-height) * 0.5)
  );
}

img {
  height: 100%;
}

#scoreboard {
  position: fixed;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
}

#back-panel-wrapper {
  position: absolute;
  height: var(--back-panel-height);
  top: 0;
  left: 0;
  z-index: -2;
  transform: translateX(-50%) translate3d(0, 0, 0);
}

#main-panel {
  filter: drop-shadow(0px 5px 5px rgba(34, 34, 34, 0.85));
}

#main-panel-wrapper {
  position: absolute;
  height: var(--main-panel-height);
  top: 0;
  left: 0;
  z-index: 0;
  transform: translateX(-50%);
}

#progress-text-wrapper {
  position: absolute;
  top: var(--progress-text-offset-y);
  left: var(--progress-text-offset-x);
  width: var(--progress-text-width);
  height: var(--progress-text-height);
  text-align: center;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
}

#progress-text {
  color: #ffffff;
  font-family: 'Bebas Neue Regular', 'Rounded Mplus Regular', sans-serif;
  font-size: 35px;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

#p1-name-wrapper {
  left: var(--name-panel-offset);
  padding-left: var(--flag-width);
  margin-left: calc(var(--flag-width) * -1);
  text-align: left;
}

#p2-name-wrapper {
  right: var(--name-panel-offset);
  padding-right: var(--flag-width);
  margin-right: calc(var(--flag-width) * -1);
  text-align: right;
}

#p1-name-text-wrapper {
  left: var(--name-text-offset-x);
  text-align: left;
}

#p2-name-text-wrapper {
  right: var(--name-text-offset-x);
  text-align: right;
}

#p1-games-text-wrapper {
  left: var(--games-text-offset-x);
}

#p2-games-text-wrapper {
  right: var(--games-text-offset-x);
}

.name-wrapper {
  position: absolute;
  height: var(--name-panel-height);
  top: 0;
  z-index: -2;
  overflow: visible;
  padding-bottom: 20px;
  filter: drop-shadow(0px 2px 5px rgba(34, 34, 34, 0.85));
}

.name-text-wrapper {
  position: absolute;
  top: var(--name-text-offset-y);
  height: var(--name-text-height);
  width: var(--name-text-width);
  line-height: var(--name-text-height);
  font-family: 'Bebas Neue Bold', 'Rounded Mplus Bold', sans-serif;
  font-size: 45px;
  letter-spacing: 0.02em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.name-text-wrapper > div {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.team-text {
  color: #a5a5a5;
  margin-right: 8px;
}

.flag-wrapper {
  position: absolute;
  top: 0;
  height: var(--flag-height);
  width: var(--flag-width);
  z-index: -3;
}

#p1-flag-wrapper {
  left: var(--flag-offset-x);
  clip-path: polygon(0 0, 75% 0, 100% 100%, 25% 100%);
}

#p2-flag-wrapper {
  right: var(--flag-offset-x);
  clip-path: polygon(25% 0, 100% 0, 75% 100%, 0 100%);
}

.flag-mask {
  width: 100%;
  height: var(--flag-height);
}

.flag {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.games-text-wrapper {
  position: absolute;
  top: var(--games-text-offset-y);
  height: var(--games-text-height);
  width: var(--games-text-width);
  text-align: center;
  line-height: var(--games-text-height);
}

.games-text {
  color: #ffffff;
  font-family: 'Gilroy', sans-serif;
  font-weight: bold;
  font-size: 55px;
}

.gamertag-text {
  color: #ffffff;
}
</style>
