// Pickers.jsx — Bottom-sheet pickers: species, admin levels, value lists.

// Generic bottom-sheet shell
function BottomSheet({ open, onClose, title, subtitle, children, height }) {
  if (!open) return null;
  return (
    <div style={{position:'absolute',inset:0,zIndex:50,display:'flex',flexDirection:'column',justifyContent:'flex-end',background:'rgba(2,28,24,0.55)'}} onClick={onClose}>
      <div onClick={(e)=>e.stopPropagation()} style={{background:'#fff',borderTopLeftRadius:18,borderTopRightRadius:18,maxHeight: height || '85%',display:'flex',flexDirection:'column',overflow:'hidden',animation:'sheetIn .2s ease-out',boxShadow:'0 -8px 30px rgba(0,0,0,0.2)'}}>
        <div style={{padding:'10px 0 4px',display:'flex',justifyContent:'center'}}>
          <div style={{width:42,height:4,borderRadius:2,background:'#D1D5DB'}}/>
        </div>
        <div style={{padding:'8px 18px 14px',display:'flex',alignItems:'flex-start',gap:10,borderBottom:'1px solid #F3F4F6'}}>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:16,fontWeight:900,color:'#022C28',letterSpacing:'-0.01em'}}>{title}</div>
            {subtitle && <div style={{fontSize:12,color:'#6B7280',marginTop:2}}>{subtitle}</div>}
          </div>
          <button onClick={onClose} aria-label="Close" style={{background:'#F3F4F6',border:'none',width:32,height:32,borderRadius:'50%',display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',flexShrink:0}}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#022C28" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div style={{flex:1,overflowY:'auto'}}>{children}</div>
      </div>
      <style>{`@keyframes sheetIn { from { transform: translateY(20px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }`}</style>
    </div>
  );
}

// Simple value-list picker (radio)
function ListPicker({ open, onClose, title, subtitle, options, value, onPick }) {
  return (
    <BottomSheet open={open} onClose={onClose} title={title} subtitle={subtitle}>
      <div style={{padding:'4px 0 16px'}}>
        {options.map(opt => {
          const v = typeof opt === 'string' ? opt : opt.value;
          const l = typeof opt === 'string' ? opt : opt.label;
          const h = typeof opt === 'string' ? null : opt.hint;
          const sel = value === v;
          return (
            <button key={v} onClick={()=>{ onPick(v); onClose(); }}
              style={{background: sel ? '#FFF8E0' : 'transparent',border:'none',padding:'14px 18px',width:'100%',textAlign:'left',display:'flex',alignItems:'center',gap:12,cursor:'pointer',fontFamily:'inherit',borderBottom:'1px solid #F6F8F7'}}>
              <div style={{width:20,height:20,borderRadius:'50%',border:`2px solid ${sel?'#F4C300':'#D1D5DB'}`,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                {sel && <div style={{width:10,height:10,borderRadius:'50%',background:'#F4C300'}}/>}
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:14,fontWeight:700,color:'#022C28'}}>{l}</div>
                {h && <div style={{fontSize:11,color:'#6B7280',marginTop:2}}>{h}</div>}
              </div>
            </button>
          );
        })}
      </div>
    </BottomSheet>
  );
}

