<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';

interface Star {
    x: number;
    y: number;
    size: number;
    opacity: number;
    speed: number;
}

const starCanvasRef = ref<HTMLCanvasElement | null>(null);
let backgroundStars: Star[] = [];
let animationFrameId: number;

function initBackgroundStars() {
    if (typeof window === 'undefined' || !starCanvasRef.value) return;

    const canvas = starCanvasRef.value;
    // Explizite Zuweisung der Fenstergröße an die Canvas-Attribute
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    backgroundStars = [];
    const count = Math.min(window.innerWidth / 3, 400); // Etwas mehr Sterne für bessere Sichtbarkeit

    for (let i = 0; i < count; i++) {
        backgroundStars.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height,
            size: Math.random() * 1.5 + 0.5,
            opacity: Math.random(),
            speed: Math.random() * 0.15 + 0.05,
        });
    }
}

function drawBackgroundStars() {
    if (typeof window === 'undefined') return;
    const canvas = starCanvasRef.value;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i < backgroundStars.length; i++) {
        const s = backgroundStars[i];

        s.opacity += (Math.random() - 0.5) * 0.03;
        if (s.opacity <= 0.1) s.opacity = 0.1;
        if (s.opacity >= 0.8) s.opacity = 0.8;

        ctx.fillStyle = `rgba(255, 255, 255, ${s.opacity})`;
        ctx.beginPath();
        ctx.arc(s.x, s.y, s.size, 0, Math.PI * 2);
        ctx.fill();

        s.y -= s.speed;
        if (s.y < -10) {
            s.y = canvas.height + 10;
            s.x = Math.random() * canvas.width;
        }
    }
    animationFrameId = requestAnimationFrame(drawBackgroundStars);
}

const handleResize = () => {
    initBackgroundStars();
};

onMounted(() => {
    initBackgroundStars();
    drawBackgroundStars();
    window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
    if (typeof window !== 'undefined') {
        window.removeEventListener('resize', handleResize);
    }
    if (animationFrameId) cancelAnimationFrame(animationFrameId);
});
</script>

<template>
    <div
        class="pointer-events-none fixed inset-0 h-full w-full"
        style="z-index: 0"
    >
        <div class="absolute inset-0 bg-[#020617]"></div>

        <canvas
            ref="starCanvasRef"
            class="absolute inset-0 block h-full w-full"
        ></canvas>

        <div
            class="absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,#020617_100%)] opacity-60"
        ></div>
    </div>
</template>
