/**
 * Organization Dashboard
 * Handles real-time updates and interactions
 */

// Mock data for demonstration
const mockData = {
    org: {
        name: "Black Phoenix Initiative",
        tag: "BPI-001",
        status: "Active"
    },
    stats: {
        totalMembers: 24,
        onlineMembers: 8,
        balance: 125000,
        reputation: 5
    },
    membersOnline: [
        { name: "John Doe", rank: "Leader", online: true },
        { name: "Jane Smith", rank: "Officer", online: true },
        { name: "Mike Johnson", rank: "Member", online: true },
        { name: "Sarah Wilson", rank: "Member", online: true },
        { name: "Alex Brown", rank: "Member", online: true },
        { name: "Chris Davis", rank: "Member", online: true },
        { name: "Pat Lee", rank: "Recruit", online: true },
        { name: "Sam Taylor", rank: "Recruit", online: true }
    ],
    activities: [
        { time: "2m ago", text: "Mike Johnson completed mission \"Alpha Strike\"" },
        { time: "15m ago", text: "Jane Smith deposited $5,000 to org bank" },
        { time: "1h ago", text: "New member Alex Brown joined the organization" },
        { time: "2h ago", text: "Organization captured territory: Zone-7" }
    ],
    assets: [
        { icon: "🏢", name: "Headquarters", location: "Downtown" },
        { icon: "🚁", name: "Helicopters", location: "3 units" },
        { icon: "🚗", name: "Vehicles", location: "12 units" },
        { icon: "📦", name: "Storage Units", location: "5 locations" }
    ],
    missions: [
        {
            name: "Supply Run",
            priority: "high",
            description: "Deliver supplies to northern outpost",
            progress: 65
        },
        {
            name: "Recon Operation",
            priority: "medium",
            description: "Scout enemy positions in Zone-4",
            progress: 30
        },
        {
            name: "Territory Defense",
            priority: "low",
            description: "Maintain control of captured zones",
            progress: 90
        }
    ]
};

// Update dashboard with data
function updateDashboard(data) {
    // Update header
    if (data.org) {
        const orgName = document.querySelector('.org-name');
        const orgTag = document.querySelector('.org-tag');
        if (orgName) orgName.textContent = data.org.name;
        if (orgTag) orgTag.textContent = data.org.tag;
    }

    // Update stats
    if (data.stats) {
        const statValues = document.querySelectorAll('.stat-value');
        if (statValues[0]) statValues[0].textContent = data.stats.totalMembers;
        if (statValues[1]) statValues[1].textContent = data.stats.onlineMembers;
        if (statValues[2]) statValues[2].textContent = `$${data.stats.balance.toLocaleString()}`;
        if (statValues[3]) statValues[3].textContent = `${data.stats.reputation}`;
    }

    // Update Members List
    if (data.membersOnline) {
        const memberList = document.querySelector('.member-list');
        if (memberList) {
            memberList.innerHTML = '';
            data.membersOnline.forEach(member => {
                const item = document.createElement('div');
                item.className = 'member-item';
                item.innerHTML = `
                    <div class="member-status ${member.online ? 'online' : 'offline'}"></div>
                    <div class="member-info">
                        <span class="member-name">${member.name}</span>
                        <span class="member-rank">${member.rank}</span>
                    </div>
                `;
                memberList.appendChild(item);
            });

            // Update member count badge
            const memberBadge = document.querySelector('.dashboard-card:nth-child(2) .card-badge');
            if (memberBadge) memberBadge.textContent = data.membersOnline.length;
        }
    }

    // Update Assets List
    if (data.assets) {
        const assetList = document.querySelector('.asset-list');
        if (assetList) {
            assetList.innerHTML = '';
            data.assets.forEach(asset => {
                const item = document.createElement('div');
                item.className = 'asset-item';
                item.innerHTML = `
                    <span class="asset-icon">${asset.icon || '📦'}</span>
                    <div class="asset-info">
                        <span class="asset-name">${asset.name}</span>
                        <span class="asset-location">${asset.location}</span>
                    </div>
                `;
                assetList.appendChild(item);
            });
        }
    }

    // Update Activities List
    if (data.activities) {
        const activityList = document.querySelector('.activity-list');
        if (activityList) {
            activityList.innerHTML = '';
            data.activities.forEach(activity => {
                const item = document.createElement('div');
                item.className = 'activity-item';
                item.innerHTML = `
                    <div class="activity-time">${activity.time}</div>
                    <div class="activity-text">${activity.text}</div>
                `;
                activityList.appendChild(item);
            });
        }
    }

    // Update Missions List
    if (data.missions) {
        const missionList = document.querySelector('.mission-list');
        if (missionList) {
            missionList.innerHTML = '';
            data.missions.forEach(mission => {
                const item = document.createElement('div');
                item.className = 'mission-item';
                item.innerHTML = `
                    <div class="mission-header">
                        <span class="mission-name">${mission.name}</span>
                        <span class="mission-priority ${mission.priority}">${mission.priority.charAt(0).toUpperCase() + mission.priority.slice(1)} Priority</span>
                    </div>
                    <div class="mission-description">${mission.description}</div>
                    <div class="mission-progress">
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${mission.progress}%"></div>
                        </div>
                        <span class="progress-text">${mission.progress}%</span>
                    </div>
                `;
                missionList.appendChild(item);
            });

            // Update mission count badge
            const missionBadge = document.querySelector('.dashboard-card:last-child .card-badge');
            if (missionBadge) missionBadge.textContent = data.missions.length;
        }
    }

    // Re-attach event handlers for new elements if needed
    // Note: The original setupEventHandlers attached to querySelectorAll which only finds elements existing at that time.
    // We should re-run or use delegation. For simplicity, we can re-attach listeners to the new items.
    attachDynamicHandlers(data);
}