// Species picker — search, kind filter, multi-select, mark dominant
function SpeciesPicker({ open, onClose, value, dominant, onChange, onDominantChange, standKind }) {
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState('all');

  React.useEffect(()=>{
    if (open && standKind && filter === 'all') {
      // Default the filter to current stand kind when opening from a known-kind context
      setFilter(standKind.toLowerCase());
    }
  // eslint-disable-next-line
  }, [open]);

  const kindFilter = {
    all:'All', tree:'Trees', bamboo:'Bamboo', shrub:'Shrubs', mixed:'All',
  };

  const list = SPECIES
    .filter(s => filter === 'all' || filter === 'mixed' ? true : s.kind.toLowerCase() === filter)
    .filter(s => {
      const q = query.trim().toLowerCase();
      if (!q) return true;
      return s.sci.toLowerCase().includes(q) || s.common.toLowerCase().includes(q);
    });

  const shortlist = list.filter(s=>s.shortlist);
  const rest      = list.filter(s=>!s.shortlist);

  const toggle = (id) => {
    const has = value.includes(id);
    const next = has ? value.filter(x=>x!==id) : [...value, id];
    onChange(next);
    if (has && dominant === id) onDominantChange(null);
    if (!has && value.length === 0) onDominantChange(id); // first pick becomes dominant
  };

  const Row = ({ s }) => {
    const sel = value.includes(s.id);
    const isDom = dominant === s.id;
    const kindColors = { Tree:'#059669', Bamboo:'#0F766E', Shrub:'#92400E', Mixed:'#6D28D9' };
    return (
      <div style={{display:'flex',alignItems:'center',gap:12,padding:'10px 18px',background:sel?'#FFF8E0':'transparent',borderBottom:'1px solid #F6F8F7'}}>
        <button onClick={()=>toggle(s.id)} style={{flex:1,minWidth:0,background:'none',border:'none',padding:0,textAlign:'left',cursor:'pointer',fontFamily:'inherit',display:'flex',alignItems:'center',gap:12}}>
          <div style={{width:20,height:20,borderRadius:5,border:`2px solid ${sel?'#F4C300':'#D1D5DB'}`,background:sel?'#F4C300':'#fff',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
            {sel && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#022C28" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>}
          </div>
          <div style={{flex:1,minWidth:0}}>
            <div style={{display:'flex',gap:6,alignItems:'baseline'}}>
              <span style={{fontSize:14,fontWeight:800,color:'#022C28',letterSpacing:'-0.01em'}}>{s.common}</span>
              {s.native && <span style={{fontSize:9,fontWeight:800,letterSpacing:'0.06em',padding:'1px 5px',borderRadius:3,background:'#ECFDF5',color:'#065F46'}}>NATIVE</span>}
              {s.shortlist && <span style={{fontSize:9,fontWeight:800,letterSpacing:'0.06em',padding:'1px 5px',borderRadius:3,background:'#FFF8E0',color:'#B8960A'}}>PROJECT</span>}
            </div>
            <div style={{fontSize:12,color:'#6B7280',fontStyle:'italic',marginTop:1}}>{s.sci} · <span style={{color:kindColors[s.kind],fontWeight:700,fontStyle:'normal'}}>{s.kind}</span></div>
          </div>
        </button>
        {sel && (
          <button onClick={()=>onDominantChange(isDom ? null : s.id)} title={isDom?'Unmark main species':'Mark as main species'} style={{background:isDom?'#022C28':'#F3F4F6',color:isDom?'#F4C300':'#6B7280',border:'none',padding:'6px 8px',borderRadius:6,fontSize:9,fontWeight:800,letterSpacing:'0.06em',cursor:'pointer',fontFamily:'inherit',flexShrink:0}}>
            {isDom?'★ MAIN':'☆ MAIN?'}
          </button>
        )}
      </div>
    );
  };

  return (
    <BottomSheet open={open} onClose={onClose} title="Species" subtitle={`${value.length} selected${dominant?' · 1 main':''}`} height="92%">
      {/* Search */}
      <div style={{padding:'14px 18px 8px',background:'#fff',position:'sticky',top:0,zIndex:2}}>
        <div style={{position:'relative'}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{position:'absolute',left:12,top:'50%',transform:'translateY(-50%)'}}>
            <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
          </svg>
          <input
            value={query}
            onChange={(e)=>setQuery(e.target.value)}
            placeholder="Search common or scientific name…"
            style={{width:'100%',padding:'10px 12px 10px 38px',border:'1.5px solid #E5E7EB',borderRadius:10,fontSize:14,fontFamily:'inherit',color:'#022C28',outline:'none',boxSizing:'border-box'}}/>
        </div>
        <div style={{display:'flex',gap:6,marginTop:10,overflowX:'auto',paddingBottom:4}}>
          {Object.entries(kindFilter).map(([id,l])=>(
            <button key={id} onClick={()=>setFilter(id)} style={{padding:'6px 12px',border:'none',background:filter===id?'#022C28':'#F3F4F6',color:filter===id?'#fff':'#6B7280',borderRadius:999,fontSize:11,fontWeight:800,letterSpacing:'0.04em',cursor:'pointer',fontFamily:'inherit',whiteSpace:'nowrap'}}>{l}</button>
          ))}
        </div>
      </div>

      {/* Lists */}
      <div>
        {shortlist.length > 0 && <>
          <div style={{padding:'10px 18px 4px',fontSize:10,fontWeight:800,letterSpacing:'0.1em',textTransform:'uppercase',color:'#B8960A',fontFamily:"'JetBrains Mono', monospace"}}>On this project · Bunyala</div>
          {shortlist.map(s => <Row key={s.id} s={s}/>)}
        </>}
        {rest.length > 0 && <>
          <div style={{padding:'14px 18px 4px',fontSize:10,fontWeight:800,letterSpacing:'0.1em',textTransform:'uppercase',color:'#6B7280',fontFamily:"'JetBrains Mono', monospace"}}>All species</div>
          {rest.map(s => <Row key={s.id} s={s}/>)}
        </>}
        {list.length === 0 && (
          <div style={{padding:'30px 18px',textAlign:'center',color:'#6B7280',fontSize:13}}>
            No match. Try a different spelling, or pick "Species unknown" below.
          </div>
        )}
      </div>

      {/* Sticky footer */}
      <div style={{padding:'12px 18px',borderTop:'1px solid #E5E7EB',background:'#fff',display:'flex',gap:10,alignItems:'center'}}>
        <button onClick={()=>{ onChange(['sp_unknown']); onDominantChange('sp_unknown'); onClose(); }} style={{flex:1,padding:'12px',background:'#fff',color:'#022C28',border:'1.5px solid #E5E7EB',borderRadius:10,fontWeight:800,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>
          Species unknown · photo
        </button>
        <button onClick={onClose} style={{flex:1,padding:'12px',background:'#022C28',color:'#fff',border:'none',borderRadius:10,fontWeight:900,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>
          Done · {value.length} selected
        </button>
      </div>
    </BottomSheet>
  );
}

// Lookup helpers
function speciesById(id) {
  if (id === 'sp_unknown') return { id:'sp_unknown', sci:'Species not identified', common:'Species unknown', kind:'Mixed', native:false, shortlist:false };
  return SPECIES.find(s => s.id === id);
}

Object.assign(window, { BottomSheet, ListPicker, SpeciesPicker, speciesById });
