const TagsInput = ({ tags, onChange, placeholder = "Add tags..." }) => {
    const [inputValue, setInputValue] = React.useState('');
    const [error, setError] = React.useState('');

    // Ensure tags is always an array
    const tagArray = Array.isArray(tags) ? tags : [];

    const addTag = (tagText) => {
        const cleaned = tagText.trim();
        if (!cleaned) return;

        // Validate: no special characters that could break JSON
        if (/[<>"'`{}[\]]/.test(cleaned)) {
            setError('Tags cannot contain: < > " \' ` { } [ ]');
            return;
        }

        // Dedupe: case-insensitive, and when adding multiple from comma-separated
        const existingLower = tagArray.map(t => String(t).toLowerCase());
        const toAdd = cleaned.split(',').map(t => t.trim()).filter(Boolean).filter(t => !existingLower.includes(t.toLowerCase()));
        toAdd.forEach(t => existingLower.push(t.toLowerCase()));
        if (toAdd.length === 0) {
            setInputValue('');
            return;
        }
        setError('');
        onChange([...tagArray, ...toAdd]);
        setInputValue('');
    };

    const removeTag = (index) => {
        const newTags = tagArray.filter((_, i) => i !== index);
        onChange(newTags);
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' || e.key === ',' || e.key === 'Tab') {
            e.preventDefault();
            addTag(inputValue);
        } else if (e.key === 'Backspace' && !inputValue && tagArray.length > 0) {
            removeTag(tagArray.length - 1);
        } else if (e.key === 'Escape') {
            setInputValue('');
            setError('');
        }
    };

    return (
        <div className="space-y-2">
            <div className="flex flex-wrap items-center gap-2 min-h-[52px] px-4 py-2.5 border border-gray-300 rounded-xl focus-within:ring-2 focus-within:ring-primary focus-within:border-transparent bg-white">
                {tagArray.map((tag, index) => (
                    <span
                        key={index}
                        className="oto-tag group inline-flex items-center gap-1 pl-3 pr-1.5 py-1.5 rounded-full bg-primary/10 text-primary text-sm font-medium border border-primary/20"
                    >
                        <span>{tag}</span>
                        <button
                            type="button"
                            onClick={() => removeTag(index)}
                            className="p-0.5 rounded-full text-primary/80 hover:text-primary hover:bg-primary/20 hover:shadow-md transition-all"
                            aria-label={`Remove ${tag}`}
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                        </button>
                    </span>
                ))}
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => {
                        setInputValue(e.target.value);
                        setError('');
                    }}
                    onKeyDown={handleKeyDown}
                    onBlur={() => {
                        if (inputValue.trim()) {
                            addTag(inputValue);
                        }
                    }}
                    placeholder={tagArray.length === 0 ? (placeholder || 'e.g. urgent, policy, 2025') : 'Add another…'}
                    className="flex-1 min-w-[120px] py-1.5 px-0 border-0 focus:ring-0 focus:outline-none text-gray-900 placeholder-gray-400 outline-none text-sm"
                />
            </div>
            {error && (
                <div className="text-red-600 text-sm">{error}</div>
            )}
            <div className="text-xs text-gray-500">
                Press Enter or comma to add. Hover a tag to remove it.
            </div>
        </div>
    );
};

if (typeof window !== 'undefined') window.TagsInput = TagsInput;