/**
 * SKILLCLIP CORE ENGINE
 * Handles Layout Injection, Physics, Animations, and Theme.
 */

document.addEventListener("DOMContentLoaded", async () => {
    // 1. INJECT LAYOUT (Header & Footer)
    await loadComponent("header-slot", "partials/header.html");
    await loadComponent("footer-slot", "partials/footer.html");

    // 2. INITIALIZE SYSTEMS (Only after HTML is loaded)
    initTheme();           // Dark/Light Mode
    initMobileMenu();      // Mobile Nav Toggle
    highlightActiveLink(); // Auto-highlight current page
    initScrollReveal();    // Reveal animations on scroll
    init3DTilt();          // Hero Card Physics
    initScrollProgress();  // Top reading bar
    
    // 3. FOUC PREVENTION (Fade in body)
    document.body.classList.add('loaded');
});

/* =========================================
   1. DYNAMIC COMPONENT LOADER
   ========================================= */
async function loadComponent(elementId, path) {
    const element = document.getElementById(elementId);
    if (!element) return;

    try {
        // Handle subfolder pathing automatically
        const depth = window.location.pathname.split('/').length - 2;
        // Adjust this prefix logic based on your specific hosting folder depth if needed
        const prefix = depth > 0 ? "../".repeat(depth) : "";
        
        const response = await fetch(prefix + path);
        if (!response.ok) throw new Error(`Failed to load ${path}`);
        
        const html = await response.text();
        element.innerHTML = html;
        
        // Re-run scripts inside injected HTML if necessary (rarely needed for static navs)
    } catch (err) {
        console.error("Layout System Error:", err);
    }
}

/* =========================================
   2. THEME ENGINE (Dark/Light)
   ========================================= */
function initTheme() {
    const toggleBtn = document.getElementById('theme-toggle');
    const html = document.documentElement;

    // Check LocalStorage or System Preference
    const savedTheme = localStorage.getItem('theme');
    const systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

    if (savedTheme === 'dark' || (!savedTheme && systemDark)) {
        html.classList.add('dark');
    } else {
        html.classList.remove('dark');
    }

    if (toggleBtn) {
        toggleBtn.addEventListener('click', () => {
            html.classList.toggle('dark');
            localStorage.setItem('theme', html.classList.contains('dark') ? 'dark' : 'light');
        });
    }
}

/* =========================================
   3. NAVIGATION LOGIC
   ========================================= */
function highlightActiveLink() {
    // Get current filename (e.g., "about.html")
    const currentPath = window.location.pathname.split("/").pop() || "index.html";
    const links = document.querySelectorAll('.nav-link');

    links.forEach(link => {
        const href = link.getAttribute('href');
        // Check if href matches current path (ignoring hash anchors)
        if (href && (href === currentPath || href.startsWith(currentPath + '#'))) {
            link.classList.add('text-brand-blue', 'font-bold');
            link.classList.remove('text-slate-600', 'dark:text-slate-300');
        }
    });
}

function initMobileMenu() {
    const btn = document.getElementById('mobile-menu-btn');
    const menu = document.getElementById('mobile-menu');

    if (btn && menu) {
        btn.addEventListener('click', () => {
            menu.classList.toggle('hidden');
            // Animate entry
            if (!menu.classList.contains('hidden')) {
                menu.classList.add('animate-slide-up');
                menu.style.opacity = "1";
                menu.style.transform = "scaleY(1)";
            } else {
                menu.style.opacity = "0";
                menu.style.transform = "scaleY(0.95)";
            }
        });
    }
}

/* =========================================
   4. SCROLL REVEAL ENGINE
   ========================================= */
function initScrollReveal() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('active');
                // Optional: Stop observing once revealed
                // observer.unobserve(entry.target); 
            }
        });
    }, { 
        threshold: 0.1, // Trigger when 10% visible
        rootMargin: "0px 0px -50px 0px" // Offset trigger slightly
    });

    document.querySelectorAll('.reveal').forEach(el => observer.observe(el));
}

/* =========================================
   5. 3D CARD PHYSICS (High Performance)
   ========================================= */
function init3DTilt() {
    const container = document.querySelector('.hero-perspective');
    const card = document.querySelector('.hero-card');

    if (!container || !card) return;

    container.addEventListener('mousemove', (e) => {
        const rect = container.getBoundingClientRect();
        // Calculate mouse position relative to container
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // Calculate rotation (center is 0)
        const xRotation = -((y - rect.height / 2) / 20); // Max rotation deg
        const yRotation = (x - rect.width / 2) / 20;

        // Use RequestAnimationFrame for smooth 60fps rendering
        requestAnimationFrame(() => {
            card.style.transform = `rotateX(${xRotation}deg) rotateY(${yRotation}deg) scale(1.02)`;
        });
    });

    container.addEventListener('mouseleave', () => {
        requestAnimationFrame(() => {
            card.style.transform = `rotateX(0deg) rotateY(0deg) scale(1)`;
        });
    });
}

/* =========================================
   6. SCROLL PROGRESS BAR
   ========================================= */
function initScrollProgress() {
    const bar = document.getElementById("progress-bar");
    if (!bar) return;

    window.addEventListener('scroll', () => {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const progress = (scrollTop / scrollHeight) * 100;
        
        // Use RequestAnimationFrame for smooth width update
        requestAnimationFrame(() => {
            bar.style.width = progress + "%";
        });
    });
}