// tgp-search.jsx — Global search overlay (Practicals, Communities, Mensen, Events)

const SEARCH_DATA = {
  practicals: [
    { title:'Eerste OBE-poging',         type:'Building',  steps:7, img:IMG.cOBE,        by:'OBE Nederland'        },
    { title:'Holacratisch vergaderen',   type:'Knowledge', steps:4, img:IMG.cHolacracy,  by:'Holacracy Ondernemen' },
    { title:'Bosgym opstelling',         type:'Building',  steps:5, img:IMG.cGym,        by:'Eigen Gym Bouwen'     },
    { title:'Meditatie routine bouwen',  type:'Knowledge', steps:6, img:IMG.cMeditatie,  by:'Meditatie Thuis'      },
    { title:'Homeschool dagritme',       type:'Knowledge', steps:5, img:IMG.cHomeschool, by:'Homeschooling NL'     },
    { title:'Tinyhouse plattegrond',     type:'Building',  steps:8, img:IMG.cTinyhouse,  by:'Tinyhouse Nederland'  },
  ],
  communities: [
    { name:'OBE Nederland',        members:186, scope:'Nationaal',      mode:'Beide',  img:IMG.cOBE,       cost:null },
    { name:'Holacracy Ondernemen', members:94,  scope:'Nationaal',      mode:'Online', img:IMG.cHolacracy, cost:5    },
    { name:'Meditatie Thuis',      members:124, scope:'Nationaal',      mode:'Online', img:IMG.cMeditatie, cost:null },
    { name:'Tinyhouse Nederland',  members:287, scope:'Nationaal',      mode:'Beide',  img:IMG.cTinyhouse, cost:8    },
    { name:'4x4 Off-road NL',      members:312, scope:'Internationaal', mode:'Fysiek', img:IMG.cOffroad,   cost:12   },
  ],
  mensen: [
    { name:'Kees Jan',  role:'Facilitator',  src:IMG.lisa,  online:true,  tags:['OBE','Meditatie']       },
    { name:'Joep',     role:'Content Lead', src:IMG.tom,   online:true,  tags:['Holacracy','Onderwijs'] },
    { name:'Sara Ahmed',     role:'Ontwerper',    src:IMG.sara,  online:false, tags:['Tinyhouse','Bouwen']    },
    { name:'Jelle',    role:'Developer',    src:IMG.mark,  online:true,  tags:['4x4','Outdoor']         },
    { name:'Melissa',  role:'Lid',          src:IMG.nina,  online:false, tags:['Bewustzijn','Natuur']   },
    { name:'Eva Smit',       role:'Lid',          src:IMG.eva,   online:true,  tags:['Homeschool','Gezin']    },
  ],
  events: [
    { title:'Begeleide OBE-sessie',    date:'di 28 apr', time:'20:00', where:'Online — Zoom',           by:'OBE Nederland',        img:IMG.cOBE        },
    { title:'Workshop Holacracy 101',  date:'za 3 mei',  time:'14:00', where:'Impact Hub, Utrecht',     by:'Holacracy Ondernemen', img:IMG.cHolacracy  },
    { title:'Bosgym bouwdag',          date:'vr 9 mei',  time:'09:00', where:'Leusderhei',              by:'Eigen Gym Bouwen',     img:IMG.cGym        },
    { title:'Homeschool meet-up',      date:'zo 11 mei', time:'11:00', where:'De Wilde Tuin, Utrecht',  by:'Homeschooling NL',     img:IMG.cHomeschool },
  ],
};

const FILTERS = [
  { id:'all',         label:'Alles'       },
  { id:'practicals',  label:'Practicals'  },
  { id:'communities', label:'Communities' },
  { id:'mensen',      label:'Mensen'      },
  { id:'events',      label:'Events'      },
];

