// Type-ahead contact selector — the "Joe types 'cindy', Cindy appears"
// moment. Searches server-side (name / department / location) via the
// contacts route's existing search param, debounced, capped at 20.
// AccountPicker's skeleton and CSS, pointed at contacts.
//
// Unlike AccountPicker this is an ACTION, not a form value: picking a
// contact fires onPick(contact) and the input resets, ready for the next
// add. The caller owns the linked list (and passes excludeIds so already-
// linked people drop out of the menu).

const ContactPicker = ({ onPick, excludeIds = [], placeholder = 'Search contacts…' }) => {
    const [query, setQuery]     = React.useState('');
    const [results, setResults] = React.useState([]);
    const [open, setOpen]       = React.useState(false);
    const boxRef = React.useRef(null);

    // Close on outside click — standard dropdown hygiene.
    React.useEffect(() => {
        const handler = (e) => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    React.useEffect(() => {
        if (!open) return;
        const t = setTimeout(() => {
            api.getContacts({ paged: 'true', limit: 20, ...(query.trim() ? { search: query.trim() } : {}) })
                .then(({ rows }) => setResults(rows.filter(c => !excludeIds.includes(c.id))))
                .catch(() => setResults([]));
        }, 200);
        return () => clearTimeout(t);
    }, [query, open, excludeIds.join(',')]);

    const pick = (c) => {
        setQuery(''); setOpen(false);
        onPick(c);
    };

    return (
        <div className="account-picker" ref={boxRef}>
            <input
                type="text"
                className="form-input"
                value={query}
                placeholder={placeholder}
                onFocus={() => setOpen(true)}
                onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
            />
            {open && (
                <div className="account-picker-menu">
                    {results.length === 0
                        ? <div className="account-picker-empty">{query ? 'No matches' : 'Type to search…'}</div>
                        : results.map(c => (
                            <div key={c.id} className="account-picker-item" onMouseDown={() => pick(c)}>
                                <span>{[c.first_name, c.last_name].filter(Boolean).join(' ')}</span>
                                {c.account_name && (
                                    <span style={{ fontSize: '0.7rem', color: 'var(--text-3)' }}>{c.account_name}</span>
                                )}
                            </div>
                        ))}
                </div>
            )}
        </div>
    );
};