function attachDynamicHandlers(data) {
    // Member item clicks
    const memberItems = document.querySelectorAll('.member-item');
    memberItems.forEach((item, index) => {
        item.addEventListener('click', () => {
            const memberData = data.membersOnline ? data.membersOnline[index] : null;
            if (memberData) {
                console.log('Member clicked:', memberData);
                if (typeof A3API !== 'undefined') {
                    A3API.SendAlert(JSON.stringify({
                        event: 'org::member::view',
                        data: { member: memberData }
                    }));
                }
            }
        });
    });

    // Asset item clicks
    const assetItems = document.querySelectorAll('.asset-item');
    assetItems.forEach((item, index) => {
        item.addEventListener('click', () => {
            const assetData = data.assets ? data.assets[index] : null;
            if (assetData) {
                console.log('Asset clicked:', assetData);
                if (typeof A3API !== 'undefined') {
                    A3API.SendAlert(JSON.stringify({
                        event: 'org::asset::view',
                        data: { asset: assetData }
                    }));
                }
            }
        });
    });

    // Mission item clicks
    const missionItems = document.querySelectorAll('.mission-item');
    missionItems.forEach((item, index) => {
        item.addEventListener('click', () => {
            const missionData = data.missions ? data.missions[index] : null;
            if (missionData) {
                console.log('Mission clicked:', missionData);
                if (typeof A3API !== 'undefined') {
                    A3API.SendAlert(JSON.stringify({
                        event: 'org::mission::view',
                        data: { mission: missionData }
                    }));
                }
            }
        });
    });
}

// Static Event Handlers (Close, Settings, etc.)
function setupEventHandlers() {
    // Close button
    const closeBtn = document.querySelector('.close-btn');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            console.log('Closing dashboard...');
            // Send close event to Arma
            if (typeof A3API !== 'undefined') {
                A3API.SendAlert(JSON.stringify({
                    event: 'org::close',
                    data: {}
                }));
            }
        });
    }

    // Settings button
    const settingsBtn = document.querySelectorAll('.action-btn')[0];
    if (settingsBtn && !settingsBtn.classList.contains('close-btn')) {
        settingsBtn.addEventListener('click', () => {
            console.log('Opening settings...');
            // Send settings event to Arma
            if (typeof A3API !== 'undefined') {
                A3API.SendAlert(JSON.stringify({
                    event: 'org::settings',
                    data: {}
                }));
            }
        });
    }
}

// Initialize dashboard
function initDashboard() {
    console.log('Organization Dashboard initializing...');

    // Setup event handlers
    setupEventHandlers();

    // Request live data from Arma
    if (typeof A3API !== 'undefined') {
        A3API.SendAlert(JSON.stringify({
            event: 'org::ready',
            data: {}
        }));
    } else {
        // Use mock data for browser testing/development
        updateDashboard(mockData);
    }

    console.log('Organization Dashboard initialized');
}

// Auto-initialize when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDashboard);
} else {
    initDashboard();
}

// Expose functions globally for Arma integration
window.updateOrgDashboard = updateDashboard;
