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
listen('irc-message', event => {
    if (event.payload) {
    /*const formattedMessage = formatIRCMessage(event.payload);
    if (formattedMessage) {
        addIRCMessage(formattedMessage);
    }*/
    addIRCMessage(event.payload);
    }
});

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