// Milestones — controlled vocabulary for the account timeline's declared
// events ('Onboarded', 'Contract signed', 'Website live'). Same pattern as
// Tags, but self-fetching: milestone types aren't needed app-wide, so the
// list isn't lifted to MainApp. Deleting a type never touches history —
// events snapshot name/color at declaration time.

const MilestonesSection = ({ currentUser }) => {
    const [types, setTypes]     = React.useState([]);
    const [newName, setNewName] = React.useState('');
    const [newColor, setNewColor] = React.useState('#3b82f6');
    const [saving, setSaving]   = React.useState(false);

    const refresh = () => api.getMilestoneTypes().then(setTypes).catch(() => {});
    React.useEffect(() => { refresh(); }, []);

    const handleCreate = async (e) => {
        e.preventDefault();
        if (!newName.trim()) return;
        setSaving(true);
        try {
            await api.createMilestoneType({ name: newName.trim(), color: newColor });
            setNewName(''); refresh();
        } catch (err) { alert(err.message); }
        finally { setSaving(false); }
    };

    const handleDelete = async (t) => {
        if (!window.confirm(`Delete milestone type "${t.name}"? Existing timeline entries keep their name and color.`)) return;
        try { await api.deleteMilestoneType(t.id); refresh(); }
        catch (err) { alert(err.message); }
    };

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>
                Milestones mark the big moments in a client relationship — reps add them to an
                account's timeline from this list, so the wording stays consistent.
            </p>
            <form onSubmit={handleCreate} 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">Milestone Name</label>
                    <input className="form-input" value={newName} onChange={e => setNewName(e.target.value)} placeholder="e.g. Onboarded, Contract signed, Website live…" required />
                </div>
                <div className="form-group">
                    <label className="form-label">Color</label>
                    <ColorSwatchPicker value={newColor} onChange={setNewColor} />
                </div>
                <button type="submit" className="btn btn-primary btn-small" disabled={saving} style={{ marginBottom: '0.1rem' }}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Creating…</> : <><i className="fas fa-plus"></i> Create Milestone</>}
                </button>
            </form>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.625rem' }}>
                {types.length === 0
                    ? <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No milestone types yet.</p>
                    : types.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' }}>
                            <i className="fas fa-flag" style={{ fontSize: '0.7rem', color: t.color }}></i>
                            <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={() => handleDelete(t)} title="Delete milestone type" style={{ padding: '0.1rem 0.3rem', fontSize: '0.7rem' }}><i className="fas fa-times"></i></button>
                            )}
                        </div>
                    ))
                }
            </div>
        </div>
    );
};
