// ── COMPONENTE UNIVERSAL: Búsqueda de Cliente ────────
// Uso: <ClienteSearch value={nombre} onChange={(cliente)=>...} />

function ClienteSearch({ value, onChange, placeholder, style }) {
  const { useState, useRef, useEffect } = React;
  const [busq,     setBusq]    = useState(value||'');
  const [results,  setResults] = useState([]);
  const [open,     setOpen]    = useState(false);
  const ref = useRef();

  useEffect(() => { setBusq(value||''); }, [value]);

  function buscar(q) {
    setBusq(q);
    if (!q || q.length < 2) { setResults([]); setOpen(false); return; }
    const clts = lsGet('clientes', []);
    const found = clts.filter(c =>
      c.nombre?.toLowerCase().includes(q.toLowerCase()) ||
      c.rut?.includes(q) ||
      c.whatsapp?.includes(q)
    ).slice(0, 6);
    setResults(found);
    setOpen(found.length > 0);
  }

  function seleccionar(c) {
    setBusq(c.nombre);
    setOpen(false);
    onChange && onChange(c);
  }

  // Close on outside click
  useEffect(() => {
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  return (
    <div ref={ref} style={{ position:'relative', ...(style||{}) }}>
      <input
        style={{ ...calcStyles.input, width:'100%' }}
        placeholder={placeholder || 'Buscar cliente guardado…'}
        value={busq}
        onChange={e => buscar(e.target.value)}
        onFocus={() => busq.length >= 2 && setOpen(true)}
      />
      {open && results.length > 0 && (
        <div style={{
          position:'absolute', top:'calc(100% + 3px)', left:0, right:0, zIndex:200,
          background:'var(--bg-card)', border:'1px solid var(--border)',
          borderRadius:'8px', boxShadow:'0 6px 20px rgba(0,0,0,0.5)',
          overflow:'hidden',
        }}>
          {results.map(c => (
            <div key={c.id} onClick={() => seleccionar(c)}
              style={{ padding:'8px 12px', cursor:'pointer', borderBottom:'1px solid var(--border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}
              onMouseEnter={e => e.currentTarget.style.background='var(--surface)'}
              onMouseLeave={e => e.currentTarget.style.background='transparent'}>
              <div>
                <div style={{ color:'var(--cream)', fontSize:'12px', fontWeight:500 }}>{c.nombre}</div>
                <div style={{ color:'var(--cream-3)', fontSize:'10px' }}>
                  {[c.rut, c.whatsapp, c.email].filter(Boolean).join(' · ')}
                </div>
              </div>
              <span style={{ color:'var(--gold)', fontSize:'11px' }}>↵</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ClienteSearch });
