/**
 * script.js - Core 3D Interactivity & Dynamic Rendering Engine
 * Supports local execution via file:/// protocol.
 */

document.addEventListener('DOMContentLoaded', () => {
    // Check if data is loaded
    if (!window.cvData) {
        console.error("Database data.js failed to load. Ensure it is placed in the same folder.");
        return;
    }
    
    const db = window.cvData;

    // 1. Theme Management (Light/Dark Mode)
    const themeToggleBtn = document.getElementById('theme-toggle');
    const themeIcon = themeToggleBtn.querySelector('i');
    
    const savedTheme = localStorage.getItem('theme');
    const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    
    if (savedTheme === 'light' || (!savedTheme && !systemPrefersDark)) {
        document.documentElement.setAttribute('data-theme', 'light');
        themeIcon.className = 'fas fa-moon';
    } else {
        document.documentElement.setAttribute('data-theme', 'dark');
        themeIcon.className = 'fas fa-sun';
    }
    
    themeToggleBtn.addEventListener('click', () => {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        let newTheme = 'dark';
        
        if (currentTheme === 'dark') {
            newTheme = 'light';
            themeIcon.className = 'fas fa-moon';
        } else {
            themeIcon.className = 'fas fa-sun';
        }
        
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
    });

    // 2. Navigation Mobile Toggles
    const burger = document.getElementById('burger');
    const navLinks = document.getElementById('nav-links');
    const nav = document.querySelector('nav');
    const navItems = document.querySelectorAll('.nav-links a');
    
    burger.addEventListener('click', () => {
        navLinks.classList.toggle('open');
        const burgerIcon = burger.querySelector('i');
        burgerIcon.className = navLinks.classList.contains('open') ? 'fas fa-times' : 'fas fa-bars';
    });

    navItems.forEach(item => {
        item.addEventListener('click', () => {
            navLinks.classList.remove('open');
            burger.querySelector('i').className = 'fas fa-bars';
        });
    });

    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            nav.classList.add('scrolled');
        } else {
            nav.classList.remove('scrolled');
        }
        
        // Highlight active menu on scroll
        const sections = document.querySelectorAll('section');
        let currentSectionId = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop - 110;
            const sectionHeight = section.clientHeight;
            if (window.scrollY >= sectionTop && window.scrollY < sectionTop + sectionHeight) {
                currentSectionId = section.getAttribute('id');
            }
        });
        
        navItems.forEach(item => {
            item.classList.remove('active');
            if (item.getAttribute('href') === `#${currentSectionId}`) {
                item.classList.add('active');
            }
        });
    });

    // 3. Render Profile Header & Bio
    document.title = `${db.profile.name} - Professional 3D CV`;
    document.querySelector('.logo').innerHTML = `<i class="fas fa-shield-halved"></i> ${db.profile.name.split(' ')[0]}<span>.sec</span>`;
    document.querySelector('.footer-logo').innerHTML = `<i class="fas fa-shield-halved"></i> ${db.profile.name}`;
    document.getElementById('profile-name').textContent = db.profile.name;
    document.getElementById('profile-bio').textContent = db.profile.bio;
    // Render Contact Channels
    const emailsContainer = document.getElementById('emails-list-container');
    if (emailsContainer) {
        emailsContainer.innerHTML = `
            <h4>Contact Channels</h4>
            <div class="email-channels-list">
                <div class="email-channel-item" style="--channel-color: var(--accent-cyan);">
                    <i class="fas fa-shield-halved channel-icon"></i>
                    <div class="channel-details">
                        <span class="channel-label">Cybersecurity</span>
                        <a href="mailto:${db.profile.emails.cyber}" class="channel-link">${db.profile.emails.cyber}</a>
                    </div>
                </div>
                <div class="email-channel-item" style="--channel-color: var(--accent-emerald);">
                    <i class="fas fa-laptop-code channel-icon"></i>
                    <div class="channel-details">
                        <span class="channel-label">IT & Software Dev</span>
                        <a href="mailto:${db.profile.emails.it}" class="channel-link">${db.profile.emails.it}</a>
                    </div>
                </div>
                <div class="email-channel-item" style="--channel-color: var(--accent-orange);">
                    <i class="fas fa-chart-line channel-icon"></i>
                    <div class="channel-details">
                        <span class="channel-label">Social Media</span>
                        <a href="mailto:${db.profile.emails.social}" class="channel-link">${db.profile.emails.social}</a>
                    </div>
                </div>
            </div>
        `;
    }
    
    document.getElementById('contact-location').textContent = db.profile.location;
    document.getElementById('contact-web-link').href = db.profile.website;
    document.getElementById('contact-web-link').textContent = db.profile.website.replace('https://', '');
    
    // Render Services Grid
    const servicesContainer = document.getElementById('services-grid-container');
    if (servicesContainer && db.services) {
        servicesContainer.innerHTML = db.services.map(svc => `
            <div class="service-card-wrapper tilt-card-parent">
                <div class="tilt-card service-card-inner" style="--hover-color: ${svc.color};">
                    <div class="tilt-card-content">
                        <div class="service-icon-box" style="color: ${svc.color};">
                            <i class="${svc.icon}"></i>
                        </div>
                        <h3 class="tilt-card-pop">${svc.title}</h3>
                        <p>${svc.desc}</p>
                    </div>
                </div>
            </div>
        `).join('');
    }
    


    // 5. Typewriter Effect
    const typingElement = document.getElementById('typewriter-text');
    let titleIndex = 0;
    let charIndex = 0;
    let isDeleting = false;
    let typingSpeed = 100;
    
    function type() {
        const currentTitle = db.profile.titles[titleIndex];
        
        if (isDeleting) {
            typingElement.textContent = currentTitle.substring(0, charIndex - 1);
            charIndex--;
            typingSpeed = 50;
        } else {
            typingElement.textContent = currentTitle.substring(0, charIndex + 1);
            charIndex++;
            typingSpeed = 100;
        }
        
        if (!isDeleting && charIndex === currentTitle.length) {
            isDeleting = true;
            typingSpeed = 2000;
        } else if (isDeleting && charIndex === 0) {
            isDeleting = false;
            titleIndex = (titleIndex + 1) % db.profile.titles.length;
            typingSpeed = 500;
        }
        
        setTimeout(type, typingSpeed);
    }
    
    if (db.profile.titles.length) {
        type();
    }

    // 6. Render Skills Terminal
    const terminalBody = document.getElementById('terminal-skills-body');
    
    function generateSkillsHTML() {
        let html = '';
        Object.keys(db.skills).forEach(category => {
            const displayStyle = (category === 'security') ? 'grid' : 'none';
            html += `<div class="skill-list-container skill-list" id="skills-${category}" style="display: ${displayStyle};">`;
            
            db.skills[category].forEach(skill => {
                html += `
                    <div class="skill-item">
                        <div class="skill-info">
                            <span class="skill-name">${skill.name}</span>
                            <span class="skill-percentage">${skill.level}%</span>
                        </div>
                        <div class="skill-bar-wrapper">
                            <div class="skill-bar" data-percent="${skill.level}"></div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
        });
        terminalBody.innerHTML = html;
    }
    generateSkillsHTML();

    const skillTabs = document.querySelectorAll('.terminal-tab');
    skillTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const category = tab.getAttribute('data-skill');
            skillTabs.forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            
            const containers = terminalBody.querySelectorAll('.skill-list-container');
            containers.forEach(container => {
                if (container.getAttribute('id') === `skills-${category}`) {
                    container.style.display = 'grid';
                    animateSkills(container);
                } else {
                    container.style.display = 'none';
                }
            });
        });
    });

    function animateSkills(container) {
        const bars = container.querySelectorAll('.skill-bar');
        bars.forEach(bar => {
            const pct = bar.getAttribute('data-percent');
            bar.style.width = pct + '%';
        });
    }

    const skillsSection = document.getElementById('skills');
    const skillsObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const activeContainer = terminalBody.querySelector('.skill-list-container[style*="display: grid"]') || terminalBody.querySelector('.skill-list-container');
                if (activeContainer) {
                    animateSkills(activeContainer);
                }
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.15 });
    
    if (skillsSection) {
        skillsObserver.observe(skillsSection);
    }

    // 8. Render Projects & Articles (Combined Filterable Grid)
    const cardsGrid = document.getElementById('cards-display-grid-container');
    
    function renderCards() {
        let cardList = [];
        
        // Map projects
        db.projects.forEach(p => {
            cardList.push({
                title: p.title,
                category: p.category,
                description: p.description,
                tech: p.tech,
                link: p.link,
                type: 'project'
            });
        });
        
        // Map articles
        db.articles.forEach(a => {
            cardList.push({
                title: a.title,
                category: 'articles',
                description: a.description,
                tech: [a.pubDate],
                link: a.link,
                type: 'article'
            });
        });
        
        cardsGrid.innerHTML = cardList.map(card => `
            <div class="card-element-wrapper tilt-card-parent" data-category="${card.category}">
                <div class="tilt-card grid-card-inner">
                    <div class="tilt-card-content">
                        <div class="card-icon">
                            ${card.type === 'article' ? '<i class="fab fa-medium-m"></i>' : 
                              (card.category === 'security' ? '<i class="fas fa-shield-halved"></i>' : 
                              (card.category === 'mobile' ? '<i class="fab fa-google-play"></i>' : '<i class="fas fa-cloud"></i>'))}
                        </div>
                        <h3 class="tilt-card-pop">${card.title}</h3>
                        <p>${card.description}</p>
                        <div class="card-tags">
                            ${card.tech.map(t => `<span class="card-tag">${t}</span>`).join('')}
                        </div>
                        <a href="${card.link}" target="_blank" class="card-action-link">
                            ${card.type === 'article' ? 'Read Publication' : 'View Project'} <i class="fas fa-arrow-right"></i>
                        </a>
                    </div>
                </div>
            </div>
        `).join('');
        
        // Bind 3D tilt interactions to newly created cards
        init3DTilt();
    }
    renderCards();

    // Cards category filtering logic
    const filterTabs = document.querySelectorAll('.filter-tab-btn');
    filterTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const filterValue = tab.getAttribute('data-filter');
            filterTabs.forEach(b => b.classList.remove('active'));
            tab.classList.add('active');
            
            const cardWrappers = cardsGrid.querySelectorAll('.card-element-wrapper');
            cardWrappers.forEach(card => {
                const cat = card.getAttribute('data-category');
                if (filterValue === 'all' || cat === filterValue) {
                    card.style.display = 'block';
                    card.style.opacity = '0';
                    card.style.transform = 'translateY(15px)';
                    setTimeout(() => {
                        card.style.opacity = '1';
                        card.style.transform = 'translateY(0)';
                        card.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
                    }, 50);
                } else {
                    card.style.display = 'none';
                }
            });
        });
    });

    // 9. Render Social Hub Grid
    const socialsGrid = document.getElementById('socials-hub-grid-container');
    socialsGrid.innerHTML = db.socials.map(soc => {
        const iconContent = soc.svg ? soc.svg : `<i class="${soc.icon}"></i>`;
        return `
            <a href="${soc.url}" target="_blank" class="tilt-card social-card-inner" 
               style="--hover-color: ${soc.color}; background: color-mix(in srgb, ${soc.color} 6%, transparent); border-color: color-mix(in srgb, ${soc.color} 15%, transparent);">
                <div class="tilt-card-content" style="display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%;">
                    <div class="social-icon-box" style="color: ${soc.color};">
                        ${iconContent}
                    </div>
                    <h4 class="tilt-card-pop">${soc.name}</h4>
                    <p>${soc.desc}</p>
                </div>
            </a>
        `;
    }).join('');

    // Render footer links
    const footerLinksContainer = document.getElementById('footer-social-links-container');
    footerLinksContainer.innerHTML = `
        <a href="${db.socials.find(s => s.name === 'LinkedIn').url}" target="_blank" title="LinkedIn"><i class="fab fa-linkedin-in"></i></a>
        <a href="${db.socials.find(s => s.name === 'GitHub').url}" target="_blank" title="GitHub"><i class="fab fa-github"></i></a>
        <a href="${db.socials.find(s => s.name === 'Medium').url}" target="_blank" title="Medium"><i class="fab fa-medium-m"></i></a>
        <a href="${db.profile.website}" target="_blank" title="Website"><i class="fas fa-globe"></i></a>
    `;
    
    document.getElementById('footer-copy-text').innerHTML = `&copy; ${new Date().getFullYear()} ${db.profile.name}. Local Client Sandbox Environment Verified.`;

    // 10. The 3D Tilt Transformation Engine
    function init3DTilt() {
        const tiltCards = document.querySelectorAll('.tilt-card');
        
        tiltCards.forEach(card => {
            card.addEventListener('mousemove', (e) => {
                const rect = card.getBoundingClientRect();
                
                // Mouse position relative to the element
                const x = e.clientX - rect.left; 
                const y = e.clientY - rect.top;
                
                // Normalized coordinate values (-1 to 1)
                const relativeX = (x / rect.width) * 2 - 1;
                const relativeY = (y / rect.height) * 2 - 1;
                
                // Tilt angle multipliers (max 15 degrees)
                const maxTilt = 12;
                const tiltX = -relativeY * maxTilt;
                const tiltY = relativeX * maxTilt;
                
                card.style.transform = `perspective(1000px) rotateX(${tiltX}deg) rotateY(${tiltY}deg) scale3d(1.03, 1.03, 1.03)`;
            });
            
            card.addEventListener('mouseleave', () => {
                card.style.transform = 'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)';
            });
            
            card.addEventListener('mouseenter', () => {
                card.style.transition = 'transform 0.1s ease-out, box-shadow 0.15s ease';
            });
        });
    }

    // 11. Contact Form Local Storage Simulation
    const contactForm = document.getElementById('contactForm');
    const formFeedback = document.getElementById('formFeedback');
    
    if (contactForm) {
        contactForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const name = document.getElementById('form_name').value.trim();
            const email = document.getElementById('form_email').value.trim();
            const subject = document.getElementById('form_subject').value.trim();
            const message = document.getElementById('form_message').value.trim();
            
            if (!name || !email || !subject || !message) {
                showFeedback('Please fill out all transmission fields.', 'error');
                return;
            }
            
            // Show sending state
            showFeedback('Initiating secure peer-to-peer transmission...', 'info');
            const submitBtn = contactForm.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Encrypting Payload...';
            
            // Simulate cryptographic handshake delay
            setTimeout(() => {
                // Save contact entry in localStorage (Mock client-side secure store)
                const inbox = JSON.parse(localStorage.getItem('secure_inbox') || '[]');
                inbox.push({
                    name,
                    email,
                    subject,
                    message,
                    timestamp: new Date().toISOString()
                });
                localStorage.setItem('secure_inbox', JSON.stringify(inbox));
                
                // Show success
                showFeedback('Message encrypted and sent successfully! Local client log entry updated.', 'success');
                contactForm.reset();
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-lock"></i> Send Secure Message';
                
                console.log("=== SECURE TRANSMISSION SIMULATED ===");
                console.log(`Sender: ${name} <${email}>`);
                console.log(`Subject: ${subject}`);
                console.log(`Body: ${message}`);
                console.log("=====================================");
            }, 1200);
        });
    }
    
    function showFeedback(msg, type) {
        formFeedback.textContent = msg;
        formFeedback.className = 'form-feedback';
        
        if (type === 'success') {
            formFeedback.classList.add('success');
        } else if (type === 'error') {
            formFeedback.classList.add('error');
        } else {
            formFeedback.style.display = 'block';
            formFeedback.style.background = 'rgba(0, 242, 254, 0.08)';
            formFeedback.style.color = 'var(--accent-cyan)';
            formFeedback.style.border = '1px solid rgba(0, 242, 254, 0.2)';
        }
    }

    // 12. Interactive Background Canvas (Subtle Particle System)
    const canvas = document.getElementById('bg-canvas');
    if (canvas) {
        const ctx = canvas.getContext('2d');
        let particles = [];
        let numParticles = 60;
        let connectionDistance = 120;
        
        window.addEventListener('resize', initCanvas);
        
        function initCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            
            if (canvas.width < 768) {
                numParticles = 25;
                connectionDistance = 80;
            } else {
                numParticles = 60;
                connectionDistance = 120;
            }
            
            particles = [];
            for (let i = 0; i < numParticles; i++) {
                particles.push({
                    x: Math.random() * canvas.width,
                    y: Math.random() * canvas.height,
                    vx: (Math.random() - 0.5) * 0.4,
                    vy: (Math.random() - 0.5) * 0.4,
                    size: Math.random() * 2 + 1
                });
            }
        }
        
        function getAccentRGB() {
            const isDark = document.documentElement.getAttribute('data-theme') !== 'light';
            return isDark ? { r: 0, g: 242, b: 254 } : { r: 2, g: 132, b: 199 };
        }
        
        function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            const rgb = getAccentRGB();
            const colorStr = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, `;
            
            particles.forEach((p, idx) => {
                p.x += p.vx;
                p.y += p.vy;
                
                if (p.x < 0 || p.x > canvas.width) p.vx = -p.vx;
                if (p.y < 0 || p.y > canvas.height) p.vy = -p.vy;
                
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                ctx.fillStyle = colorStr + '0.3)';
                ctx.fill();
                
                // Draw connecting lines
                for (let j = idx + 1; j < particles.length; j++) {
                    const p2 = particles[j];
                    const dx = p.x - p2.x;
                    const dy = p.y - p2.y;
                    const dist = Math.sqrt(dx * dx + dy * dy);
                    
                    if (dist < connectionDistance) {
                        const alpha = (1 - dist / connectionDistance) * 0.15;
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(p2.x, p2.y);
                        ctx.strokeStyle = colorStr + alpha + ')';
                        ctx.lineWidth = 0.5;
                        ctx.stroke();
                    }
                }
            });
            
            requestAnimationFrame(animate);
        }
        
        initCanvas();
        animate();
    }
});