// ─── Result rows ──────────────────────────────────────────────────────────
const PracticalMiniIcon = ({ type }) => {
  const isBuilding = type === 'Building';
  return (
    <div style={{
      width:52, height:52, borderRadius:12, flexShrink:0,
      background:'linear-gradient(145deg, #F5F1E8 0%, #E6E0D0 100%)',
      display:'flex', alignItems:'center', justifyContent:'center',
      boxShadow:'inset 0 1px 0 rgba(255,255,255,0.6), 0 1px 2px rgba(0,0,0,0.05)',
    }}>
      {isBuilding ? (
        <svg width="36" height="36" viewBox="0 0 52 52">
          {/* Handle */}
          <path d="M 20 10 Q 20 7 23 7 L 29 7 Q 32 7 32 10 L 32 15 L 30 15 L 30 11 Q 30 9 28 9 L 24 9 Q 22 9 22 11 L 22 15 L 20 15 Z" fill="#9E978A" />
          {/* Body */}
          <rect x="8" y="15" width="36" height="30" rx="3" fill="#FAF8F4" stroke="rgba(0,0,0,0.1)" />
          {/* Lid seam */}
          <line x1="8" y1="23" x2="44" y2="23" stroke="rgba(0,0,0,0.12)" strokeWidth="1"/>
          {/* Latches */}
          <rect x="14" y="20" width="6" height="6" rx="1" fill="#CFC9BC" stroke="rgba(0,0,0,0.1)" />
          <rect x="32" y="20" width="6" height="6" rx="1" fill="#CFC9BC" stroke="rgba(0,0,0,0.1)" />
        </svg>
      ) : (
        <svg width="36" height="36" viewBox="0 0 52 52">
          {/* Pages edge right */}
          <rect x="43" y="10" width="2.5" height="33" fill="#F0EDE5" stroke="rgba(0,0,0,0.08)" strokeWidth="0.5"/>
          {/* Book cover */}
          <rect x="7" y="9" width="37" height="35" rx="3" fill="#FAF8F4" stroke="rgba(0,0,0,0.1)" />
          {/* Spine */}
          <rect x="7" y="9" width="6" height="35" rx="1" fill="#C7C0B1" />
          <line x1="10" y1="15" x2="13" y2="15" stroke="rgba(0,0,0,0.15)" strokeWidth="0.8" />
          <line x1="10" y1="38" x2="13" y2="38" stroke="rgba(0,0,0,0.15)" strokeWidth="0.8" />
          {/* Title lines */}
          <line x1="17" y1="18" x2="40" y2="18" stroke="rgba(0,0,0,0.1)" strokeWidth="1" />
          <line x1="17" y1="23" x2="40" y2="23" stroke="rgba(0,0,0,0.1)" strokeWidth="1" />
          <line x1="17" y1="28" x2="35" y2="28" stroke="rgba(0,0,0,0.1)" strokeWidth="1" />
        </svg>
      )}
    </div>
  );
};

