<template>
    <div class="settingsPage">
        <Toast
            ref="toast"
            :message="toast.message"
            :type="toast.type"
            :duration="toast.duration"
        />
        <div class="settingsPage__container">
            <section class="settingsCard">
                <h1 class="settingsCard__title">Settings</h1>
                <p class="settingsCard__description">Configure your application preferences</p>

                <div class="settingsCard__body">
                    <!-- General Settings Section -->
                    <div class="settingsSection">
                        <button
                            type="button"
                            class="settingsSection__header"
                            @click="toggleSection('general')"
                        >
                            <span class="settingsSection__title">General Settings</span>
                            <span class="settingsSection__icon" :class="{ 'settingsSection__icon--open': sections.general }">&#9660;</span>
                        </button>
                        <div v-show="sections.general" class="settingsSection__content">
                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Title</label>
                                <input
                                    v-model="settings.title"
                                    type="text"
                                    class="settingsFormGroup__input"
                                    :class="{ 'settingsFormGroup__input--error': errors.title }"
                                    placeholder="Enter title"
                                    @blur="validateField('title')"
                                />
                                <p v-if="errors.title" class="settingsFormGroup__error">{{ errors.title }}</p>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Subtitle</label>
                                <input
                                    v-model="settings.subtitle"
                                    type="text"
                                    class="settingsFormGroup__input"
                                    placeholder="Enter subtitle"
                                />
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">First Message</label>
                                <input
                                    v-model="settings.first_message"
                                    type="text"
                                    class="settingsFormGroup__input"
                                    placeholder="Enter first message"
                                />
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Position</label>
                                <select v-model="settings.position" class="settingsFormGroup__select">
                                    <option v-for="pos in positions" :key="pos.value" :value="pos.value">
                                        {{ pos.label }}
                                    </option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Token Limits Section -->
                    <div class="settingsSection">
                        <button
                            type="button"
                            class="settingsSection__header"
                            @click="toggleSection('tokens')"
                        >
                            <span class="settingsSection__title">Token Limits</span>
                            <span class="settingsSection__icon" :class="{ 'settingsSection__icon--open': sections.tokens }">&#9660;</span>
                        </button>
                        <div v-show="sections.tokens" class="settingsSection__content">
                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Daily Input Max Token Limit</label>
                                <input
                                    v-model.number="settings.input_max_tokens"
                                    type="number"
                                    class="settingsFormGroup__input"
                                    :class="{ 'settingsFormGroup__input--error': errors.input_max_tokens }"
                                    min="0"
                                    @blur="validateField('input_max_tokens')"
                                />
                                <p v-if="errors.input_max_tokens" class="settingsFormGroup__error">{{ errors.input_max_tokens }}</p>
                                <p v-else class="settingsFormGroup__help-text">Maximum input tokens allowed per day</p>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Daily Output Max Token Limit</label>
                                <input
                                    v-model.number="settings.output_max_tokens"
                                    type="number"
                                    class="settingsFormGroup__input"
                                    :class="{ 'settingsFormGroup__input--error': errors.output_max_tokens }"
                                    min="0"
                                    @blur="validateField('output_max_tokens')"
                                />
                                <p v-if="errors.output_max_tokens" class="settingsFormGroup__error">{{ errors.output_max_tokens }}</p>
                                <p v-else class="settingsFormGroup__help-text">Maximum output tokens allowed per day</p>
                            </div>
                        </div>
                    </div>

                    <div class="settingsSection">
                        <button
                            type="button"
                            class="settingsSection__header"
                            @click="toggleSection('behavior')"
                        >
                            <span class="settingsSection__title">AI Behavior</span>
                            <span class="settingsSection__icon" :class="{ 'settingsSection__icon--open': sections.behavior }">&#9660;</span>
                        </button>
                        <div v-show="sections.behavior" class="settingsSection__content">
                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Background</label>
                                <p class="settingsFormGroup__help-text">Define the AI's behavior and personality</p>
                                <div class="settingsList">
                                    <div
                                        v-for="(item, index) in backgroundItems"
                                        :key="'bg-' + item.id"
                                        class="settingsList__item"
                                    >
                                        <div class="settingsList__order-buttons">
                                            <button
                                                type="button"
                                                class="settingsList__order-btn"
                                                :disabled="index === 0"
                                                @click="swapBackgroundByIndex(index, index - 1)"
                                            >↑</button>
                                            <button
                                                type="button"
                                                class="settingsList__order-btn"
                                                :disabled="index === backgroundItems.length - 1"
                                                @click="swapBackgroundByIndex(index, index + 1)"
                                            >↓</button>
                                        </div>
                                        <textarea
                                            :value="item.background"
                                            class="settingsList__textarea"
                                            rows="2"
                                            placeholder="Enter background instruction..."
                                            @input="updateBackgroundText(index, $event.target.value)"
                                            @blur="saveBackground(item, index)"
                                        ></textarea>
                                        <button
                                            type="button"
                                            class="settingsList__remove-btn"
                                            @click="removeBackground(item.id, index)"
                                        >×</button>
                                    </div>
                                    <button
                                        type="button"
                                        class="settingsList__add-btn"
                                        @click="addBackground"
                                    >+ Add Background</button>
                                </div>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Steps</label>
                                <p class="settingsFormGroup__help-text">Define processing steps or workflow</p>
                                <div class="settingsList">
                                    <div
                                        v-for="(item, index) in stepsItems"
                                        :key="'step-' + item.id"
                                        class="settingsList__item"
                                    >
                                        <div class="settingsList__order-buttons">
                                            <button
                                                type="button"
                                                class="settingsList__order-btn"
                                                :disabled="index === 0"
                                                @click="swapStepsByIndex(index, index - 1)"
                                            >↑</button>
                                            <button
                                                type="button"
                                                class="settingsList__order-btn"
                                                :disabled="index === stepsItems.length - 1"
                                                @click="swapStepsByIndex(index, index + 1)"
                                            >↓</button>
                                        </div>
                                        <textarea
                                            :value="item.step"
                                            class="settingsList__textarea"
                                            rows="2"
                                            placeholder="Enter step instruction..."
                                            @input="updateStepText(index, $event.target.value)"
                                            @blur="saveStep(item, index)"
                                        ></textarea>
                                        <button
                                            type="button"
                                            class="settingsList__remove-btn"
                                            @click="removeSteps(item.id, index)"
                                        >×</button>
                                    </div>
                                    <button
                                        type="button"
                                        class="settingsList__add-btn"
                                        @click="addSteps"
                                    >+ Add Step</button>
                                </div>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Output</label>
                                <p class="settingsFormGroup__help-text">Define how the AI agent is supposed to give comments to the client</p>
                                <div class="settingsList">
                                    <div
                                        v-for="(item, index) in outputItems"
                                        :key="'out-' + item.id"
                                        class="settingsList__item"
                                    >
                                        <div class="settingsList__order-buttons">
                                            <button
                                                type="button"
                                                class="settingsList__order-btn"
                                                :disabled="index === 0"
                                                @click="swapOutputByIndex(index, index - 1)"
                                            >↑</button>
                                            <button
                                                type="button"
                                                class="settingsList__order-btn"
                                                :disabled="index === outputItems.length - 1"
                                                @click="swapOutputByIndex(index, index + 1)"
                                            >↓</button>
                                        </div>
                                        <textarea
                                            :value="item.output"
                                            class="settingsList__textarea"
                                            rows="2"
                                            placeholder="Enter output instruction..."
                                            @input="updateOutputText(index, $event.target.value)"
                                            @blur="saveOutput(item, index)"
                                        ></textarea>
                                        <button
                                            type="button"
                                            class="settingsList__remove-btn"
                                            @click="removeOutput(item.id, index)"
                                        >×</button>
                                    </div>
                                    <button
                                        type="button"
                                        class="settingsList__add-btn"
                                        @click="addOutput"
                                    >+ Add Output</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- OpenAI Configuration Section -->
                    <div class="settingsSection">
                        <button
                            type="button"
                            class="settingsSection__header"
                            @click="toggleSection('openai')"
                        >
                            <span class="settingsSection__title">OpenAI Configuration</span>
                            <span class="settingsSection__icon" :class="{ 'settingsSection__icon--open': sections.openai }">&#9660;</span>
                        </button>
                        <div v-show="sections.openai" class="settingsSection__content">
                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">OpenAI API Key</label>
                                <div class="settingsFormGroup__input-wrapper">
                                    <input
                                        v-model="openaiApiKey"
                                        :type="showApiKey ? 'text' : 'password'"
                                        class="settingsFormGroup__input"
                                        :class="{ 'settingsFormGroup__input--error': errors.openai_api_key }"
                                        placeholder="sk-..."
                                        @blur="validateField('openai_api_key')"
                                    />
                                    <button
                                        type="button"
                                        class="settingsFormGroup__toggle-btn"
                                        @click="showApiKey = !showApiKey"
                                    >
                                        {{ showApiKey ? 'Hide' : 'Show' }}
                                    </button>
                                </div>
                                <p v-if="errors.openai_api_key" class="settingsFormGroup__error">{{ errors.openai_api_key }}</p>
                                <p v-else class="settingsFormGroup__help-text">
                                    <span v-if="hasOpenaiKey" class="settingsFormGroup__key-status settingsFormGroup__key-status--set">
                                        ✓ API key is configured
                                    </span>
                                    <span v-else class="settingsFormGroup__key-status">
                                        Enter your OpenAI API key
                                    </span>
                                </p>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Chat Model</label>
                                <input
                                    v-model="settings.openai_model"
                                    type="text"
                                    class="settingsFormGroup__input"
                                    :class="{ 'settingsFormGroup__input--error': errors.openai_model }"
                                    placeholder="Enter chat model. E.g., gpt-4o"
                                    @blur="validateField('openai_model')"
                                />
                                <p v-if="errors.openai_model" class="settingsFormGroup__error">{{ errors.openai_model }}</p>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Embedding Model</label>
                                <input
                                    v-model="settings.openai_embedding_model"
                                    type="text"
                                    class="settingsFormGroup__input"
                                    :class="{ 'settingsFormGroup__input--error': errors.openai_embedding_model }"
                                    placeholder="Enter embedding model. E.g., text-embedding-3-small"
                                    @blur="validateField('openai_embedding_model')"
                                />
                                <p v-if="errors.openai_embedding_model" class="settingsFormGroup__error">{{ errors.openai_embedding_model }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- Pinecone Configuration Section -->
                    <div class="settingsSection">
                        <button
                            type="button"
                            class="settingsSection__header"
                            @click="toggleSection('pinecone')"
                        >
                            <span class="settingsSection__title">Pinecone Configuration</span>
                            <span class="settingsSection__icon" :class="{ 'settingsSection__icon--open': sections.pinecone }">&#9660;</span>
                        </button>
                        <div v-show="sections.pinecone" class="settingsSection__content">
                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Pinecone API Key</label>
                                <div class="settingsFormGroup__input-wrapper">
                                    <input
                                        v-model="pineconeApiKey"
                                        :type="showpineconeApiKey ? 'text' : 'password'"
                                        class="settingsFormGroup__input"
                                        :class="{ 'settingsFormGroup__input--error': errors.pinecone_api_key }"
                                        placeholder="Enter Pinecone API key"
                                        @blur="validateField('pinecone_api_key')"
                                    />
                                    <button
                                        type="button"
                                        class="settingsFormGroup__toggle-btn"
                                        @click="showpineconeApiKey = !showpineconeApiKey"
                                    >
                                        {{ showpineconeApiKey ? 'Hide' : 'Show' }}
                                    </button>
                                </div>
                                <p v-if="errors.pinecone_api_key" class="settingsFormGroup__error">{{ errors.pinecone_api_key }}</p>
                                <p v-else class="settingsFormGroup__help-text">
                                    <span v-if="hasPineconeKey" class="settingsFormGroup__key-status settingsFormGroup__key-status--set">
                                        ✓ API key is configured
                                    </span>
                                    <span v-else class="settingsFormGroup__key-status">
                                        Enter your pinecone API key
                                    </span>
                                </p>
                            </div>

                            <div class="settingsFormGroup">
                                <label class="settingsFormGroup__label">Pinecone Index URL</label>
                                <input
                                    v-model="settings.pinecone_index_url"
                                    type="text"
                                    class="settingsFormGroup__input"
                                    :class="{ 'settingsFormGroup__input--error': errors.pinecone_index_url }"
                                    placeholder="Enter pinecone index URL"
                                    @blur="validateField('pinecone_index_url')"
                                />
                                <p v-if="errors.pinecone_index_url" class="settingsFormGroup__error">{{ errors.pinecone_index_url }}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="settingsCard__actions">
                    <button @click="handleSave" class="settingsBtn settingsBtn--primary">Save Changes</button>
                    <button @click="handleReset" class="settingsBtn settingsBtn--outline">Reset</button>
                </div>
            </section>

        </div>
    </div>
</template>

<script>
import Toast from './elements/Toast.vue';

export default {
    name: 'Settings',
    components: {
        Toast
    },
    data() {
        return {
            settings: {
                title: 'AI Assistant',
                subtitle: 'Your intelligent helper',
                first_message: 'Hi! How can I assist you today?',
                position: 'center',
                openai_model: 'gpt-4o',
                openai_embedding_model: 'text-embedding-3-small',
                pinecone_index_url: '',
                input_max_tokens: 10000,
                output_max_tokens: 1000000
            },
            backgroundItems: [],
            stepsItems: [],
            outputItems: [],
            openaiApiKey: '',
            showApiKey: false,
            hasOpenaiKey: false,
            hasPineconeKey: false,
            pineconeApiKey: '',
            showpineconeApiKey: false,
            positions: [
                { value: '#', label: 'Custom' },
                { value: 'top-left', label: 'Top Left' },
                { value: 'top-right', label: 'Top Right' },
                { value: 'bottom-left', label: 'Bottom Left' },
                { value: 'bottom-right', label: 'Bottom Right' }
            ],
            toast: {
                message: '',
                type: 'success',
                duration: 3000
            },
            sections: {
                general: true,
                tokens: false,
                behavior: false,
                openai: false,
                pinecone: false
            },
            errors: {
                title: '',
                input_max_tokens: '',
                output_max_tokens: '',
                openai_api_key: '',
                openai_model: '',
                openai_embedding_model: '',
                pinecone_api_key: '',
                pinecone_index_url: ''
            }
        };
    },
    mounted() {
        this.fetchSettings();
    },
    computed: {
        getPositionLabel() {
            const pos = this.positions.find(p => p.value === this.settings.position);
            return pos ? pos.label : '';
        }
    },
    methods: {
        toggleSection(section) {
            this.sections[section] = !this.sections[section];
        },
        validateField(field) {
            this.errors[field] = '';

            switch (field) {
                case 'title':
                    if (!this.settings.title || !this.settings.title.trim()) {
                        this.errors.title = 'Title is required';
                    } else if (this.settings.title.length > 100) {
                        this.errors.title = 'Title must be less than 100 characters';
                    }
                    break;
                case 'input_max_tokens':
                    if (this.settings.input_max_tokens === null || this.settings.input_max_tokens === '') {
                        this.errors.input_max_tokens = 'Input token limit is required';
                    } else if (this.settings.input_max_tokens < 0) {
                        this.errors.input_max_tokens = 'Input token limit must be a positive number';
                    } else if (!Number.isInteger(this.settings.input_max_tokens)) {
                        this.errors.input_max_tokens = 'Input token limit must be a whole number';
                    }
                    break;
                case 'output_max_tokens':
                    if (this.settings.output_max_tokens === null || this.settings.output_max_tokens === '') {
                        this.errors.output_max_tokens = 'Output token limit is required';
                    } else if (this.settings.output_max_tokens < 0) {
                        this.errors.output_max_tokens = 'Output token limit must be a positive number';
                    } else if (!Number.isInteger(this.settings.output_max_tokens)) {
                        this.errors.output_max_tokens = 'Output token limit must be a whole number';
                    }
                    break;
                case 'openai_api_key':
                    if (this.openaiApiKey && !this.openaiApiKey.startsWith('sk-')) {
                        this.errors.openai_api_key = 'OpenAI API key should start with "sk-"';
                    }
                    break;
                case 'openai_model':
                    if (this.settings.openai_model && this.settings.openai_model.length > 50) {
                        this.errors.openai_model = 'Model name must be less than 50 characters';
                    }
                    break;
                case 'openai_embedding_model':
                    if (this.settings.openai_embedding_model && this.settings.openai_embedding_model.length > 50) {
                        this.errors.openai_embedding_model = 'Embedding model name must be less than 50 characters';
                    }
                    break;
                case 'pinecone_api_key':
                    if (this.pineconeApiKey && this.pineconeApiKey.length < 10) {
                        this.errors.pinecone_api_key = 'Pinecone API key appears to be invalid';
                    }
                    break;
                case 'pinecone_index_url':
                    if (this.settings.pinecone_index_url) {
                        try {
                            new URL(this.settings.pinecone_index_url);
                        } catch {
                            this.errors.pinecone_index_url = 'Please enter a valid URL';
                        }
                    }
                    break;
            }

            return !this.errors[field];
        },
        validateAll() {
            const fields = [
                'title',
                'input_max_tokens',
                'output_max_tokens',
                'openai_api_key',
                'openai_model',
                'openai_embedding_model',
                'pinecone_api_key',
                'pinecone_index_url'
            ];

            let isValid = true;
            fields.forEach(field => {
                if (!this.validateField(field)) {
                    isValid = false;
                }
            });

            return isValid;
        },
        clearErrors() {
            Object.keys(this.errors).forEach(key => {
                this.errors[key] = '';
            });
        },
        getHeaders() {
            const headers = {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            };
            const csrfToken = document.querySelector('meta[name="csrf-token"]');
            if (csrfToken) {
                headers['X-CSRF-TOKEN'] = csrfToken.getAttribute('content');
            }
            return headers;
        },
        showToast(message, type = 'success') {
            this.toast.message = message;
            this.toast.type = type;
            this.$nextTick(() => {
                this.$refs.toast.show();
            });
        },
        async handleSave() {
            if (!this.validateAll()) {
                this.showToast('Please fix the validation errors before saving', 'error');
                return;
            }

            const payload = { ...this.settings };

            if (this.openaiApiKey) {
                payload.openai_api_key = this.openaiApiKey;
            }

            if (this.pineconeApiKey) {
                payload.pinecone_api_key = this.pineconeApiKey;
            }

            try {
                const response = await fetch('/admin/agent/settings', {
                    method: 'POST',
                    headers: this.getHeaders(),
                    body: JSON.stringify(payload)
                });

                if (response.ok) {
                    if (this.openaiApiKey) {
                        this.hasOpenaiKey = true;
                        this.openaiApiKey = '';
                    }
                    if (this.pineconeApiKey) {
                        this.hasPineconeKey = true;
                        this.pineconeApiKey = '';
                    }
                    this.showToast('Settings saved successfully', 'success');
                } else {
                    this.showToast('Failed to save settings', 'error');
                }
            } catch (error) {
                console.error('Error saving settings:', error);
                this.showToast('An error occurred while saving', 'error');
            }
        },
        async fetchSettings() {
            try {
                const response = await fetch('/admin/agent/settings');
                if (response.ok) {
                    const data = await response.json();
                    this.settings = {
                        title: data.title,
                        subtitle: data.subtitle,
                        first_message: data.first_message,
                        position: data.position,
                        input_max_tokens: data.input_max_tokens,
                        openai_model: data.openai_model,
                        openai_embedding_model: data.openai_embedding_model,
                        pinecone_index_url: data.pinecone_index_url,
                        output_max_tokens: data.output_max_tokens
                    };
                    this.backgroundItems = data.backgrounds || [];
                    this.stepsItems = data.steps || [];
                    this.outputItems = data.outputs || [];
                    this.hasOpenaiKey = data.has_openai_key || false;
                    this.hasPineconeKey = data.has_pinecone_key || false;
                } else {
                    console.error('Failed to fetch settings');
                }
            } catch (error) {
                console.error('Error fetching settings:', error);
            }
        },
        handleReset() {
            this.settings = {
                title: 'AI Assistant',
                subtitle: '',
                first_message: '',
                position: 'center',
                input_max_tokens: 10000,
                output_max_tokens: 10000
            };
            this.openaiApiKey = '';
            this.pineconeApiKey = '';
            this.clearErrors();
        },

        // Background Methods
        updateBackgroundText(index, value) {
            this.$set(this.backgroundItems[index], 'background', value);
        },
        addBackground() {
            const tempId = 'temp-' + Date.now();
            const order = this.backgroundItems.length + 1;
            this.backgroundItems.push({
                id: tempId,
                background: '',
                order: order,
                isNew: true
            });
        },
        async removeBackground(id, index) {
            const item = this.backgroundItems[index];
            if (item.isNew) {
                this.backgroundItems.splice(index, 1);
                return;
            }
            try {
                const response = await fetch('/admin/agent/settings/background/' + id, {
                    method: 'DELETE',
                    headers: this.getHeaders()
                });
                const result = await response.json();
                if (result.message) {
                    this.backgroundItems = this.backgroundItems.filter(item => item.id !== id);
                }
            } catch (error) {
                console.error('Error removing background:', error);
            }
        },
        async saveBackground(item, index) {
            if (!item.background.trim()) {
                return;
            }
            try {
                if (item.isNew) {
                    const response = await fetch('/admin/agent/settings/background', {
                        method: 'POST',
                        headers: this.getHeaders(),
                        body: JSON.stringify({ background: item.background, order: item.order })
                    });
                    const result = await response.json();
                    if (result.message && result.data) {
                        this.$set(this.backgroundItems, index, result.data);
                    }
                } else {
                    await fetch('/admin/agent/settings/background/' + item.id, {
                        method: 'PUT',
                        headers: this.getHeaders(),
                        body: JSON.stringify({ background: item.background, order: item.order })
                    });
                }
            } catch (error) {
                console.error('Error saving background:', error);
            }
        },
        async swapBackgroundByIndex(idx1, idx2) {
            if (idx1 < 0 || idx2 < 0 || idx1 >= this.backgroundItems.length || idx2 >= this.backgroundItems.length) return;
            const item1 = this.backgroundItems[idx1];
            const item2 = this.backgroundItems[idx2];
            if (item1.isNew || item2.isNew) {
                const temp = this.backgroundItems[idx1];
                this.$set(this.backgroundItems, idx1, this.backgroundItems[idx2]);
                this.$set(this.backgroundItems, idx2, temp);
                return;
            }
            try {
                const response = await fetch('/admin/agent/settings/background/swap', {
                    method: 'POST',
                    headers: this.getHeaders(),
                    body: JSON.stringify({ order1: item1.id, order2: item2.id })
                });
                const result = await response.json();
                if (result.message) {
                    const temp = this.backgroundItems[idx1];
                    this.$set(this.backgroundItems, idx1, this.backgroundItems[idx2]);
                    this.$set(this.backgroundItems, idx2, temp);
                }
            } catch (error) {
                console.error('Error swapping background order:', error);
            }
        },

        // Steps Methods
        updateStepText(index, value) {
            this.$set(this.stepsItems[index], 'step', value);
        },
        addSteps() {
            const tempId = 'temp-' + Date.now();
            const order = this.stepsItems.length + 1;
            this.stepsItems.push({
                id: tempId,
                step: '',
                order: order,
                isNew: true
            });
        },
        async removeSteps(id, index) {
            const item = this.stepsItems[index];
            if (item.isNew) {
                this.stepsItems.splice(index, 1);
                return;
            }
            try {
                const response = await fetch('/admin/agent/settings/steps/' + id, {
                    method: 'DELETE',
                    headers: this.getHeaders()
                });
                const result = await response.json();
                if (result.message) {
                    this.stepsItems = this.stepsItems.filter(item => item.id !== id);
                }
            } catch (error) {
                console.error('Error removing step:', error);
            }
        },
        async saveStep(item, index) {
            if (!item.step.trim()) {
                return;
            }
            try {
                if (item.isNew) {
                    const response = await fetch('/admin/agent/settings/steps', {
                        method: 'POST',
                        headers: this.getHeaders(),
                        body: JSON.stringify({ step: item.step, order: item.order })
                    });
                    const result = await response.json();
                    if (result.message && result.data) {
                        this.$set(this.stepsItems, index, result.data);
                    }
                } else {
                    await fetch('/admin/agent/settings/steps/' + item.id, {
                        method: 'PUT',
                        headers: this.getHeaders(),
                        body: JSON.stringify({ step: item.step, order: item.order })
                    });
                }
            } catch (error) {
                console.error('Error saving step:', error);
            }
        },
        async swapStepsByIndex(idx1, idx2) {
            if (idx1 < 0 || idx2 < 0 || idx1 >= this.stepsItems.length || idx2 >= this.stepsItems.length) return;
            const item1 = this.stepsItems[idx1];
            const item2 = this.stepsItems[idx2];
            if (item1.isNew || item2.isNew) {
                const temp = this.stepsItems[idx1];
                this.$set(this.stepsItems, idx1, this.stepsItems[idx2]);
                this.$set(this.stepsItems, idx2, temp);
                return;
            }
            try {
                const response = await fetch('/admin/agent/settings/steps/swap', {
                    method: 'POST',
                    headers: this.getHeaders(),
                    body: JSON.stringify({ order1: item1.id, order2: item2.id })
                });
                const result = await response.json();
                if (result.message) {
                    const temp = this.stepsItems[idx1];
                    this.$set(this.stepsItems, idx1, this.stepsItems[idx2]);
                    this.$set(this.stepsItems, idx2, temp);
                }
            } catch (error) {
                console.error('Error swapping steps order:', error);
            }
        },

        // Output Methods
        updateOutputText(index, value) {
            this.$set(this.outputItems[index], 'output', value);
        },
        addOutput() {
            const tempId = 'temp-' + Date.now();
            const order = this.outputItems.length + 1;
            this.outputItems.push({
                id: tempId,
                output: '',
                order: order,
                isNew: true
            });
        },
        async removeOutput(id, index) {
            const item = this.outputItems[index];
            if (item.isNew) {
                this.outputItems.splice(index, 1);
                return;
            }
            try {
                const response = await fetch('/admin/agent/settings/output/' + id, {
                    method: 'DELETE',
                    headers: this.getHeaders()
                });
                const result = await response.json();
                if (result.message) {
                    this.outputItems = this.outputItems.filter(item => item.id !== id);
                }
            } catch (error) {
                console.error('Error removing output:', error);
            }
        },
        async saveOutput(item, index) {
            if (!item.output.trim()) {
                return;
            }
            try {
                if (item.isNew) {
                    const response = await fetch('/admin/agent/settings/output', {
                        method: 'POST',
                        headers: this.getHeaders(),
                        body: JSON.stringify({ output: item.output, order: item.order })
                    });
                    const result = await response.json();
                    if (result.message && result.data) {
                        this.$set(this.outputItems, index, result.data);
                    }
                } else {
                    await fetch('/admin/agent/settings/output/' + item.id, {
                        method: 'PUT',
                        headers: this.getHeaders(),
                        body: JSON.stringify({ output: item.output, order: item.order })
                    });
                }
            } catch (error) {
                console.error('Error saving output:', error);
            }
        },
        async swapOutputByIndex(idx1, idx2) {
            if (idx1 < 0 || idx2 < 0 || idx1 >= this.outputItems.length || idx2 >= this.outputItems.length) return;
            const item1 = this.outputItems[idx1];
            const item2 = this.outputItems[idx2];
            if (item1.isNew || item2.isNew) {
                const temp = this.outputItems[idx1];
                this.$set(this.outputItems, idx1, this.outputItems[idx2]);
                this.$set(this.outputItems, idx2, temp);
                return;
            }
            try {
                const response = await fetch('/admin/agent/settings/output/swap', {
                    method: 'POST',
                    headers: this.getHeaders(),
                    body: JSON.stringify({ order1: item1.id, order2: item2.id })
                });
                const result = await response.json();
                if (result.message) {
                    const temp = this.outputItems[idx1];
                    this.$set(this.outputItems, idx1, this.outputItems[idx2]);
                    this.$set(this.outputItems, idx2, temp);
                }
            } catch (error) {
                console.error('Error swapping output order:', error);
            }
        }
    }
};
</script>

<style lang="less" scoped>
/* Blocks */
.settingsPage {
    padding: 1.5rem;
}

.settingsCard {
    background: #ffffff;
    border-radius: 0.5rem;
    padding: 2rem;

    /* Elements */
    &__title {
        font-size: 1.875rem;
        font-weight: 700;
        color: #1e293b;
        margin-bottom: 0.5rem;
        margin-top: 0;
    }

    &__description {
        color: #475569;
        margin-bottom: 2rem;
    }

    &__body {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }

    &__actions {
        display: flex;
        gap: 1rem;
        margin-top: 2rem;
    }
}





/* Form Group Block */
.settingsFormGroup {
    display: flex;
    flex-direction: column;

    &__label {
        font-size: 0.875rem;
        font-weight: 500;
        color: #334155;
        margin-bottom: 0.5rem;
    }

    &__input,
    &__select,
    &__textarea {
        width: 100%;
        padding: 0.5rem 1rem;
        border: 1px solid #cbd5e1;
        border-radius: 0.5rem;
        outline: none;
        font-size: 1rem;
        box-sizing: border-box;
        transition: border-color 0.2s, box-shadow 0.2s;

        &:focus {
            border-color: transparent;
            box-shadow: 0 0 0 2px #3b82f6;
        }
    }

    &__textarea {
        resize: none;
    }

    &__help-text {
        font-size: 0.875rem;
        color: #64748b;
        margin-top: 0.25rem;
    }

    &__input-wrapper {
        display: flex;
        gap: 0.5rem;

        .settingsFormGroup__input {
            flex: 1;
        }
    }

    &__toggle-btn {
        padding: 0.5rem 1rem;
        border: 1px solid #cbd5e1;
        border-radius: 0.5rem;
        background: #f8fafc;
        color: #475569;
        cursor: pointer;
        font-size: 0.875rem;
        white-space: nowrap;
        transition: background-color 0.2s;

        &:hover {
            background: #e2e8f0;
        }
    }

    &__key-status {
        &--set {
            color: #16a34a;
        }
    }

    &__input--error,
    &__select--error,
    &__textarea--error {
        border-color: #dc2626;

        &:focus {
            box-shadow: 0 0 0 2px #fca5a5;
        }
    }

    &__error {
        font-size: 0.875rem;
        color: #dc2626;
        margin-top: 0.25rem;
        margin-bottom: 0;
    }
}



/* Collapsible Section Block */
.settingsSection {
    border: 1px solid #e2e8f0;
    border-radius: 0.5rem;
    overflow: hidden;

    &__header {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem 1.25rem;
        background: #f8fafc;
        border: none;
        cursor: pointer;
        transition: background-color 0.2s;

        &:hover {
            background: #f1f5f9;
        }
    }

    &__title {
        font-size: 1rem;
        font-weight: 600;
        color: #1e293b;
    }

    &__icon {
        font-size: 0.75rem;
        color: #64748b;
        transition: transform 0.2s;

        &--open {
            transform: rotate(180deg);
        }
    }

    &__content {
        padding: 1.25rem;
        display: flex;
        flex-direction: column;
        gap: 1.25rem;
        border-top: 1px solid #e2e8f0;
    }
}

/* Button Block */
.settingsBtn {
    padding: 0.75rem 1.5rem;
    max-width: fit-content;
    border-radius: 0.5rem;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 1rem;
    border: 1px solid transparent;

    &--primary {
        flex: 1;
        background-color: #2563eb;
        color: #ffffff;
    }

    &--primary:hover {
        background-color: #1d4ed8;
    }

    &--outline {
        background-color: #ffffff;
        color: #334155;
        border-color: #cbd5e1;
    }
}

/* Settings List Block */
.settingsList {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    margin-top: 0.5rem;

    &__item {
        display: flex;
        align-items: flex-start;
        gap: 0.5rem;
        padding: 0.75rem;
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 0.5rem;
    }

    &__order-buttons {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }

    &__order-btn {
        width: 28px;
        height: 28px;
        padding: 0;
        border: 1px solid #cbd5e1;
        border-radius: 0.25rem;
        background: #ffffff;
        color: #475569;
        cursor: pointer;
        font-size: 0.875rem;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background-color 0.2s;

        &:hover:not(:disabled) {
            background: #e2e8f0;
        }

        &:disabled {
            opacity: 0.4;
            cursor: not-allowed;
        }
    }

    &__textarea {
        flex: 1;
        padding: 0.5rem;
        border: 1px solid #cbd5e1;
        border-radius: 0.375rem;
        outline: none;
        font-size: 0.875rem;
        resize: none;
        min-height: 60px;
        box-sizing: border-box;
        transition: border-color 0.2s, box-shadow 0.2s;

        &:focus {
            border-color: transparent;
            box-shadow: 0 0 0 2px #3b82f6;
        }
    }

    &__remove-btn {
        width: 28px;
        height: 28px;
        padding: 0;
        border: 1px solid #fca5a5;
        border-radius: 0.25rem;
        background: #fef2f2;
        color: #dc2626;
        cursor: pointer;
        font-size: 1.25rem;
        line-height: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background-color 0.2s;

        &:hover {
            background: #fee2e2;
        }
    }

    &__add-btn {
        padding: 0.5rem 1rem;
        border: 1px dashed #cbd5e1;
        border-radius: 0.5rem;
        background: transparent;
        color: #64748b;
        cursor: pointer;
        font-size: 0.875rem;
        transition: background-color 0.2s, border-color 0.2s;

        &:hover {
            background: #f8fafc;
            border-color: #94a3b8;
        }
    }
}

</style>
