jQuery(document).ready(function($) {
    const cloudSyncApp = {
        init() {
            this.bindEvents();
            this.loadProtocolSettings('webdav'); // 默认加载WebDAV设置
        },

        bindEvents() {
            // 协议标签切换
            $('.protocol-tab').on('click', (e) => {
                const protocol = $(e.currentTarget).data('protocol');
                this.loadProtocolSettings(protocol);
            });

            // 连接按钮
            $('#protocol-settings').on('submit', '.protocol-form', this.handleConnect.bind(this));
        },

        loadProtocolSettings(protocol) {
            $('.protocol-tab').removeClass('active');
            $(`.protocol-tab[data-protocol="${protocol}"]`).addClass('active');

            const formHtml = this.getProtocolForm(protocol);
            $('#protocol-settings').html(formHtml);
        },

        getProtocolForm(protocol) {
            const forms = {
                'webdav': this.generateForm('webdav', 'WebDAV Settings', [
                    {type: 'url', id: 'url', label: 'Server URL', placeholder: 'https://example.com/webdav', required: true},
                    {type: 'text', id: 'username', label: 'Username', required: true},
                    {type: 'password', id: 'password', label: 'Password', required: true}
                ]),
                'ftp': this.generateForm('ftp', 'FTP Settings', [
                    {type: 'text', id: 'host', label: 'Host', placeholder: 'ftp.example.com', required: true},
                    {type: 'number', id: 'port', label: 'Port', value: '21'},
                    {type: 'text', id: 'username', label: 'Username'},
                    {type: 'password', id: 'password', label: 'Password'}
                ]),
                'sftp': this.generateForm('sftp', 'SFTP Settings', [
                    {type: 'text', id: 'host', label: 'Host', placeholder: 'sftp.example.com', required: true},
                    {type: 'number', id: 'port', label: 'Port', value: '22'},
                    {type: 'text', id: 'username', label: 'Username', required: true},
                    {type: 'password', id: 'password', label: 'Password'},
                    {type: 'text', id: 'private-key', label: 'Private Key (optional)', placeholder: '/path/to/private_key'}
                ]),
                'alist': this.generateForm('alist', 'Alist Settings', [
                    {type: 'text', id: 'url', label: 'Alist URL', required: true},
                    {type: 'text', id: 'username', label: 'Username'},
                    {type: 'password', id: 'password', label: 'Password'},
                    {type: 'text', id: 'token', label: 'Token (optional)'}
                ]),
                'baidu': this.generateForm('baidu', '百度云盘 Settings', [
                    {type: 'text', id: 'access-key', label: 'Access Key', required: true},
                    {type: 'text', id: 'secret-key', label: 'Secret Key', required: true},
                    {type: 'text', id: 'bucket', label: 'Bucket Name'}
                ]),
                'smb': this.generateForm('smb', 'SMB Settings', [
                    {type: 'text', id: 'host', label: 'Host/IP', required: true},
                    {type: 'text', id: 'share', label: 'Share Name', required: true},
                    {type: 'text', id: 'username', label: 'Username'},
                    {type: 'password', id: 'password', label: 'Password'},
                    {type: 'text', id: 'domain', label: 'Domain (optional)'}
                ])
            };

            return forms[protocol] || '<div class="protocol-settings"><p>Protocol settings not available yet.</p></div>';
        },

        generateForm(protocol, title, fields) {
            let formHtml = `
                <div class="protocol-settings">
                    <h3>${title}</h3>
                    <form class="protocol-form" data-protocol="${protocol}">
            `;

            fields.forEach(field => {
                formHtml += `
                    <div class="form-group">
                        <label for="${protocol}-${field.id}">${field.label}</label>
                        <input type="${field.type}" id="${protocol}-${field.id}" 
                               ${field.placeholder ? `placeholder="${field.placeholder}"` : ''}
                               ${field.value ? `value="${field.value}"` : ''}
                               ${field.required ? 'required' : ''}>
                    </div>
                `;
            });

            formHtml += `
                        <div class="form-actions">
                            <button type="submit" class="button button-primary">Connect</button>
                        </div>
                    </form>
                </div>
            `;

            return formHtml;
        },

        handleConnect(e) {
            e.preventDefault();
            const $form = $(e.currentTarget);
            const protocol = $form.data('protocol');
            
            const data = {
                action: 'code_editor_cloud_connect',
                protocol: protocol,
                security: codeEditorVars.nonce
            };

            // 收集表单数据
            $form.find('input').each(function() {
                const id = $(this).attr('id').replace(protocol + '-', '');
                data[id] = $(this).val();
            });

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: data,
                success: (response) => {
                    if (response.success) {
                        this.showMessage('Connected successfully');
                    } else {
                        this.showMessage('Connection failed: ' + response.data, 'error');
                    }
                }
            });
        },

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

    cloudSyncApp.init();
});