export default class RemoteDesktop {
    constructor(os) {
        this.os = os;
        this.element = document.getElementById('remote-desktop');
        this.closeBtn = this.element.querySelector('.close-btn');
        this.launchBtn = this.element.querySelector('#rd-launch-btn');
        this.serverToggle = this.element.querySelector('#rd-server-toggle');
        this.statusIndicator = this.element.querySelector('#rd-status');
        this.statusText = this.element.querySelector('#rd-status-text');
        this.serverUrlInput = this.element.querySelector('#rd-server-url');

        this.serverRunning = false;

        this.initialize();
    }

    initialize() {
        this.closeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.os.closeAllPopups();
        });

        // Launch web client button
        this.launchBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.openWebClient();
        });

        // Server toggle
        this.serverToggle.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleServer();
        });

        // Listen for server status events from Tauri
        this.listenForEvents();
    }

    async listenForEvents() {
        if (window.__TAURI__) {
            try {
                const { listen } = await import('@tauri-apps/api/event');
                await listen('rustdesk-status', (event) => {
                    const { running, pid } = event.payload;
                    this.updateServerStatus(running, pid);
                });
            } catch (e) {
                console.warn('Tauri events not available:', e);
            }
        }
    }

    async toggleServer() {
        if (!window.__TAURI__) {
            this.setStatus('error', 'Requires Tauri runtime');
            return;
        }

        try {
            const { invoke } = await import('@tauri-apps/api/core');

            if (this.serverRunning) {
                this.setStatus('connecting', 'Stopping server...');
                const result = await invoke('stop_rustdesk_server');
                this.updateServerStatus(result.running, result.pid);
            } else {
                this.setStatus('connecting', 'Starting server...');
                const result = await invoke('start_rustdesk_server');
                this.updateServerStatus(result.running, result.pid);
            }
        } catch (err) {
            console.error('Server toggle error:', err);
            this.setStatus('error', `Failed: ${err}`);
            this.serverRunning = false;
            this.serverToggle.classList.remove('rd-toggle-active');
            this.serverToggle.textContent = 'Start Server';
        }
    }

    async openWebClient() {
        this.setStatus('connecting', 'Launching web client...');

        try {
            if (window.__TAURI__) {
                const { invoke } = await import('@tauri-apps/api/core');
                const serverUrl = this.serverUrlInput?.value?.trim() || null;
                await invoke('open_rustdesk_web', { serverUrl });
                this.setStatus('connected', 'Web client opened');
            } else {
                // Dev fallback: open in new browser tab
                const server = this.serverUrlInput?.value?.trim() || 'localhost';
                window.open('https://web.rustdesk.com', '_blank');
                this.setStatus('connected', 'Opened in browser');
            }
        } catch (err) {
            console.error('Failed to open web client:', err);
            this.setStatus('error', `Failed to launch: ${err}`);
        }
    }

    updateServerStatus(running, pid) {
        this.serverRunning = running;
        const toggle = this.serverToggle;

        if (running) {
            this.setStatus('connected', `Server running (PID: ${pid})`);
            toggle.classList.add('rd-toggle-active');
            toggle.textContent = 'Stop Server';
        } else {
            this.setStatus('disconnected', 'Server stopped');
            toggle.classList.remove('rd-toggle-active');
            toggle.textContent = 'Start Server';
        }
    }

    setStatus(state, text) {
        this.statusIndicator.className = 'rd-status-indicator';
        this.statusIndicator.classList.add(`rd-status-${state}`);
        this.statusText.textContent = text;
    }

    async open() {
        this.element.classList.add('active');
        this.os.components.taskbar.updateActiveButton('remoteDesktop');

        // Check current server status
        if (window.__TAURI__) {
            try {
                const { invoke } = await import('@tauri-apps/api/core');
                const result = await invoke('get_rustdesk_status');
                this.updateServerStatus(result.running, result.pid);
            } catch (e) {
                // Ignore - not running in Tauri
            }
        }
    }

    close() {
        this.element.classList.remove('active');
        this.os.components.taskbar.updateActiveButton(null);
    }
}
