---
import { Picture } from 'astro:assets';
import heroPortrait from '../../assets/nicholai-closeup-portrait.avif';

interface Props {
	headlineLine1: string;
	headlineLine2: string;
	portfolioYear: string;
	location: string;
	locationLabel: string;
	bio: string;
}

const { headlineLine1, headlineLine2, portfolioYear, location, locationLabel, bio } = Astro.props;
---
<section id="hero" class="relative w-full h-[100dvh] overflow-hidden bg-[var(--theme-bg-primary)]">
    <!-- Industrial Scanlines -->
    <div class="absolute inset-0 z-1 pointer-events-none opacity-[0.03] bg-[linear-gradient(rgba(18,16,16,0)_50%,rgba(0,0,0,0.25)_50%),linear-gradient(90deg,rgba(255,0,0,0.06),rgba(0,255,0,0.02),rgba(0,0,112,0.06))] bg-[length:100%_2px,3px_100%]"></div>
    
    <!-- Background Image (Portrait) - Optimized with AVIF/WebP -->
    <div class="absolute top-0 right-0 w-full md:w-1/2 h-full z-0">
        <div class="relative w-full h-full">
            <Picture
                src={heroPortrait}
                formats={['avif', 'webp']}
                widths={[640, 1024, 1600]}
                sizes="(max-width: 768px) 100vw, 50vw"
                alt="Nicholai Vogel portrait"
                class="w-full h-full object-cover object-center opacity-0 mix-blend-luminosity transition-opacity duration-[2500ms] ease-out delay-700 intro-element"
                id="hero-portrait"
                loading="eager"
                decoding="sync"
            />
            <div class="absolute inset-0 bg-gradient-to-l from-transparent via-[var(--theme-hero-gradient-side)] to-[var(--theme-bg-primary)] transition-colors duration-500"></div>
            <div class="absolute inset-0 bg-gradient-to-t from-[var(--theme-bg-primary)] via-transparent to-transparent transition-colors duration-500"></div>
            
            <!-- Technical Overlay Elements -->
            <div class="absolute bottom-12 right-12 hidden lg:flex flex-col items-end gap-1 font-mono text-[9px] text-brand-accent/40 uppercase tracking-[0.3em] intro-element opacity-0 delay-1000">
                <span>COORD: 38.8339° N, 104.8214° W</span>
                <span>ELV: 1,839M</span>
                <div class="flex gap-2 mt-2">
                    <div class="w-8 h-px bg-brand-accent/20"></div>
                    <div class="w-2 h-px bg-brand-accent/40"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- The 100 Squares Grid Overlay -->
    <div id="grid-container" class="absolute inset-0 z-10 w-full h-full grid grid-cols-10 grid-rows-10 pointer-events-none">
        {Array.from({ length: 100 }).map((_, i) => (
            <div class="grid-cell w-full h-full border border-[var(--theme-border-secondary)] opacity-0 transition-all duration-500 ease-out" data-index={i}></div>
        ))}
    </div>

    <!-- The Content -->
    <!-- Mobile: pt-24 clears mobile top bar. Desktop: pt-16 since nav is on left side -->
    <div class="absolute inset-0 z-20 flex flex-col justify-between p-6 md:p-12 lg:p-16 pt-24 lg:pt-16 pointer-events-auto">

        <!-- Top Metadata -->
        <div class="flex justify-between items-start w-full intro-element opacity-0 translate-y-4 transition-all duration-1000 ease-out delay-300">
            <div class="flex items-center gap-3">
                <div class="w-1.5 h-1.5 bg-brand-accent animate-pulse"></div>
                <div class="font-mono text-[10px] uppercase tracking-[0.2em] text-[var(--theme-text-muted)]">
                    <span class="text-brand-accent mr-1">SYS.PRTF</span> / {portfolioYear}
                </div>
            </div>
            
            <div class="font-mono text-[10px] text-[var(--theme-text-muted)] text-right tracking-[0.15em] uppercase">
                <div class="mb-1 flex items-center justify-end gap-2">
                    <span class="text-[var(--theme-text-subtle)]">{locationLabel}</span>
                    <span class="text-brand-accent font-bold">///</span>
                </div>
                <div class="text-[var(--theme-text-secondary)]">{location}</div>
                <div id="clock" class="text-brand-accent mt-0.5">00:00:00 MST</div>
            </div>
        </div>

        <!-- Main Heading & Description -->
        <div class="max-w-5xl">
            <h1 class="text-6xl md:text-8xl lg:text-9xl tracking-tighter leading-[0.85] font-bold text-[var(--theme-text-primary)] mb-8 perspective-text">
                <span class="block intro-element opacity-0 translate-y-10 transition-all duration-1000 ease-out delay-100">{headlineLine1}</span>
                <span class="block text-brand-accent opacity-0 translate-y-10 transition-all duration-1000 ease-out delay-200 intro-element">{headlineLine2}</span>
            </h1>

            <p class="font-mono text-sm md:text-base max-w-lg text-[var(--theme-text-secondary)] font-light leading-relaxed intro-element opacity-0 translate-y-6 transition-all duration-1000 ease-out delay-500">
                {bio}
            </p>
        </div>

        <!-- Bottom Navigation -->
        <div class="flex justify-between items-end w-full intro-element opacity-0 transition-all duration-1000 ease-out delay-700">
            <a href="#experience" class="group flex items-center gap-6 py-2">
                <div class="relative w-12 h-12 flex items-center justify-center border border-[var(--theme-border-primary)] text-brand-accent hover:border-brand-accent hover:bg-brand-accent/5 transition-all duration-300">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="square" stroke-linejoin="miter" class="group-hover:translate-y-1 transition-transform duration-300">
                        <path d="M7 13l5 5 5-5M12 6v12"/>
                    </svg>
                    <!-- Technical Corner Accent -->
                    <div class="absolute -top-px -left-px w-2 h-2 border-t border-l border-brand-accent opacity-0 group-hover:opacity-100 transition-opacity"></div>
                    <div class="absolute -bottom-px -right-px w-2 h-2 border-b border-r border-brand-accent opacity-0 group-hover:opacity-100 transition-opacity"></div>
                </div>
                <div class="flex flex-col font-mono text-[10px] uppercase tracking-[0.2em]">
                    <span class="text-[var(--theme-text-muted)] group-hover:text-brand-accent transition-colors">Scroll</span>
                    <span class="text-[var(--theme-text-subtle)] group-hover:text-[var(--theme-text-secondary)] transition-colors">To Explore</span>
                </div>
            </a>

            <div class="hidden md:block text-right font-mono text-[10px] text-[var(--theme-text-muted)] tracking-[0.2em] uppercase">
                <span class="text-[var(--theme-text-subtle)]">STATUS:</span> <span class="text-brand-accent">READY_FOR_INPUT</span><br>
                <span class="text-[var(--theme-text-subtle)]">INDEX:</span> 00.01 / 05.00
            </div>
        </div>
    </div>
