jQuery(document).ready(function($) {
    const webdavApp = {
        init() {
            console.log('WebDAV App Initializing...');
            if (!$('#webdav-panel').length) {
                console.error('WebDAV container not found');
                return;
            }
            this.bindEvents();
            this.renderConnectionForm();
        },

        bindEvents() {
            $('#webdav-connect-form').on('submit', this.handleConnect.bind(this));
            $('#webdav-file-list').on('click', '.webdav-file', this.handleFileClick.bind(this));
        },

        renderConnectionForm() {
            $('#webdav-panel').html(`
                <div class="webdav-connection">
                    <h3>Connect to WebDAV</h3>
                    <form id="webdav-connect-form">
                        <div class="form-group">
                            <label for="webdav-url">Server URL</label>
                            <input type="text" id="webdav-url" placeholder="https://example.com/webdav" required>
                        </div>
                        <div class="form-group">
                            <label for="webdav-username">Username</label>
                            <input type="text" id="webdav-username" required>
                        </div>
                        <div class="form-group">
                            <label for="webdav-password">Password</label>
                            <input type="password" id="webdav-password" required>
                        </div>
                        <button type="submit" class="button button-primary">Connect</button>
                    </form>
                </div>
            `);
        },

        handleConnect(e) {
            e.preventDefault();
            
            const url = $('#webdav-url').val().trim();
            const username = $('#webdav-username').val().trim();
            const password = $('#webdav-password').val();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_webdav_connect',
                    url: url,
                    username: username,
                    password: password,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    console.log('WebDAV Response:', response);
                    if (response.success) {
                        this.showMessage('Connected successfully');
                        this.listFiles('/');
                    } else {
                        this.showMessage('Connection failed: ' + response.data, 'error');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('WebDAV Error:', status, error);
                    this.showMessage('Connection error: ' + error, 'error');
                }
            });
        },

        listFiles(path) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_webdav_list',
                    path: path,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.renderFileList(response.data.files, path);
                    } else {
                        this.showMessage('Error listing files: ' + response.data, 'error');
                    }
                }
            });
        },

        renderFileList(files, currentPath) {
            let html = `
                <div class="webdav-path">
                    <span>Current path: ${currentPath}</span>
                </div>
                <div class="webdav-files">
            `;

            files.forEach(file => {
                const icon = file.type === 'directory' ? 'dashicons-portfolio' : 'dashicons-media-default';
                html += `
                    <div class="webdav-file" data-path="${currentPath}${file.name}" data-type="${file.type}">
                        <span class="dashicons ${icon}"></span>
                        <span class="file-name">${file.name}</span>
                    </div>
                `;
            });

            html += '</div>';
            $('#webdav-panel').html(html);
        },

        handleFileClick(e) {
            const $file = $(e.currentTarget);
            const path = $file.data('path');
            const type = $file.data('type');

            if (type === 'directory') {
                this.listFiles(path);
            } else {
                this.downloadFile(path);
            }
        },

        downloadFile(remotePath) {
            const localPath = prompt('Enter local path to save file:', remotePath.split('/').pop());
            
            if (!localPath) return;

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_webdav_download',
                    remotePath: remotePath,
                    localPath: localPath,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showMessage('File downloaded successfully');
                    } else {
                        this.showMessage('Download failed: ' + response.data, 'error');
                    }
                }
            });
        },

        showMessage(message, type = 'success') {
            const $message = $('#webdav-message');
            $message.text(message).removeClass('error success').addClass(type).fadeIn();
            setTimeout(() => $message.fadeOut(), 3000);
        }
    };

    webdavApp.init();
});