/**
 * KSO Chandigarh Timeline Component
 * Interactive timeline for activity logs and system events
 */

class KSOTimeline {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        this.options = {
            showIcons: true,
            showTime: true,
            showDates: true,
            groupByDate: true,
            animations: true,
            loadMore: true,
            itemsPerPage: 10,
            ...options
        };
        this.currentPage = 1;
        this.allItems = [];
        this.init();
    }

    init() {
        this.addStyles();
        this.createTimeline();
    }

    addStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .kso-timeline {
                position: relative;
                margin: 20px 0;
            }

            .kso-timeline::before {
                content: '';
                position: absolute;
                left: 30px;
                top: 0;
                bottom: 0;
                width: 2px;
                background: #e9ecef;
                z-index: 1;
            }

            .kso-timeline-item {
                position: relative;
                margin-bottom: 25px;
                padding-left: 70px;
                opacity: 0;
                transform: translateX(-20px);
                transition: all 0.5s ease;
            }

            .kso-timeline-item.visible {
                opacity: 1;
                transform: translateX(0);
            }

            .kso-timeline-item::before {
                content: '';
                position: absolute;
                left: -40px;
                top: 50%;
                transform: translateY(-50%);
                width: 12px;
                height: 12px;
                background: #007bff;
                border: 3px solid #fff;
                border-radius: 50%;
                z-index: 2;
                box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.3);
            }

            .kso-timeline-item.success::before {
                background: #28a745;
                box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.3);
            }

            .kso-timeline-item.warning::before {
                background: #ffc107;
                box-shadow: 0 0 0 3px rgba(255, 193, 7, 0.3);
            }

            .kso-timeline-item.danger::before {
                background: #dc3545;
                box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.3);
            }

            .kso-timeline-item.info::before {
                background: #17a2b8;
                box-shadow: 0 0 0 3px rgba(23, 162, 184, 0.3);
            }

            .kso-timeline-icon {
                position: absolute;
                left: -46px;
                top: 50%;
                transform: translateY(-50%);
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #007bff;
                color: white;
                border-radius: 50%;
                z-index: 3;
                font-size: 11px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            .kso-timeline-icon.success {
                background: #28a745;
            }

            .kso-timeline-icon.warning {
                background: #ffc107;
            }

            .kso-timeline-icon.danger {
                background: #dc3545;
            }

            .kso-timeline-icon.info {
                background: #17a2b8;
            }

            .kso-timeline-content {
                background: #fff;
                border-radius: 8px;
                padding: 20px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                position: relative;
                border-left: 4px solid #007bff;
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }

            .kso-timeline-content:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }

            .kso-timeline-content.success {
                border-left-color: #28a745;
            }

            .kso-timeline-content.warning {
                border-left-color: #ffc107;
            }

            .kso-timeline-content.danger {
                border-left-color: #dc3545;
            }

            .kso-timeline-content.info {
                border-left-color: #17a2b8;
            }

            .kso-timeline-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 10px;
            }

            .kso-timeline-title {
                font-weight: 600;
                font-size: 16px;
                color: #333;
                margin: 0;
            }

            .kso-timeline-time {
                font-size: 12px;
                color: #6c757d;
                white-space: nowrap;
            }

            .kso-timeline-body {
                color: #666;
                font-size: 14px;
                line-height: 1.5;
                margin-bottom: 15px;
            }

            .kso-timeline-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 12px;
                color: #6c757d;
                border-top: 1px solid #e9ecef;
                padding-top: 10px;
            }

            .kso-timeline-user {
                display: flex;
                align-items: center;
            }

            .kso-timeline-user img {
                width: 24px;
                height: 24px;
                border-radius: 50%;
                margin-right: 8px;
            }

            .kso-timeline-actions {
                display: flex;
                gap: 10px;
            }

            .kso-timeline-action {
                background: none;
                border: none;
                color: #007bff;
                cursor: pointer;
                font-size: 12px;
                padding: 4px 8px;
                border-radius: 4px;
                transition: background-color 0.2s ease;
            }

            .kso-timeline-action:hover {
                background: rgba(0, 123, 255, 0.1);
            }

            .kso-timeline-date-separator {
                position: relative;
                margin: 40px 0 30px 0;
                text-align: center;
            }

            .kso-timeline-date-separator::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                right: 0;
                height: 1px;
                background: #e9ecef;
            }

            .kso-timeline-date-label {
                background: #f8f9fa;
                padding: 8px 16px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 600;
                color: #6c757d;
                text-transform: uppercase;
                position: relative;
                z-index: 2;
                display: inline-block;
            }

            .kso-timeline-load-more {
                text-align: center;
                margin-top: 30px;
            }

            .kso-timeline-load-more button {
                background: #007bff;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.2s ease;
            }

            .kso-timeline-load-more button:hover {
                background: #0056b3;
            }

            .kso-timeline-load-more button:disabled {
                background: #6c757d;
                cursor: not-allowed;
            }

            .kso-timeline-loading {
                text-align: center;
                padding: 20px;
                color: #6c757d;
            }

            .kso-timeline-empty {
                text-align: center;
                padding: 40px;
                color: #6c757d;
            }

            .kso-timeline-empty i {
                font-size: 48px;
                margin-bottom: 16px;
                display: block;
            }

            /* Dark mode */
            .dark-mode .kso-timeline::before {
                background: #495057;
            }

            .dark-mode .kso-timeline-content {
                background: #343a40;
                color: #fff;
            }

            .dark-mode .kso-timeline-title {
                color: #fff;
            }

            .dark-mode .kso-timeline-body {
                color: #ced4da;
            }

            .dark-mode .kso-timeline-footer {
                border-top-color: #495057;
                color: #adb5bd;
            }

            .dark-mode .kso-timeline-date-label {
                background: #495057;
                color: #adb5bd;
            }

            .dark-mode .kso-timeline-date-separator::before {
                background: #495057;
            }

            /* Responsive */
            @media (max-width: 768px) {
                .kso-timeline-item {
                    padding-left: 50px;
                }

                .kso-timeline::before {
                    left: 20px;
                }

                .kso-timeline-icon {
                    left: -32px;
                }

                .kso-timeline-header {
                    flex-direction: column;
                    gap: 5px;
                }

                .kso-timeline-footer {
                    flex-direction: column;
                    gap: 10px;
                    align-items: flex-start;
                }
            }
        `;
        document.head.appendChild(style);
    }

    createTimeline() {
        if (!this.container) return;
        
        this.container.innerHTML = `
            <div class="kso-timeline" id="kso-timeline-content">
                <div class="kso-timeline-loading">
                    <i class="fas fa-spinner fa-spin"></i>
                    <div>Loading timeline...</div>
                </div>
            </div>
        `;
    }

    loadData(data) {
        this.allItems = data;
        this.render();
    }

    render() {
        const timeline = document.getElementById('kso-timeline-content');
        if (!timeline) return;

        timeline.innerHTML = '';

        if (this.allItems.length === 0) {
            timeline.innerHTML = `
                <div class="kso-timeline-empty">
                    <i class="fas fa-history"></i>
                    <div>No activity logs found</div>
                </div>
            `;
            return;
        }

        const itemsToShow = this.allItems.slice(0, this.currentPage * this.options.itemsPerPage);
        const groupedItems = this.options.groupByDate ? this.groupByDate(itemsToShow) : { '': itemsToShow };

        Object.entries(groupedItems).forEach(([date, items]) => {
            if (date && this.options.showDates) {
                const dateElement = document.createElement('div');
                dateElement.className = 'kso-timeline-date-separator';
                dateElement.innerHTML = `<span class="kso-timeline-date-label">${date}</span>`;
                timeline.appendChild(dateElement);
            }

            items.forEach((item, index) => {
                const timelineItem = this.createTimelineItem(item, index);
                timeline.appendChild(timelineItem);
            });
        });

        if (this.options.loadMore && this.allItems.length > this.currentPage * this.options.itemsPerPage) {
            const loadMoreButton = document.createElement('div');
            loadMoreButton.className = 'kso-timeline-load-more';
            loadMoreButton.innerHTML = `
                <button onclick="window.ksoTimeline.loadMore()">
                    Load More Activities
                </button>
            `;
            timeline.appendChild(loadMoreButton);
        }

        if (this.options.animations) {
            this.animateItems();
        }
    }

    createTimelineItem(item, index) {
        const timelineItem = document.createElement('div');
        timelineItem.className = `kso-timeline-item ${item.type || 'info'}`;
        
        const iconHtml = this.options.showIcons ? `
            <div class="kso-timeline-icon ${item.type || 'info'}">
                <i class="${item.icon || 'fas fa-info'}"></i>
            </div>
        ` : '';

        const timeHtml = this.options.showTime ? `
            <div class="kso-timeline-time">${item.time || new Date().toLocaleTimeString()}</div>
        ` : '';

        const userHtml = item.user ? `
            <div class="kso-timeline-user">
                <img src="${item.user.avatar || 'dist/img/default-avatar.png'}" alt="${item.user.name}">
                <span>${item.user.name}</span>
            </div>
        ` : '';

        const actionsHtml = item.actions ? `
            <div class="kso-timeline-actions">
                ${item.actions.map(action => `
                    <button class="kso-timeline-action" onclick="${action.onClick}">
                        ${action.label}
                    </button>
                `).join('')}
            </div>
        ` : '';

        timelineItem.innerHTML = `
            ${iconHtml}
            <div class="kso-timeline-content ${item.type || 'info'}">
                <div class="kso-timeline-header">
                    <h4 class="kso-timeline-title">${item.title}</h4>
                    ${timeHtml}
                </div>
                <div class="kso-timeline-body">${item.description}</div>
                <div class="kso-timeline-footer">
                    ${userHtml}
                    ${actionsHtml}
                </div>
            </div>
        `;

        return timelineItem;
    }

    groupByDate(items) {
        const groups = {};
        items.forEach(item => {
            const date = this.formatDate(item.date || new Date());
            if (!groups[date]) {
                groups[date] = [];
            }
            groups[date].push(item);
        });
        return groups;
    }

    formatDate(date) {
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        
        const itemDate = new Date(date);
        
        if (itemDate.toDateString() === today.toDateString()) {
            return 'Today';
        } else if (itemDate.toDateString() === yesterday.toDateString()) {
            return 'Yesterday';
        } else {
            return itemDate.toLocaleDateString('en-US', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });
        }
    }

    animateItems() {
        const items = document.querySelectorAll('.kso-timeline-item');
        items.forEach((item, index) => {
            setTimeout(() => {
                item.classList.add('visible');
            }, index * 100);
        });
    }

    addItem(item) {
        this.allItems.unshift(item);
        this.render();
    }

    loadMore() {
        this.currentPage++;
        this.render();
    }

    refresh() {
        this.currentPage = 1;
        this.render();
    }

    filter(filterFn) {
        const filtered = this.allItems.filter(filterFn);
        const timeline = document.getElementById('kso-timeline-content');
        
        // Save original data
        const originalItems = this.allItems;
        this.allItems = filtered;
        this.render();
        
        // Restore original data
        this.allItems = originalItems;
    }

    clear() {
        this.allItems = [];
        this.render();
    }
}

// Initialize timeline when needed
window.KSOTimeline = KSOTimeline;
