<script setup lang="ts">
import {
  mdiBookOpenPageVariantOutline,
  mdiDownload,
} from "@mdi/js";
import { heroMessages, type HeroMessagePhase } from "~/data/heroScene";

const { content } = useLandingContent();
const { t, locale } = useI18n();
const { baseURL } = useRuntimeConfig().app;
const heroRef = ref<HTMLElement | null>(null);
const activeHeroMessageIndex = ref(0);
const heroMessagePhase = ref<HeroMessagePhase>("cooldown");
const isHeroVisible = ref(false);
const heroReducedMotion = ref(false);
let heroMessageTimers: number[] = [];
let heroMessageObserver: IntersectionObserver | null = null;
let heroMotionQuery: MediaQueryList | null = null;

const downloadStore = useDownloadStore();
const { resolve, data: releaseData } = useReleaseDownloads();
const { latestReleaseUrl, releaseDownloadUrl } = useGithubRepo();
const withBase = (path: string) => `${baseURL.replace(/\/?$/, "/")}${path.replace(/^\/+/, "")}`;

useCyberHeroParallax(heroRef);

const releaseVersion = computed(() => releaseData.value?.version || null);
const activeHeroMessage = computed(() => heroMessages[activeHeroMessageIndex.value] ?? null);

const heroDownloadUrl = computed(() => {
  const asset = downloadStore.selectedAsset;
  if (!asset) return latestReleaseUrl.value;
  const arch = asset.os === "macos" ? downloadStore.macArch : asset.arch;
  return resolve(asset.os, arch)?.url || releaseDownloadUrl(asset.fileName);
});

const docsHref = computed(() => withBase(locale.value === "ru" ? "docs/ru/" : "docs/"));

function clearHeroMessageTimers() {
  heroMessageTimers.forEach(window.clearTimeout);
  heroMessageTimers = [];
}

function setHeroMessageTimer(callback: () => void, delay: number) {
  const id = window.setTimeout(callback, delay);
  heroMessageTimers.push(id);
}

function runHeroMessageCycle() {
  clearHeroMessageTimers();

  if (!isHeroVisible.value || heroReducedMotion.value || heroMessages.length === 0) {
    heroMessagePhase.value = "cooldown";
    return;
  }

  heroMessagePhase.value = "sender";
  setHeroMessageTimer(() => {
    heroMessagePhase.value = "packet";
  }, 900);
  setHeroMessageTimer(() => {
    heroMessagePhase.value = "receiver";
  }, 2200);
  setHeroMessageTimer(() => {
    heroMessagePhase.value = "cooldown";
  }, 3900);
  setHeroMessageTimer(() => {
    activeHeroMessageIndex.value = (activeHeroMessageIndex.value + 1) % heroMessages.length;
    runHeroMessageCycle();
  }, 4700);
}

function syncHeroMotion() {
  heroReducedMotion.value = Boolean(heroMotionQuery?.matches);
  runHeroMessageCycle();
}

function onHeroVisibilityChange() {
  if (document.hidden) {
    clearHeroMessageTimers();
    heroMessagePhase.value = "cooldown";
    return;
  }

  runHeroMessageCycle();
}

onMounted(() => {
  downloadStore.init();

  heroMotionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
  heroReducedMotion.value = heroMotionQuery.matches;
  heroMotionQuery.addEventListener("change", syncHeroMotion);
  document.addEventListener("visibilitychange", onHeroVisibilityChange);

  heroMessageObserver = new IntersectionObserver(
    ([entry]) => {
      isHeroVisible.value = Boolean(entry?.isIntersecting);
      runHeroMessageCycle();
    },
    { threshold: 0.15 },
  );

  if (heroRef.value) heroMessageObserver.observe(heroRef.value);
});

onUnmounted(() => {
  clearHeroMessageTimers();
  heroMessageObserver?.disconnect();
  heroMotionQuery?.removeEventListener("change", syncHeroMotion);
  document.removeEventListener("visibilitychange", onHeroVisibilityChange);
});
</script>

<template>
  <section id="hero" ref="heroRef" class="hero-section cyber-hero section anchor-offset" data-cyber-hero>
    <div class="cyber-hero__background" aria-hidden="true" />
    <div class="cyber-hero__wash" aria-hidden="true" />
    <div class="cyber-hero__gridlines" aria-hidden="true" />
    <div class="cyber-hero__scanlines" aria-hidden="true" />

    <v-container class="cyber-hero__container">
      <div class="cyber-hero__layout">
        <div class="cyber-hero__copy">
          <h1 class="cyber-hero__title" aria-label="Agent Teams">
            <span>Agent</span>
            <span class="cyber-hero__title-accent">Teams</span>
          </h1>

          <p class="cyber-hero__slogan cyber-panel">
            Get a lot done by doing very little
          </p>

          <p class="cyber-hero__description">
            {{ content.hero.subtitle }}
          </p>

          <div class="cyber-hero__actions">
            <v-btn
              variant="flat"
              size="large"
              :href="heroDownloadUrl"
              target="_blank"
              class="cyber-hero__action cyber-hero__action--primary"
              :prepend-icon="mdiDownload"
            >
              {{ t("hero.downloadNow") }}
            </v-btn>
            <v-btn
              variant="outlined"
              size="large"
              :href="docsHref"
              class="cyber-hero__action cyber-hero__action--docs"
              :prepend-icon="mdiBookOpenPageVariantOutline"
            >
              {{ t("hero.ctaDocs") }}
            </v-btn>
          </div>

          <p
            v-if="releaseVersion"
            class="cyber-hero__terminal-note cyber-panel"
          >
            <span class="cyber-hero__release">
              v{{ releaseVersion }}
            </span>
          </p>
        </div>

        <CyberHeroScene
          class="cyber-hero__scene"
          :message="activeHeroMessage"
          :phase="heroMessagePhase"
          :reduced-motion="heroReducedMotion"
        />
      </div>

      <CyberHeroFeatureStrip
        class="cyber-hero__feature-strip"
        :active-message="activeHeroMessage"
        :phase="heroMessagePhase"
        :reduced-motion="heroReducedMotion"
      />
    </v-container>
  </section>
</template>
