// frontend/js/components/tagInput.js

export default class TagInput {
    constructor(container, options = {}) {
        if (!container) {
            console.error("TagInput container not found.");
            return;
        }
        this.container = container;
        this.input = container.querySelector('.tag-input-new');
        this.tags = [];
        this.options = {
            validator: /.+/, 
            validationMessage: '输入格式无效',
            ...options 
        };

        this.copyBtn = document.createElement('button');
        this.copyBtn.className = 'tag-copy-btn'; 
        this.copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
        this.copyBtn.title = '复制所有';
        this.container.appendChild(this.copyBtn);

        this._initEventListeners();
    }

    _initEventListeners() {
        this.container.addEventListener('click', (e) => {
            // 使用 .closest() 来处理点击事件，即使点击到图标也能正确触发
            if (e.target.closest('.tag-delete')) {
                this._removeTag(e.target.closest('.tag-item'));
            }
        });

        if (this.input) {
            this.input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ',' || e.key === ' ') {
                    e.preventDefault();
                    const value = this.input.value.trim();
                    if (value) {
                        this._addTag(value);
                        this.input.value = '';
                    }
                }
            });
            this.input.addEventListener('blur', () => {
                const value = this.input.value.trim();
                if (value) {
                    this._addTag(value);
                    this.input.value = '';
                }
            });
        }

        // 为“复制”按钮绑定点击事件
        this.copyBtn.addEventListener('click', this._handleCopyAll.bind(this));
    }

    _addTag(raw_value) {
        // 在所有操作之前，自动转换为小写
        const value = raw_value.toLowerCase();

        if (!this.options.validator.test(value)) {
            console.warn(`Tag validation failed for value: "${value}". Rule: ${this.options.validator}`);
            this.input.placeholder = this.options.validationMessage;
            this.input.classList.add('input-error');
            setTimeout(() => {
                this.input.classList.remove('input-error');
                this.input.placeholder = '添加...';
            }, 2000);
            return;
        }

        if (this.tags.includes(value)) return;
        this.tags.push(value);

        const tagEl = document.createElement('span');
        tagEl.className = 'tag-item';
        tagEl.innerHTML = `<span class="tag-text">${value}</span><button class="tag-delete">&times;</button>`;
        this.container.insertBefore(tagEl, this.input);
    }
    
    // 处理复制逻辑的专用方法
    _handleCopyAll() {
        const tagsString = this.tags.join(',');
        if (!tagsString) {
            // 如果没有标签，可以给个提示
            this.copyBtn.innerHTML = '<span>无内容!</span>';
            this.copyBtn.classList.add('none');
            setTimeout(() => {
                this.copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
                this.copyBtn.classList.remove('copied');
            }, 1500);
            return;
        }

        navigator.clipboard.writeText(tagsString).then(() => {
            // 复制成功，提供视觉反馈
            this.copyBtn.innerHTML = '<span>已复制!</span>';
            this.copyBtn.classList.add('copied');
            setTimeout(() => {
                this.copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
                this.copyBtn.classList.remove('copied');
            }, 2000);
        }).catch(err => {
            // 复制失败
            console.error('Could not copy text: ', err);
            this.copyBtn.innerHTML = '<span>失败!</span>';
             setTimeout(() => {
                this.copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
            }, 2000);
        });
    }

    _removeTag(tagEl) {
        const value = tagEl.querySelector('.tag-text').textContent;
        this.tags = this.tags.filter(t => t !== value);
        tagEl.remove();
    }

    getValues() {
        return this.tags;
    }

    setValues(values) {
        this.container.querySelectorAll('.tag-item').forEach(el => el.remove());
        this.tags = [];
        if (Array.isArray(values)) {
            values.filter(value => value).forEach(value => this._addTag(value));
        }
    }
}
