// js/components/common/SmartSelect.jsx
// Select com busca fuzzy (Levenshtein tolerance) — substituição de <select> nativo.
// Movido de index.html em Fase 5 do refactor (2026-04-29): L10122-L10195
(function() {
  'use strict';
  const {useState, useRef, useEffect, useMemo} = React;

  // CÓPIA EXATA do index.html L10122-L10195
  function SmartSelect({options,value,onChange,placeholder,style,width,autoFocus}){
    const[open,setOpen]=useState(false);
    const[q,setQ]=useState('');
    const ref=useRef(null);
    const inputRef=useRef(null);
    const norm=s=>(s||'').toString().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g,'').trim();
    const opts=useMemo(()=>options.map(o=>typeof o==='string'?{value:o,label:o}:o),[options]);
    const currentLabel=opts.find(o=>o.value!=null&&value!=null&&String(o.value)===String(value))?.label||'';
    const filtered=useMemo(()=>{
      if(!q)return opts;
      const nq=norm(q);
      const scored=opts.map(o=>{
        const t=norm(o.label);
        if(t===nq)return{o,s:4};
        if(t.startsWith(nq))return{o,s:3};
        if(t.includes(nq))return{o,s:2};
        let qi=0;for(let i=0;i<t.length&&qi<nq.length;i++)if(t[i]===nq[qi])qi++;
        if(qi===nq.length)return{o,s:1};
        // Levenshtein tolerance para palavras curtas
        if(nq.length>=3){
          const a=nq,b=t.slice(0,a.length+2);
          const d=Array.from({length:a.length+1},(_,i)=>i);
          for(let j=0;j<b.length;j++){
            let prev=j+1;
            for(let i=0;i<a.length;i++){const tmp=d[i];const cur=a[i]===b[j]?tmp:1+Math.min(tmp,d[i+1],prev);d[i]=prev;prev=cur;}
            d[a.length]=prev;
          }
          if(d[a.length]<=Math.floor(nq.length/3))return{o,s:0.5};
        }
        return null;
      }).filter(Boolean).sort((a,b)=>b.s-a.s);
      return scored.map(x=>x.o);
    },[q,opts]);
    useEffect(()=>{
      if(!open)return;
      const h=e=>{if(ref.current&&!ref.current.contains(e.target)){setOpen(false);setQ('');}};
      document.addEventListener('mousedown',h);
      return()=>document.removeEventListener('mousedown',h);
    },[open]);
    useEffect(()=>{if(open&&inputRef.current&&opts.length>4)inputRef.current.focus();},[open]);
    const select=o=>{onChange(o.value);setOpen(false);setQ('');};
    const showSearch=opts.length>4;
    return(
      <div ref={ref} style={{position:'relative',width:width||'100%',...style}}>
        <div onClick={()=>setOpen(o=>!o)} style={{display:'flex',alignItems:'center',justifyContent:'space-between',background:'#FFFFFF',border:`1px solid ${open?'#2563EB':'#E4E7EC'}`,borderRadius:6,padding:'7px 12px',cursor:'pointer',fontSize:14,color:currentLabel?'#374151':'#9CA3AF',minHeight:36,userSelect:'none'}}>
          <span style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{currentLabel||(placeholder||'— Selecione —')}</span>
          <span style={{color:'#9CA3AF',fontSize:9,marginLeft:6,flexShrink:0}}>{open?'▲':'▼'}</span>
        </div>
        {open&&(
          <div style={{position:'absolute',top:'calc(100% + 3px)',left:0,right:0,background:'#FFFFFF',border:'1px solid #E4E7EC',borderRadius:8,boxShadow:'0 8px 24px rgba(0,0,0,0.12)',zIndex:600,display:'flex',flexDirection:'column',minWidth:160}}>
            {showSearch&&(
              <div style={{padding:'8px 10px',borderBottom:'1px solid #F3F4F6'}}>
                <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)} placeholder="Pesquisar..." style={{width:'100%',border:'1px solid #E4E7EC',borderRadius:5,padding:'5px 10px',fontSize:12,outline:'none'}}
                  onKeyDown={e=>{if(e.key==='Escape'){setOpen(false);setQ('');}if(e.key==='Enter'&&filtered.length>0)select(filtered[0]);e.stopPropagation();}}/>
              </div>
            )}
            <div style={{overflowY:'auto',maxHeight:220}}>
              {filtered.length===0&&<div style={{padding:'10px 14px',color:'#9CA3AF',fontSize:13}}>Nenhum resultado</div>}
              {filtered.map(o=>(
                <div key={String(o.value)} onClick={()=>select(o)} style={{padding:'8px 14px',cursor:'pointer',fontSize:13,color:String(o.value)===String(value)?'#2563EB':'#374151',background:String(o.value)===String(value)?'#FFFBEB':'transparent',fontWeight:String(o.value)===String(value)?600:400,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}
                  onMouseEnter={e=>e.currentTarget.style.background=String(o.value)===String(value)?'#FFFBEB':'#F9FAFB'}
                  onMouseLeave={e=>e.currentTarget.style.background=String(o.value)===String(value)?'#FFFBEB':'transparent'}
                >{o.label}</div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.SmartSelect = SmartSelect;
  window.SmartSelect = SmartSelect;

  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.SmartSelect = true;

})();
