function SearchEmpty({ tab, q, onAction, onClear }) {
  const copy = {
    '게시물': { icon: 'photo-search', title: '"' + q + '" 사진이 아직 없어요', body: '메뉴 이름이나 해시태그로 다시 찾아보거나, 첫 사진을 직접 올려보세요.', cta: '이 메뉴로 사진 올리기', ctaIcon: 'camera', chips: ['#순대국', '#떡볶이', '#브런치', '#야식'] },
    '맛집': { icon: 'map-pin-question', title: '"' + q + '" 가게를 못 찾았어요', body: '아직 등록되지 않은 곳일 수 있어요. 직접 등록하면 이웃들도 찾을 수 있어요.', cta: '새 가게 등록하기', ctaIcon: 'map-pin-plus', chips: ['한식', '분식', '카페·디저트', '야식'] },
    '회원': { icon: 'user-search', title: '"' + q + '" 닉네임이 없어요', body: '닉네임 전체를 정확히 입력해야 찾을 수 있어요. 대신 같은 동네 이웃을 추천해드릴까요?', cta: '추천 이웃 보기', ctaIcon: 'users', chips: [] }
  }[tab];
  return (
    <div style={{ padding: '24px 20px 104px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
      <div style={{ width: 62, height: 62, borderRadius: '50%', background: 'var(--surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}><i className={'ti ti-' + copy.icon} style={{ fontSize: 27, color: 'var(--text-muted)' }}></i></div>
      <span style={{ font: 'var(--text-body-strong)', display: 'block', marginBottom: 8, wordBreak: 'break-all' }}>{copy.title}</span>
      <p style={{ font: 'var(--text-caption)', color: 'var(--text-secondary)', margin: '0 0 20px', lineHeight: 1.65, textWrap: 'pretty', maxWidth: 280 }}>{copy.body}</p>
      <span onClick={onAction} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, font: '600 14px/1 var(--font-family)', color: '#fff', background: 'var(--bg-ink)', borderRadius: 999, padding: '14px 22px', cursor: 'pointer' }}><i className={'ti ti-' + copy.ctaIcon} style={{ fontSize: 16 }}></i>{copy.cta}</span>
      <span onClick={onClear} style={{ font: 'var(--text-small)', color: 'var(--text-muted)', marginTop: 14, cursor: 'pointer', borderBottom: '1px solid var(--border-strong)' }}>검색어 지우기</span>
      {copy.chips.length > 0 && (
        <div style={{ width: '100%', marginTop: 30 }}>
          <span style={{ font: 'var(--text-small)', color: 'var(--text-muted)', display: 'block', marginBottom: 10, textAlign: 'left' }}>이런 검색은 어때요?</span>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'flex-start' }}>
            {copy.chips.map(c => <span key={c} onClick={() => onClear(c)} style={{ font: 'var(--text-caption)', color: 'var(--text-primary)', background: 'var(--surface-1)', border: '1px solid var(--border)', borderRadius: 999, padding: '11px 15px', cursor: 'pointer' }}>{c}</span>)}
          </div>
        </div>
      )}
    </div>
  );
}
window.SearchEmpty = SearchEmpty;

function UserRow({ u, following, onToggle, onClick }) {
  const { Avatar } = window.SpotureDesignSystem_f7ad96;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-1)', borderRadius: 'var(--radius-card)', padding: 14, boxShadow: 'var(--shadow-card)' }}>
      <div onClick={onClick} style={{ cursor: 'pointer', display: 'flex', flexShrink: 0 }}><Avatar user={u.name} size={48} /></div>
      <div onClick={onClick} style={{ flex: 1, minWidth: 0, cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 3 }}>
          <span style={{ font: 'var(--text-body-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.name}</span>
          {u.badges && u.badges.slice(0, 2).map(b => <i key={b} className={'ti ti-' + b} style={{ fontSize: 13, color: 'var(--text-accent)', flexShrink: 0 }}></i>)}
          {u.badges && u.badges.length > 2 && <span style={{ font: 'var(--text-micro)', color: 'var(--text-accent)' }}>+{u.badges.length - 2}</span>}
        </div>
        <span style={{ font: 'var(--text-small)', color: 'var(--text-secondary)', display: 'block', marginBottom: 2 }}>{u.title}</span>
        <span style={{ font: 'var(--text-micro)', color: 'var(--text-muted)' }}>게시물 {u.posts} · 팔로워 {u.followers}</span>
      </div>
      <span onClick={onToggle} style={{ flexShrink: 0, font: '600 13px/1 var(--font-family)', color: following ? 'var(--text-secondary)' : '#fff', background: following ? 'var(--surface-2)' : 'var(--text-accent)', border: following ? '1px solid var(--border-strong)' : 'none', borderRadius: 999, padding: '11px 15px', cursor: 'pointer' }}>{following ? '팔로잉' : '팔로우'}</span>
    </div>
  );
}

