<script setup lang="ts">
import HeaderLinks from './HeaderLinks.vue';
import SiteOptions from './site_options/SiteOptions.vue';
import StickyHeader from './StickyHeader.vue';
import { accent } from '~/composables/theme'
const spritePath = computed(() => {
    return `/sprites/${accent.value}/${accent.value}.gif`
});
const hasAnimated = useState('title-animated', () => false)

const asciiArt = [
  "█▀█ █▀▄ █▀█ █▀█ █▀▄ █▀█ ▀█▀ █▀▀    █▀▀ █▀█ █▄█",
  "█▀█ █▀▄ █▀█ █ █ █▀▄ █ █  █  █ █    █   █ █ █ █",
  "▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀  ▀▀▀ ▀▀▀ ▀ ▀"
];
const fullText = asciiArt.join('\n');

interface ArtChar {
  char: string;
  done: boolean;
}

const displayedArt = ref<ArtChar[]>([]);
let charIndex = 0;
let intervalId: ReturnType<typeof setInterval> | null = null;

const dragon_names = ["katlum", "solus"];
const sprite_names = dragon_names.map(name => `/sprites/${name}/${name}.gif`);

const preloadImages = (imageArray) => {
  return Promise.all(
    imageArray.map(src => {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = src
        img.onload = resolve
        img.onerror = reject
      })
    })
  )
}

   onMounted(() => {
        preloadImages(sprite_names);

        if (hasAnimated.value || displayedArt.value.length === fullText.length) {
            for (let i = 0; i < fullText.length; i++) {
                displayedArt.value.push({ char: fullText[i], done: true });
            }
            return;
        }

        intervalId = setInterval(() => {
            if (charIndex < fullText.length) {
                displayedArt.value[charIndex] = { char: fullText[charIndex], done: true };
                charIndex++;
            } else {
                clearInterval(intervalId!);
                intervalId = null;
                hasAnimated.value = true;
            }
        }, 5);
    });

  const getGridPos = (idx: number) => {
        let x = 0, y = 0;
        for (let j = 0; j < idx; j++) {
            if (fullText[j] === '\n') { y++; x = 0; }
            else { x++; }
        }
        return { x, y };
    };

    const onCharClick = (index: number, spanEl: HTMLElement) => {
        for (let i = 0; i < fullText.length; i++) {
            if (fullText[i] === '\n') continue;
            const indexGrid = getGridPos(index);
            const charGrid = getGridPos(i);
            let manhattanDistance = Math.abs(indexGrid.x - charGrid.x) + Math.abs(indexGrid.y - charGrid.y);
            let delay = manhattanDistance * 20;
            setTimeout(() => {
                displayedArt.value[i] = { char: fullText[i], done: true };
                const targetSpan = document.querySelector(`.ascii-art span[index="${i}"]`) as HTMLElement;
                if (targetSpan) {
                    targetSpan.style.transition = 'color 80ms ease-out';
                    targetSpan.style.color = 'var(--color-link)';
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            targetSpan.style.color = '';
                        }, 150);
                    });
                }
            }, delay);
        }
    };
    onBeforeUnmount(() => {
        if (intervalId) clearInterval(intervalId);
    });

</script>

<template>
    <div class="header">
        <div class="header-container website">
                <pre class="title ascii-art" aria-label="ARANROIG.COM"><span v-for="(c, i) in displayedArt" :key="i" :index="i.toString()" :class="{ 'char-done': c.done }" @click="onCharClick(i, $event.target as HTMLElement)">{{ c.char }}</span><span class="cursor" :class="{ 'blink': displayedArt.length < fullText.length }" v-if="displayedArt.length < fullText.length">_</span></pre>
                <HeaderLinks></HeaderLinks>
        </div>
        <div class="header-container right">
            <SiteOptions></SiteOptions>
        </div>
    </div>
    <div class="undertable-wrapper">
        <div class="undertable">
            <Sprite :path="spritePath"></Sprite> 
        </div>
    </div>
    <StickyHeader></StickyHeader>
</template>

<style lang="scss" scoped>
.header {
    position: relative;
    margin-top: 30px;
    user-select: none;
    display: flex;
    justify-content: space-between;

    @media screen and (max-width: 670px) {
        flex-direction: column;
        gap: 8px;
    }
}

.header-container {
    
    &.website {
        z-index: 200;
        @media screen and (max-width: 600px) {
            margin-top: 20px;
        }
    }
}

.undertable-wrapper {
    position: relative;
    margin-top: -100px;
    display: flex;
    user-select: none;
    pointer-events: none;
    z-index: 1;

    @media screen and (max-width: 1200px) and (min-width: 900px) {
        margin-top: -340px;
    }

    @media screen and (max-width: 900px) and (min-width: 600px) {
        margin-top: -240px;
    }

    @media screen and (max-width: 600px) {
        margin-top: -300px;
    }

    @media screen and (max-width: 480px) {
        margin-top: -340px;
    }
}

.undertable {
    position: relative;
    width: 160px;
    height: 180px;
}

.web-links {
    position: relative;
    z-index: 200;
    padding: 10px 20px;
    margin-bottom: -10px;
    left: -30px;
    background-color: var(--color-background);
}

.ascii-art {
    font-family: 'Hurmit', monospace;
    font-size: clamp(0.45rem, 1.8vw, 0.85rem);
    line-height: 1.18;
    letter-spacing: -0.05ch;
    white-space: pre;
    color: var(--color-text);
    min-height: clamp(1.59rem, 6.38vw, 3.01rem);
    min-width: clamp(11rem, 44vw, 23rem);

    span:not(.char-done) {
        color: transparent;
    }
}

.char-done {
    opacity: 1;
}

.cursor {
    font-weight: bold;
    color: var(--color-text);

    &.blink {
        animation: blink 1s step-end infinite;
    }
}

@keyframes blink {
  0%, 50%, 100% {
    opacity: 1;
  }
  25%, 75% {
    opacity: 0;
  }
}
</style>
