// Tags — controlled vocabulary for segmenting accounts. Migrated from the
// AdminPanel drawer; tag state stays lifted in MainApp (sidebar filter chips
// read the same list), so changes flow up via onTagsChange.

const TagsSection = ({ currentUser, allTags = [], onTagsChange }) => {
    const [newTagName, setNewTagName]   = React.useState('');
    const [newTagColor, setNewTagColor] = React.useState('#3b82f6');
    const [tagSaving, setTagSaving]     = React.useState(false);

    const handleCreateTag = async (e) => {
        e.preventDefault();
        if (!newTagName.trim()) return;
        setTagSaving(true);
        try {
            await api.createTag({ name: newTagName.trim(), color: newTagColor });
            setNewTagName(''); onTagsChange && onTagsChange();
        } catch(err) { alert(err.message); }
        finally { setTagSaving(false); }
    };

    const handleDeleteTag = async (tag) => {
        if (!window.confirm(`Delete tag "${tag.name}"? It will be removed from all accounts.`)) return;
        try { await api.deleteTag(tag.id); onTagsChange && onTagsChange(); }
        catch(err) { alert(err.message); }
    };

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>Tags can be applied to accounts for filtering and categorization.</p>
            <form onSubmit={handleCreateTag} style={{ display: 'flex', gap: '0.75rem', alignItems: 'flex-end', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
                <div className="form-group" style={{ flex: 1, minWidth: 180 }}>
                    <label className="form-label">Tag Name</label>
                    <input className="form-input" value={newTagName} onChange={e => setNewTagName(e.target.value)} placeholder="e.g. VIP, Wholesale, Prospect…" required />
                </div>
                <div className="form-group">
                    <label className="form-label">Color</label>
                    <ColorSwatchPicker value={newTagColor} onChange={setNewTagColor} />
                </div>
                <button type="submit" className="btn btn-primary btn-small" disabled={tagSaving} style={{ marginBottom: '0.1rem' }}>
                    {tagSaving ? <><i className="fas fa-spinner fa-spin"></i> Creating…</> : <><i className="fas fa-plus"></i> Create Tag</>}
                </button>
            </form>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.625rem' }}>
                {allTags.length === 0
                    ? <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No tags yet.</p>
                    : allTags.map(t => (
                        <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: t.color + '18', border: `1px solid ${t.color}44`, borderRadius: '999px', padding: '0.3rem 0.75rem 0.3rem 0.5rem' }}>
                            <span style={{ width: 10, height: 10, borderRadius: '50%', background: t.color, flexShrink: 0 }}></span>
                            <span style={{ fontWeight: 600, fontSize: '0.8125rem', color: t.color }}>{t.name}</span>
                            <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>({t.usage_count})</span>
                            {currentUser.role === 'admin' && (
                                <button className="btn-icon-sm danger" onClick={() => handleDeleteTag(t)} title="Delete tag" style={{ padding: '0.1rem 0.3rem', fontSize: '0.7rem' }}><i className="fas fa-times"></i></button>
                            )}
                        </div>
                    ))
                }
            </div>
        </div>
    );
};