const PracticalRow = ({ item }) => (
  <div style={{ display:'flex', gap:12, alignItems:'center', padding:'10px 14px', borderRadius:14, cursor:'pointer' }}
    onMouseEnter={e=>e.currentTarget.style.background='#F7F7F7'}
    onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
    <PracticalMiniIcon type={item.type} />
    <div style={{ flex:1, minWidth:0 }}>
      <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:3 }}>
        <span style={{ fontSize:9.5, padding:'2px 7px', borderRadius:999, fontWeight:600, background:item.type==='Knowledge'?'rgba(0,122,255,0.12)':'rgba(255,77,26,0.12)', color:item.type==='Knowledge'?'#007AFF':'#FF4D1A', fontFamily:'Inter,system-ui,sans-serif' }}>{item.type}</span>
        <span style={{ fontSize:10.5, color:'#8E8E93', fontFamily:'Inter,system-ui,sans-serif' }}>{item.steps} stappen</span>
      </div>
      <div style={{ fontSize:14, fontWeight:600, color:'#020100', fontFamily:'Inter,system-ui,sans-serif', letterSpacing:'-0.1px', marginBottom:2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{item.title}</div>
      <div style={{ fontSize:11, color:'#9B9B9B', fontFamily:'Inter,system-ui,sans-serif' }}>{item.by}</div>
    </div>
  </div>
);

const CommunityRow = ({ item }) => {
  const scopeCol = { 'Lokaal':'#6B8F6F', 'Nationaal':'#4A7EC4', 'Internationaal':'#C86B4B' }[item.scope] || '#6B8F6F';
  return (
    <div style={{ display:'flex', gap:12, alignItems:'center', padding:'10px 14px', borderRadius:14, cursor:'pointer' }}
      onMouseEnter={e=>e.currentTarget.style.background='#F7F7F7'}
      onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
      <img src={item.img} alt="" style={{ width:52, height:52, borderRadius:12, objectFit:'cover', flexShrink:0 }} />
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:14, fontWeight:700, color:'#020100', fontFamily:'Inter,system-ui,sans-serif', letterSpacing:'-0.1px', marginBottom:4, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{item.name}</div>
        <div style={{ display:'flex', gap:5, alignItems:'center', flexWrap:'wrap' }}>
          <span style={{ fontSize:10, padding:'2px 7px', borderRadius:999, fontWeight:600, background:`${scopeCol}18`, color:scopeCol, fontFamily:'Inter,system-ui,sans-serif' }}>{item.scope}</span>
          <span style={{ fontSize:11, color:'#8E8E93', fontFamily:'Inter,system-ui,sans-serif' }}>{item.members} leden</span>
          <span style={{ fontSize:11, fontWeight:600, color:item.cost?'#8E8E93':'#34C759', fontFamily:'Inter,system-ui,sans-serif' }}>· {item.cost?`€${item.cost}/mnd`:'Gratis'}</span>
        </div>
      </div>
    </div>
  );
};

const PersonRow = ({ item }) => (
  <div style={{ display:'flex', gap:12, alignItems:'center', padding:'10px 14px', borderRadius:14, cursor:'pointer' }}
    onMouseEnter={e=>e.currentTarget.style.background='#F7F7F7'}
    onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
    <div style={{ position:'relative', flexShrink:0 }}>
      <img src={item.src} alt="" style={{ width:48, height:48, borderRadius:'50%', objectFit:'cover' }} />
      {item.online && <span style={{ position:'absolute', bottom:1, right:1, width:11, height:11, borderRadius:'50%', background:'#34C759', border:'2px solid #fff' }} />}
    </div>
    <div style={{ flex:1, minWidth:0 }}>
      <div style={{ fontSize:14, fontWeight:700, color:'#020100', fontFamily:'Inter,system-ui,sans-serif', letterSpacing:'-0.1px', marginBottom:3 }}>{item.name}</div>
      <div style={{ display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
        <span style={{ fontSize:11, padding:'2px 8px', borderRadius:999, background:'rgba(116,116,128,0.1)', color:'#8E8E93', fontFamily:'Inter,system-ui,sans-serif' }}>{item.role}</span>
        {item.tags.slice(0,1).map(t => (
          <span key={t} style={{ fontSize:11, color:'#9B9B9B', fontFamily:'Inter,system-ui,sans-serif' }}>· {t}</span>
        ))}
      </div>
    </div>
  </div>
);

const EventRow = ({ item }) => (
  <div style={{ display:'flex', gap:12, alignItems:'center', padding:'10px 14px', borderRadius:14, cursor:'pointer' }}
    onMouseEnter={e=>e.currentTarget.style.background='#F7F7F7'}
    onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
    <div style={{ width:52, height:52, borderRadius:12, background:'rgba(0,122,255,0.1)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
      <span style={{ fontSize:9, fontWeight:600, color:'#007AFF', fontFamily:'Inter,system-ui,sans-serif', letterSpacing:'0.04em', textTransform:'uppercase' }}>{item.date.split(' ')[0]}</span>
      <span style={{ fontSize:18, fontWeight:800, color:'#007AFF', fontFamily:'Inter,system-ui,sans-serif', lineHeight:1 }}>{item.date.split(' ')[1]}</span>
      <span style={{ fontSize:9, color:'#007AFF', fontFamily:'Inter,system-ui,sans-serif', textTransform:'lowercase' }}>{item.date.split(' ')[2]}</span>
    </div>
    <div style={{ flex:1, minWidth:0 }}>
      <div style={{ fontSize:14, fontWeight:600, color:'#020100', fontFamily:'Inter,system-ui,sans-serif', letterSpacing:'-0.1px', marginBottom:3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{item.title}</div>
      <div style={{ fontSize:11, color:'#8E8E93', fontFamily:'Inter,system-ui,sans-serif', marginBottom:2 }}>{item.time} · {item.where}</div>
      <div style={{ fontSize:11, color:'#9B9B9B', fontFamily:'Inter,system-ui,sans-serif' }}>{item.by}</div>
    </div>
  </div>
);

// ─── Result group (with heading) ───────────────────────────────────────────
const ResultGroup = ({ title, count, children }) => (
  <div style={{ marginBottom:14 }}>
    <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', padding:'8px 16px 6px' }}>
      <span style={{ fontSize:11, fontWeight:700, color:'#8E8E93', fontFamily:'Inter,system-ui,sans-serif', textTransform:'uppercase', letterSpacing:'0.08em' }}>{title}</span>
      <span style={{ fontSize:11, color:'#C7C7CC', fontFamily:'Inter,system-ui,sans-serif' }}>{count}</span>
    </div>
    <div style={{ padding:'0 2px' }}>{children}</div>
  </div>
);

// ─── SearchPage overlay ────────────────────────────────────────────────────
const SearchPage = ({ isOpen, onClose }) => {
  const [query,  setQuery]  = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (isOpen && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 360);
    }
    if (!isOpen) {
      const t = setTimeout(() => { setQuery(''); setFilter('all'); }, 300);
      return () => clearTimeout(t);
    }
  }, [isOpen]);

  const q = query.trim().toLowerCase();
  const match = (txt) => !q || (txt || '').toLowerCase().includes(q);

  const practicals  = SEARCH_DATA.practicals .filter(x => match(x.title) || match(x.by) || match(x.type));
  const communities = SEARCH_DATA.communities.filter(x => match(x.name)  || match(x.scope));
  const mensen      = SEARCH_DATA.mensen     .filter(x => match(x.name)  || match(x.role) || x.tags.some(match));
  const events      = SEARCH_DATA.events     .filter(x => match(x.title) || match(x.where) || match(x.by));

  const showP = filter==='all' || filter==='practicals';
  const showC = filter==='all' || filter==='communities';
  const showM = filter==='all' || filter==='mensen';
  const showE = filter==='all' || filter==='events';

  const totalShown =
    (showP?practicals.length:0) + (showC?communities.length:0) +
    (showM?mensen.length:0)     + (showE?events.length:0);

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position:'absolute', inset:0, zIndex:250,
        background:'rgba(20,18,16,0.38)', backdropFilter:'blur(3px)', WebkitBackdropFilter:'blur(3px)',
        opacity:isOpen?1:0, pointerEvents:isOpen?'auto':'none', transition:'opacity 0.25s',
      }} />

      {/* Overlay */}
      <div style={{
        position:'absolute', top:12, left:12, bottom:95, right:14,
        background:'#FFFFFF', borderRadius:26, zIndex:260, overflow:'hidden',
        boxShadow:'0 24px 60px rgba(0,0,0,0.25), 0 0 0 1px rgba(0,0,0,0.04)',
        transformOrigin:'top left',
        transform:isOpen?'scale(1)':'scale(0.02)',
        opacity:isOpen?1:0,
        transition:'transform 0.38s cubic-bezier(0.2, 0.9, 0.25, 1), opacity 0.26s',
        pointerEvents:isOpen?'auto':'none',
        display:'flex', flexDirection:'column',
      }}>
        {/* Header */}
        <div style={{ padding:'18px 18px 10px', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <h1 style={{
            fontFamily:'"Instrument Serif", Georgia, serif',
            fontWeight:400, fontSize:28, color:'#020100',
            margin:0, lineHeight:1, letterSpacing:'-0.4px', flex:1,
          }}>Zoeken</h1>
          <button onClick={onClose} style={{
            width:32, height:32, borderRadius:'50%',
            background:'rgba(116,116,128,0.15)', border:'none',
            display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
          }}>
            <Ico.X size={14} />
          </button>
        </div>

        {/* Search input */}
        <div style={{ padding:'0 18px 10px', flexShrink:0 }}>
          <div style={{
            display:'flex', alignItems:'center', gap:10,
            background:'rgba(116,116,128,0.12)', borderRadius:14,
            padding:'11px 14px',
          }}>
            <Ico.Search size={16} color="rgba(2,1,0,0.5)" />
            <input
              ref={inputRef}
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Zoek practicals, communities, mensen, events..."
              style={{
                flex:1, border:'none', background:'transparent', outline:'none',
                fontSize:14, fontFamily:'Inter, system-ui, sans-serif', color:'#020100',
              }}
            />
            {query && (
              <button onClick={()=>setQuery('')} style={{
                border:'none', background:'rgba(116,116,128,0.2)', width:20, height:20, borderRadius:'50%',
                display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', padding:0,
              }}>
                <Ico.X size={10} />
              </button>
            )}
          </div>
        </div>

        {/* Filter pills */}
        <div style={{ padding:'0 18px 10px', display:'flex', gap:6, overflowX:'auto', scrollbarWidth:'none', flexShrink:0 }}>
          {FILTERS.map(f => (
            <button key={f.id} onClick={()=>setFilter(f.id)} style={{
              padding:'7px 14px', borderRadius:999, border:'none', whiteSpace:'nowrap',
              background: filter===f.id ? '#020100' : 'rgba(116,116,128,0.12)',
              color:      filter===f.id ? '#FFFFFF' : 'rgba(2,1,0,0.7)',
              fontSize:12, fontWeight: filter===f.id?600:500, cursor:'pointer',
              fontFamily:'Inter, system-ui, sans-serif', transition:'all 0.15s',
            }}>{f.label}</button>
          ))}
        </div>

        {/* Results */}
        <div style={{ flex:1, overflowY:'auto', scrollbarWidth:'none', padding:'4px 0 20px' }}>
          {totalShown === 0 ? (
            <div style={{ textAlign:'center', padding:'60px 24px 20px', color:'#8E8E93' }}>
              <Ico.Search size={28} color="#C7C7CC" />
              <div style={{ fontSize:14, fontWeight:600, color:'#020100', fontFamily:'Inter,system-ui,sans-serif', margin:'12px 0 4px' }}>
                {q ? 'Geen resultaten' : 'Begin met typen'}
              </div>
              <div style={{ fontSize:12, color:'#8E8E93', fontFamily:'Inter,system-ui,sans-serif' }}>
                {q ? `We vonden niets voor "${query}"` : 'Zoek naar practicals, communities, mensen of events'}
              </div>
            </div>
          ) : (
            <>
              {showP && practicals.length>0 && (
                <ResultGroup title="Practicals" count={practicals.length}>
                  {practicals.map(p => <PracticalRow key={p.title} item={p} />)}
                </ResultGroup>
              )}
              {showC && communities.length>0 && (
                <ResultGroup title="Communities" count={communities.length}>
                  {communities.map(c => <CommunityRow key={c.name} item={c} />)}
                </ResultGroup>
              )}
              {showM && mensen.length>0 && (
                <ResultGroup title="Mensen" count={mensen.length}>
                  {mensen.map(m => <PersonRow key={m.name} item={m} />)}
                </ResultGroup>
              )}
              {showE && events.length>0 && (
                <ResultGroup title="Events" count={events.length}>
                  {events.map(ev => <EventRow key={ev.title} item={ev} />)}
                </ResultGroup>
              )}
            </>
          )}
        </div>
      </div>
    </>
  );
};

Object.assign(window, { SearchPage });