</section>

<style>
    .grid-cell.active {
        background-color: var(--color-brand-accent);
        opacity: 0.15;
        transition: opacity 0s, background-color 0s; /* Instant on */
    }
    /* Fade out */
    .grid-cell {
        /* Snappier fade-out */
        transition: opacity 0.6s ease-out, background-color 0.6s ease-out;
    }

    /* Initial Loaded State Classes */
    .intro-visible {
        opacity: 1 !important;
        transform: translateY(0) !important;
    }

    /* Portrait Loaded State */
    .portrait-visible {
        opacity: 0.4 !important; /* Mobile default */
    }
    @media (min-width: 768px) {
        .portrait-visible {
            opacity: 0.6 !important; /* Desktop default */
        }
    }
</style>

<script>
    const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ?? false;
    const finePointer = window.matchMedia?.('(pointer: fine) and (hover: hover)')?.matches ?? false;

    // Track active timers to clear them on navigation/cleanup
    let clockTimer: number | undefined;
    let pulseInterval: number | undefined;

    function cleanup() {
        if (clockTimer) window.clearTimeout(clockTimer);
        if (pulseInterval) window.clearInterval(pulseInterval);
        clockTimer = undefined;
        pulseInterval = undefined;
    }

    function initHero() {
        // Clean up previous instances first
        cleanup();

        // ===== CLOCK =====
        const clock = document.getElementById('clock');
        if (clock) {
            function updateClockOnce() {
                if (!clock) return;
                const now = new Date();
                const timeString = now.toLocaleTimeString('en-US', { hour12: false, timeZone: 'America/Denver' });
                clock.textContent = `${timeString} MST`;
            }

            function startClock() {
                const tick = () => {
                    // Stop if element is gone
                    if (!document.body.contains(clock)) return;

                    if (document.hidden) {
                        clockTimer = window.setTimeout(tick, 1000);
                        return;
                    }

                    updateClockOnce();
                    // Align to the next second boundary to reduce drift.
                    const msToNextSecond = 1000 - (Date.now() % 1000);
                    clockTimer = window.setTimeout(tick, msToNextSecond);
                };
                tick();
            }
            startClock();
        }

        // ===== INTRO ANIMATIONS =====
        // Trigger Intro Elements
        const introElements = document.querySelectorAll('.intro-element');
        introElements.forEach(el => {
            el.classList.add('intro-visible');
        });

        // Trigger Portrait
        const portrait = document.getElementById('hero-portrait');
        if (portrait) {
            portrait.classList.add('portrait-visible');
        }

        const section = document.getElementById('hero');
        const cells = document.querySelectorAll('.grid-cell');

        // Trigger Grid Ripple (skip if reduced motion)
        if (!reduceMotion && cells.length > 0) {
            // Diagonal sweep effect
            cells.forEach((cell, i) => {
                const row = Math.floor(i / 10);
                const col = i % 10;
                const delay = (row + col) * 45; // slightly faster diagonal delay

                window.setTimeout(() => {
                    cell.classList.add('active');
                    window.setTimeout(() => {
                        cell.classList.remove('active');
                    }, 180);
                }, delay);
            });
        }

        // ===== GRID INTERACTION =====
        if (section && cells.length > 0) {
            // Throttle mousemove work to one update per frame.
            let latestX = 0;
            let latestY = 0;
            let pending = false;
            let lastIndex = -1;
            const timeouts: number[] = new Array(cells.length).fill(0);

            const process = () => {
                pending = false;
                if (!finePointer || reduceMotion) return;
                
                // Safety check if section is still valid
                if (!document.body.contains(section)) return;

                const rect = section.getBoundingClientRect();
                const width = rect.width;
                const height = rect.height;
                if (width <= 0 || height <= 0) return;

                const x = latestX - rect.left;
                const y = latestY - rect.top;

                const col = Math.floor((x / width) * 10);
                const row = Math.floor((y / height) * 10);

                if (col < 0 || col >= 10 || row < 0 || row >= 10) return;

                const index = row * 10 + col;
                if (index === lastIndex) return;
                lastIndex = index;

                const cell = cells[index] as HTMLElement | undefined;
                if (!cell) return;

                cell.classList.add('active');

                const prev = timeouts[index];
                if (prev) window.clearTimeout(prev);

                // Shorter hold time for a quicker trail.
                timeouts[index] = window.setTimeout(() => {
                    cell.classList.remove('active');
                    timeouts[index] = 0;
                }, 35);
            };

            section.addEventListener('mousemove', (e) => {
                latestX = e.clientX;
                latestY = e.clientY;
                if (pending) return;
                pending = true;
                window.requestAnimationFrame(process);
            }, { passive: true });
        }

        // ===== PULSE ANIMATION =====
        if (finePointer && !reduceMotion && cells.length > 0) {
            pulseInterval = window.setInterval(() => {
                if (document.hidden) return;
                
                // Stop if elements are gone
                if (cells.length > 0 && !document.body.contains(cells[0])) {
                    clearInterval(pulseInterval);
                    return;
                }

                const randomIndex = Math.floor(Math.random() * cells.length);
                const cell = cells[randomIndex] as HTMLElement | undefined;
                if (!cell) return;

                cell.classList.add('active');
                window.setTimeout(() => {
                    cell.classList.remove('active');
                }, 160);
            }, 1200);
        }
    }

    // Run on every navigation
    document.addEventListener('astro:page-load', initHero);
    
    // Clean up before swap
    document.addEventListener('astro:before-swap', cleanup);
    
    // Visibility change handler for clock updates (keep persistent)
    document.addEventListener('visibilitychange', () => {
        const clock = document.getElementById('clock');
        if (!document.hidden && clock) {
            const now = new Date();
            const timeString = now.toLocaleTimeString('en-US', { hour12: false, timeZone: 'America/Denver' });
            clock.textContent = `${timeString} MST`;
        }
    });
</script>
