// Value-suggestion typeahead — a plain text input that suggests values
// already used on other properties (city, subdivision, plan name…), so
// "Beverly Hills" doesn't get typed five different ways. The field still
// stores free text; picking a suggestion is a convenience, not a constraint.
//
// Same debounce-and-dropdown skeleton as AccountPicker (and its CSS), but no
// "picked chip" state — this IS the input, suggestions just fill it.
//
// Why not native <datalist>: zero-JS, but the dropdown styling is
// browser-inconsistent and can't match the app's theme. Reusing the
// account-picker menu keeps every typeahead in the app looking identical.
//
// Props: field (server-whitelisted name — built-in column or text custom-field
// key), value, onValueChange(string), plus passthroughs for the input.

const SuggestInput = ({ field, value, onValueChange, maxLength, placeholder, className = 'form-input' }) => {
    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);
    }, []);

    // Debounced fetch — 200ms after the last keystroke, like AccountPicker.
    // Empty query is allowed on purpose: focusing the field shows the first
    // 10 known values, which for short lists (cities) is the whole menu.
    React.useEffect(() => {
        if (!open) return;
        const t = setTimeout(() => {
            api.suggestPropertyValues({ field, q: (value || '').trim() })
                .then(setResults)
                .catch(() => setResults([]));
        }, 200);
        return () => clearTimeout(t);
    }, [value, open, field]);

    // Hide the menu when the only suggestion is exactly what's typed.
    const visible = results.filter(v => v !== (value || '').trim() || results.length > 1);

    return (
        <div className="account-picker" ref={boxRef}>
            <input
                type="text"
                className={className}
                value={value ?? ''}
                maxLength={maxLength}
                placeholder={placeholder}
                onFocus={() => setOpen(true)}
                onChange={(e) => { onValueChange(e.target.value); setOpen(true); }}
            />
            {open && visible.length > 0 && (
                <div className="account-picker-menu">
                    {visible.map(v => (
                        <div key={v} className="account-picker-item"
                             onMouseDown={() => { onValueChange(v); setOpen(false); }}>
                            <span>{v}</span>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};