function Search({ nav }) {
  const { SearchBar, ChipFilter, RestaurantCard, Avatar } = window.SpotureDesignSystem_f7ad96;
  const sp = new URLSearchParams(location.search);
  const [q, setQ] = React.useState(sp.get('sq') || '');
  const [menuPost, setMenuPost] = React.useState(null);
  const [tab, setTab] = React.useState({ place: '맛집', user: '회원' }[sp.get('stab')] || '게시물');
  const [cat, setCat] = React.useState('전체');
  const [follow, setFollow] = React.useState({ 1: true });
  const [filterOpen, setFilterOpen] = React.useState(false);
  const [open, setOpen] = React.useState(null);
  const noResult = q.trim().length > 0 && (sp.get('sempty') === '1' || /zzz|qqq|xxxx/.test(q));
  const [pf, setPf] = React.useState({ radius: '500m', sort: '거리순', rating: '전체', open: false, hasPhoto: false });
  const [uf, setUf] = React.useState({ radius: '이 동네', sort: '팔로워순', badge: '전체', followingOnly: false });
  const [gf, setGf] = React.useState({ radius: '500m', sort: '최신순', media: '전체', hasPlace: false });
  const active = tab === '맛집' ? pf : tab === '회원' ? uf : gf;
  const activeChips = tab === '맛집'
    ? [active.radius !== '전체' && '반경 ' + active.radius, active.sort, active.rating !== '전체' && '평점 ' + active.rating, active.open && '영업중', active.hasPhoto && '사진 5장+'].filter(Boolean)
    : tab === '회원'
      ? [active.radius, active.sort, active.badge !== '전체' && active.badge, active.followingOnly && '팔로잉만'].filter(Boolean)
      : [active.radius !== '전체' && '반경 ' + active.radius, active.sort, active.media !== '전체' && active.media, active.hasPlace && '위치 등록됨'].filter(Boolean);
  const recents = tab === '맛집' ? ['할매순대국', '역삼동 국밥', '청년다방', '감성타코'] : tab === '회원' ? ['국밥러버92', '야식탐험가', '카페인탐정'] : ['#갈치조림', '#야식', '#분식', '#브런치'];
  const results = [
    { name: '할매순대국 강남점', category: '한식', distance: '45m', photos: 128, likes: 642 },
    { name: '감성타코 야식당', category: '멕시칸', distance: '60m', photos: 34, likes: 214 },
    { name: '청년다방 역삼점', category: '카페·디저트', distance: '120m', photos: 18, likes: 96 },
    { name: '역삼동 국밥집', category: '한식', distance: '180m', photos: 52, likes: 331 }
  ];
  const posts = [
    { user: '국밥러버92', badges: ['soup', 'map-pin-check'], place: '금강산초다리 역삼점', menu: '갈치조림', mediaCount: 4, likes: 128, time: '2시간 전', src: '../../assets/feed/jorim-1.jpeg' },
    { user: '야식탐험가', badges: ['moon-stars'], place: '우나기야 역삼', menu: '장어덮밥', mediaCount: 6, likes: 91, time: '5시간 전', src: '../../assets/feed/unagi-don.jpeg' },
    { user: '토박이야식', badges: [], menu: '로스카츠', mediaCount: 2, likes: 17, time: '어제', src: '../../assets/feed/tonkatsu.jpeg' },
    { user: '떡볶이덕후', badges: ['bowl-chopsticks', 'award'], place: '역삼 참숯갈비', menu: '한우 모둠', mediaCount: 3, likes: 210, time: '어제', src: '../../assets/feed/hanwoo-raw.jpeg' },
    { user: '카페인탐정', badges: ['coffee'], place: '나무가나길 커피', menu: '핸드드립', mediaCount: 1, likes: 44, time: '2일 전', src: '../../assets/feed/cafe-1.jpeg' },
    { user: '밥순이', badges: ['building-store'], place: '분짜하노이 역삼', menu: '분짜', mediaCount: 5, likes: 63, time: '3일 전', src: '../../assets/feed/buncha-1.jpeg' }
  ];
  const users = [
    { name: '국밥러버92', title: '국밥전문가 · 위치제보왕', badges: ['soup', 'map-pin-check', 'building-store'], posts: 128, followers: '1.2천' },
    { name: '야식탐험가', title: '야식탐험가 · 야식러버', badges: ['moon-stars', 'flame'], posts: 91, followers: 842 },
    { name: '카페인탐정', title: '카페인탐정', badges: ['coffee'], posts: 44, followers: 213 },
    { name: '떡볶이덕후', title: '분식마스터 · 게시물 50개', badges: ['bowl-chopsticks', 'award'], posts: 57, followers: 396 }
  ];
  return (
    <div style={{ flex: '1 1 0%', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      <StatusBar />
      <div style={{ flex: '1 1 0%', minHeight: 0, overflowY: 'auto' }}>
      <ScreenHeader title="검색" sub={tab === '맛집' ? '가까운 맛집부터 보여드려요' : tab === '회원' ? '취향이 맞는 이웃을 찾아보세요' : '이웃이 올린 사진과 메뉴를 찾아보세요'} />
      <div style={{ padding: '0 20px 14px' }}><SearchBar value={q} onChange={setQ} placeholder={tab === '맛집' ? '맛집·메뉴 검색' : tab === '회원' ? '닉네임 검색' : '메뉴 · 해시태그 · 사진 검색'} onFilter={() => setFilterOpen(true)} /></div>
      <div style={{ display: 'flex', gap: 18, padding: '0 20px', borderBottom: '1px solid var(--border)', margin: '0 0 16px' }}>
        {['게시물', '맛집', '회원'].map(t => (
          <span key={t} onClick={() => { setTab(t); setCat('전체'); }} style={{ font: tab === t ? '700 16px/1.2 var(--font-family)' : '400 16px/1.2 var(--font-family)', color: tab === t ? 'var(--text-primary)' : 'var(--text-muted)', cursor: 'pointer', paddingBottom: 12, marginBottom: -1, borderBottom: tab === t ? '2px solid var(--text-accent)' : '2px solid transparent' }}>{t}</span>
        ))}
      </div>
      {!q && (
        <div style={{ padding: '0 20px 18px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
            <span style={{ font: 'var(--text-body-strong)' }}>최근 검색</span>
            <span style={{ font: 'var(--text-small)', color: 'var(--text-muted)', cursor: 'pointer' }}>전체 삭제</span>
          </div>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -20px', padding: '0 20px', scrollbarWidth: 'none' }}>
            {recents.map(r => (
              <span key={r} onClick={() => setQ(r)} style={{ flexShrink: 0, whiteSpace: 'nowrap', font: 'var(--text-caption)', color: 'var(--text-primary)', background: 'var(--surface-1)', borderRadius: 'var(--radius-chip)', padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>{r}<i className="ti ti-x" style={{ fontSize: 12, color: 'var(--text-muted)' }}></i></span>
            ))}
          </div>
        </div>
      )}
      {tab !== '회원' && (
        <div style={{ display: 'flex', gap: 8, padding: '0 20px 18px', overflowX: 'auto' }}>
          {(tab === '맛집' ? ['전체', '한식', '분식', '카페·디저트', '멕시칸', '야식'] : ['전체', '#순대국', '#떡볶이', '#브런치', '#야식', '#커피']).map(c => <ChipFilter key={c} label={c} active={cat === c} onClick={() => setCat(c)} />)}
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '0 20px 14px', overflowX: 'auto' }}>
        {activeChips.map(c => (
          <span key={c} onClick={() => setFilterOpen(true)} style={{ flexShrink: 0, font: 'var(--text-small)', color: 'var(--text-secondary)', background: 'var(--surface-1)', border: '1px solid var(--border)', borderRadius: 999, padding: '8px 12px', display: 'inline-flex', alignItems: 'center', gap: 5, cursor: 'pointer' }}><i className="ti ti-adjustments-horizontal" style={{ fontSize: 12, color: 'var(--text-muted)' }}></i>{c}</span>
        ))}
      </div>
      {noResult ? (
        <SearchEmpty tab={tab} q={q} onAction={() => nav(tab === '회원' ? 'follows' : 'upload')} onClear={(v) => setQ(typeof v === 'string' ? v : '')} />
      ) : tab === '게시물' ? (
        <div style={{ padding: '0 20px 104px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gridAutoRows: 'min-content', gap: 10 }}>
            {posts.map((p, i) => (
              <div key={p.user + i} onClick={() => setOpen(p)} style={{ background: 'var(--surface-1)', borderRadius: 'var(--radius-card)', overflow: 'hidden', boxShadow: 'var(--shadow-card)', cursor: 'pointer' }}>
                <div style={{ width: '100%', aspectRatio: '1', background: 'var(--surface-2)', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {p.src ? <img src={p.src} alt={p.menu} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} /> : <i className={p.hasVideo ? 'ti ti-video' : 'ti ti-photo'} style={{ fontSize: 24, color: 'var(--text-muted)' }}></i>}
                  {p.mediaCount > 1 && <span style={{ position: 'absolute', right: 8, top: 8, font: 'var(--text-micro)', color: '#fff', background: 'rgba(26,26,26,.68)', borderRadius: 999, padding: '4px 8px' }}>1/{p.mediaCount}</span>}
                  <span style={{ position: 'absolute', left: 8, bottom: 8, font: 'var(--text-micro)', color: '#fff', background: 'rgba(26,26,26,.68)', borderRadius: 999, padding: '4px 8px' }}>#{p.menu}</span>
                </div>
                <div style={{ padding: '11px 12px 13px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5 }}>
                    <Avatar user={p.user} size={20} />
                    <span style={{ font: '600 13px/1.2 var(--font-family)', color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.user}</span>
                    {p.badges[0] && <i className={'ti ti-' + p.badges[0]} style={{ fontSize: 11, color: 'var(--text-accent)', flexShrink: 0 }}></i>}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 6 }}>
                    <i className={p.place ? 'ti ti-map-pin' : 'ti ti-map-pin-question'} style={{ fontSize: 11, color: p.place ? 'var(--text-secondary)' : 'var(--text-warning)', flexShrink: 0 }}></i>
                    <span style={{ font: 'var(--text-micro)', color: p.place ? 'var(--text-secondary)' : 'var(--text-warning)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.place || '장소 미지정'}</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ font: 'var(--text-micro)', color: 'var(--text-muted)', display: 'inline-flex', alignItems: 'center', gap: 3 }}><i className="ti ti-heart" style={{ fontSize: 10 }}></i>{p.likes}</span>
                    <span style={{ font: 'var(--text-micro)', color: 'var(--text-muted)' }}>{p.time}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div style={{ padding: '0 20px 104px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {tab === '맛집'
            ? results.map((r, i) => <RestaurantCard key={r.name} {...r} imageId={'sr-' + i} onClick={() => nav('restaurantDetail')} />)
            : users.map((u, i) => <UserRow key={u.name} u={u} following={!!follow[i]} onToggle={() => setFollow(f => ({ ...f, [i]: !f[i] }))} onClick={() => nav('userProfile', { name: u.name })} />)}
        </div>
      )}
      </div>
      {open && <PostViewer post={open} onClose={() => setOpen(null)} onComments={() => setOpen(null)} onMenu={() => { setMenuPost(open); setOpen(null); }} onPlace={() => { setOpen(null); nav('restaurantDetail'); }} />}
      {menuPost && <PostActionSheets post={menuPost} onClose={() => setMenuPost(null)} onDeleted={() => setMenuPost(null)} onEdit={(pp) => nav('editPost', { post: pp })} />}
      {filterOpen && <SearchFilterSheet tab={tab} init={active} onClose={() => setFilterOpen(false)} onApply={(v) => { tab === '맛집' ? setPf(v) : tab === '회원' ? setUf(v) : setGf(v); setFilterOpen(false); }} />}
    </div>
  );
}
window.Search = Search;
