const { invoke } = window.__TAURI__.core;
const { listen } = window.__TAURI__.event;

// Original Tauri integration code
async function refreshChannels() {
    try {
    const channels = await invoke("list_channels");
    // Clear existing channels that aren't in the new list
    const currentChannels = [...uiState.channels];
    currentChannels.forEach(ch => {
        if (!channels.includes(ch)) {
        removeChannel(ch);
        }
    });
    
    // Add new channels
    channels.forEach(ch => {
        if (!uiState.channels.includes(ch)) {
        addChannel(ch);
        }
    });
    } catch (e) {
    addSystemMessage("Failed to refresh channels: " + e);
    }
}

// Override the connect button handler to use Tauri
connectBtn.onclick = async () => {
    const server = document.getElementById('server').value.trim();
    const port = Number(document.getElementById('port').value);
    const nickname = document.getElementById('nickname').value.trim();

    if (!server || !port || !nickname) {
    addSystemMessage('Please fill in server, port, and nickname.');
    return;
    }

    try {
    await invoke('connect', {
        server: server,
        port: port,
        nickname: nickname,
        useTls: false
    });

    uiState.connected = true;
    updateConnectionStatus();
    addSystemMessage('Connected to ' + server);
    
    // Refresh channels after connection
    setTimeout(refreshChannels, 1000);
    } catch(e) {
    addSystemMessage('Connection failed: ' + e);
    }
};

// Override the disconnect button handler to use Tauri
disconnectBtn.onclick = async () => {
    try {
    await invoke('disconnect');
    uiState.connected = false;
    updateConnectionStatus();
    
    // Clear channels and tabs
    uiState.channels.forEach(channel => {
        removeChannel(channel);
    });
    setActiveTab('welcome');
    addSystemMessage('Disconnected');
    } catch(e) {
    addSystemMessage('Disconnect failed: ' + e);
    }
};

// Override the join button handler to use Tauri
joinBtn.onclick = async () => {
    let channel = channelInput.value.trim();
    if (!channel) return;
    
    if (!channel.startsWith('#')) {
    channel = '#' + channel;
    channelInput.value = channel;
    }
    
    try {
    await invoke('join_channel', { channel });
    addChannel(channel);
    channelInput.value = '';
    } catch(e) {
    addSystemMessage(`Failed to join ${channel}: ${e}`);
    }
};

// Override the part button handler to use Tauri
partBtn.onclick = async () => {
    const channel = uiState.activeTab;
    if (!channel || channel === 'welcome') {
    addSystemMessage('Select a channel to leave first.');
    return;
    }
    
    try {
    await invoke('part_channel', { channel });
    removeChannel(channel);
    } catch(e) {
    addSystemMessage(`Failed to leave ${channel}: ${e}`);
    }
};

// Override the send button handler to use Tauri
sendBtn.onclick = async () => {
    const target = uiState.activeTab;
    const message = messageInput.value.trim();
    
    if (!target || target === 'welcome') {
    addSystemMessage('Join a channel to send messages.');
    return;
    }
    
    if (!message) return;
    
    try {
    await invoke('send_message', { target, message });
    addMessage(uiState.currentUser, message, true);
    messageInput.value = '';
    } catch(e) {
    addSystemMessage(`Failed to send message: ${e}`);
    }
};

// Listen to backend IRC messages (async processing)
listen('irc-message', event => {
    if (event.payload) {
        const message = event.payload;
        
        // Process message parsing asynchronously to avoid blocking
        setTimeout(() => {
            // Check if this is a NAMES message
            if (typeof message === 'string' && message.includes('NAMES')) {
                // Parse NAMES message: extract channel and users
                // Format from backend: <span>server</span><span>[</span><span>NAMES</span><span>]</span> <span>channel</span><span>: </span><span>user1</span> <span>user2</span>...
                // Match pattern: NAMES</span> ... <span>channel</span><span>: </span>users...
                const namesMatch = message.match(/NAMES<\/span><span[^>]*>\]<\/span>\s*<span[^>]*>([^<]+)<\/span><span[^>]*>:\s*<\/span>(.*)/);
                if (namesMatch) {
                    const channel = namesMatch[1].trim();
                    const usersHtml = namesMatch[2];
                    
                    // Extract all user names from spans (they may have different styles) - async
                    requestAnimationFrame(() => {
                        const userMatches = usersHtml.matchAll(/<span[^>]*>([^<]+)<\/span>/g);
                        const users = Array.from(userMatches, m => m[1].trim()).filter(u => u && u.length > 0);
                        const usersStr = users.join(' ');
                        
                        if (channel && usersStr) {
                            parseNamesMessage(channel, usersStr);
                        }
                    });
                } else {
                    // Try simpler pattern - just look for channel after NAMES
                    const altMatch = message.match(/NAMES.*?<span[^>]*>([^<]+)<\/span><span[^>]*>:\s*<\/span>(.*)/);
                    if (altMatch) {
                        const channel = altMatch[1].trim();
                        const usersHtml = altMatch[2];
                        requestAnimationFrame(() => {
                            const userMatches = usersHtml.matchAll(/<span[^>]*>([^<]+)<\/span>/g);
                            const users = Array.from(userMatches, m => m[1].trim()).filter(u => u && u.length > 0);
                            const usersStr = users.join(' ');
                            if (channel && usersStr) {
                                parseNamesMessage(channel, usersStr);
                            }
                        });
                    }
                }
            } else if (typeof message === 'string' && message.includes('ENDOFNAMES')) {
                // When ENDOFNAMES is received, the list is complete
                // Extract channel to mark list as complete (optional - for future use)
                const endMatch = message.match(/ENDOFNAMES.*?<span[^>]*>([^<]+)<\/span>/);
                if (endMatch) {
                    const channel = endMatch[1].trim();
                    // List is complete, ensure it's displayed (async)
                    requestAnimationFrame(() => {
                        if (uiState.activeTab === channel) {
                            updatePeopleList(channel);
                        }
                    });
                }
            }
        }, 0);
        
        // Display message asynchronously
        requestAnimationFrame(() => {
            addIRCMessage(message);
        });
    }
});

// Listen for channel updates
listen('channel-update', event => {
    if (event.payload) {
    refreshChannels();
    }
});