'use strict';

/**
 * Research Site - Client-side JavaScript
 * Handles analytics tracking, navigation, and interactive features.
 */

// Configuration
const CONFIG = {
    siteName: 'Site 4726837462198733423',
    version: '1.0.0',
    apiEndpoint: null,
    debugMode: false,
    scrollThreshold: 100,
    observerRootMargin: '0px 0px -10% 0px',
};

// Utility class for common operations
class Utils {
    static generateId(length = 12) {
        const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

    static formatTimestamp(date) {
        return date.toISOString().replace('T', ' ').substring(0, 19);
    }

    static debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    static throttle(func, limit) {
        let inThrottle = false;
        return function executedFunction(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => { inThrottle = false; }, limit);
            }
        };
    }

    static getScrollPercentage() {
        const scrollTop = window.scrollY;
        const docHeight = document.documentElement.scrollHeight - window.innerHeight;
        return docHeight > 0 ? Math.round((scrollTop / docHeight) * 100) : 0;
    }
}

// Page interaction tracker
class InteractionTracker {
    constructor() {
        this.sessionId = Utils.generateId();
        this.startTime = Date.now();
        this.events = [];
        this.maxScrollDepth = 0;
        this.sectionsViewed = new Set();
    }

    logEvent(type, data = {}) {
        const event = {
            type,
            timestamp: Utils.formatTimestamp(new Date()),
            elapsed: Date.now() - this.startTime,
            ...data,
        };
        this.events.push(event);
        if (CONFIG.debugMode) {
            console.log(`[Tracker] ${type}:`, data);
        }
    }

    trackScroll() {
        const pct = Utils.getScrollPercentage();
        if (pct > this.maxScrollDepth) {
            this.maxScrollDepth = pct;
            if (pct % 25 === 0 && pct > 0) {
                this.logEvent('scroll_milestone', { depth: pct });
            }
        }
    }

    trackSectionView(sectionId) {
        if (!this.sectionsViewed.has(sectionId)) {
            this.sectionsViewed.add(sectionId);
            this.logEvent('section_view', { section: sectionId });
        }
    }

    getSummary() {
        return {
            sessionId: this.sessionId,
            duration: Date.now() - this.startTime,
            eventCount: this.events.length,
            maxScrollDepth: this.maxScrollDepth,
            sectionsViewed: Array.from(this.sectionsViewed),
            page: window.location.pathname,
            referrer: document.referrer || 'direct',
            userAgent: navigator.userAgent,
        };
    }
}

// Navigation enhancement
class Navigation {
    constructor() {
        this.header = document.querySelector('header');
        this.lastScrollY = 0;
        this.headerHeight = this.header ? this.header.offsetHeight : 0;
    }

    init() {
        if (!this.header) return;

        // Highlight current page in nav
        const links = document.querySelectorAll('nav ul a');
        const currentPath = window.location.pathname.split('/').pop() || 'index.html';
        links.forEach(link => {
            const href = link.getAttribute('href');
            if (href === currentPath) {
                link.style.color = 'var(--color-primary)';
                link.style.fontWeight = '600';
            }
        });

        // Smooth scroll for anchor links
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', (e) => {
                const target = document.querySelector(anchor.getAttribute('href'));
                if (target) {
                    e.preventDefault();
                    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            });
        });
    }

    handleScroll() {
        const scrollY = window.scrollY;
        if (this.header) {
            if (scrollY > CONFIG.scrollThreshold) {
                this.header.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.3)';
            } else {
                this.header.style.boxShadow = 'none';
            }
        }
        this.lastScrollY = scrollY;
    }
}

// Section observer using IntersectionObserver
class SectionObserver {
    constructor(tracker) {
        this.tracker = tracker;
        this.observer = null;
    }

    init() {
        if (!('IntersectionObserver' in window)) return;

        this.observer = new IntersectionObserver(
            (entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting && entry.target.id) {
                        this.tracker.trackSectionView(entry.target.id);
                    }
                });
            },
            { rootMargin: CONFIG.observerRootMargin, threshold: 0.1 }
        );

        document.querySelectorAll('section[id]').forEach(section => {
            this.observer.observe(section);
        });
    }
}

// File list enhancements
class FileListEnhancer {
    static init() {
        const fileLinks = document.querySelectorAll('#files li a');
        fileLinks.forEach(link => {
            const href = link.getAttribute('href');
            const ext = href.includes('.') ? href.split('.').pop().toLowerCase() : 'none';
            const typeMap = {
                html: 'document', css: 'stylesheet', js: 'script',
                json: 'data', xml: 'data', txt: 'text',
                png: 'image', jpg: 'image', gif: 'image',
                svg: 'image', webp: 'image', log: 'log', zip: 'archive',
                none: 'binary',
            };
            const type = typeMap[ext] || 'file';
            link.setAttribute('data-file-type', type);
            link.title = `${href} (${type})`;
        });
    }
}

// Initialize everything on DOM ready
document.addEventListener('DOMContentLoaded', () => {
    const tracker = new InteractionTracker();
    const nav = new Navigation();
    const sectionObserver = new SectionObserver(tracker);

    nav.init();
    sectionObserver.init();
    FileListEnhancer.init();

    // Scroll tracking
    const handleScroll = Utils.throttle(() => {
        tracker.trackScroll();
        nav.handleScroll();
    }, 150);
    window.addEventListener('scroll', handleScroll, { passive: true });

    // Track page load
    tracker.logEvent('page_load', {
        path: window.location.pathname,
        referrer: document.referrer,
    });

    // Track link clicks
    document.addEventListener('click', (e) => {
        const link = e.target.closest('a');
        if (link) {
            tracker.logEvent('link_click', {
                href: link.getAttribute('href'),
                text: link.textContent.trim().substring(0, 50),
            });
        }
    });

    // Log session summary before unload
    window.addEventListener('beforeunload', () => {
        const summary = tracker.getSummary();
        if (CONFIG.debugMode) {
            console.log('[Tracker] Session summary:', summary);
        }
    });

    if (CONFIG.debugMode) {
        console.log(`[${CONFIG.siteName}] v${CONFIG.version} initialized`);
        console.log(`[Tracker] Session: ${tracker.sessionId}`);
    }
});
