// ─────────────────────────────────────────────────────────────
// Search — flat results view that replaces Ladder/Rings while
// the search query is non-empty.
//
// Surfaces three buckets:
//   1. Folk in your roster (any stage)
//   2. Folk you have a pending proposal to (filter applies)
//   3. Other folk in your forests — people you've seen but not staged
// ─────────────────────────────────────────────────────────────

function SearchBar({ value, onChange, onFocus, onClear, autoFocus = false }) {
  const inputRef = React.useRef(null);
  React.useEffect(() => {
    if (autoFocus) inputRef.current?.focus();
  }, [autoFocus]);

  return (
    <div style={{ padding: '0 18px 10px', flexShrink: 0 }}>
      <div style={{
        height: 42, padding: '0 12px',
        background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <PIcons.Search size={16} color="#586552"/>
        <input
          ref={inputRef}
          value={value}
          onChange={e => onChange(e.target.value)}
          onFocus={onFocus}
          placeholder="Search folk in your forests"
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            font: '500 14px var(--font-sans)', color: '#F2EDE4',
          }}/>
        {value && (
          <button onClick={onClear} aria-label="Clear search"
            style={{
              background: 'transparent', border: 'none', padding: 4, color: '#586552',
              cursor: 'pointer', display: 'flex',
            }}>
            <PIcons.X size={16}/>
          </button>
        )}
      </div>
    </div>
  );
}


function SearchResults({ query, folk, proposals, onTapUser, onTapForestFolk,
                         onTapCanopyFolk, onTapTradeHandles }) {
  const q = query.trim().toLowerCase();
  const matchedFolk        = folk.filter(f => f.handle.toLowerCase().includes(q));
  const matchedForestFolk  = FOREST_FOLK.filter(f => f.handle.toLowerCase().includes(q));
  const matchedCanopyFolk  = ACROSS_CANOPY.filter(f => f.handle.toLowerCase().includes(q));
  const totalMatches = matchedFolk.length + matchedForestFolk.length + matchedCanopyFolk.length;

  return (
    <div style={{ padding: '4px 0 24px' }}>
      {totalMatches === 0 && <SearchEmpty query={query}/>}

      {/* In your roster */}
      {matchedFolk.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <SectionLabel>In your folk · {matchedFolk.length}</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8 }}>
            {matchedFolk.map(u => (
              <FlatFolkRow key={u.handle} user={u}
                proposed={proposals[u.handle]}
                onTap={() => onTapUser(u.handle)}/>
            ))}
          </div>
        </div>
      )}

      {/* In your forests but not yet staged */}
      {matchedForestFolk.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <SectionLabel>In your forests · {matchedForestFolk.length}</SectionLabel>
          <div style={{ font: 'italic 400 12px var(--font-serif)',
                        color: '#586552', marginTop: 2, marginBottom: 8 }}>
            People you've seen around but haven't met yet.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {matchedForestFolk.map(u => (
              <ForestFolkRow key={u.handle} user={u}
                onTap={() => onTapForestFolk(u)}/>
            ))}
          </div>
        </div>
      )}

      {/* Across the canopy — no overlap at all. Privacy-light. */}
      {matchedCanopyFolk.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <SectionLabel>Across the canopy · {matchedCanopyFolk.length}</SectionLabel>
          <div style={{ font: 'italic 400 12px var(--font-serif)',
                        color: '#586552', marginTop: 2, marginBottom: 8 }}>
            No overlap with you yet. They need to accept before any details show.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {matchedCanopyFolk.map(u => (
              <CanopyFolkRow key={u.handle} user={u}
                onTap={() => onTapCanopyFolk(u)}/>
            ))}
          </div>
        </div>
      )}

      {/* Trade handles tile — always at the bottom of search results so it's
          a stable destination for "I just met someone, search isn't finding them". */}
      <div style={{ padding: '4px 18px 0' }}>
        <button onClick={onTapTradeHandles}
          style={{
            width: '100%',
            background: '#111D0A', border: '0.5px solid #2D3A22',
            borderRadius: 12, padding: '12px 14px',
            display: 'flex', alignItems: 'center', gap: 12,
            cursor: 'pointer', textAlign: 'left',
          }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: '#3A2A07', border: '0.5px solid #6B5018',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <PIcons.Handshake size={18} color="#F4DCA0"/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ font: '500 14px var(--font-sans)', color: '#F2EDE4' }}>
              Trade handles in person
            </div>
            <div style={{ font: 'italic 400 12px var(--font-serif)', color: '#8A9678', marginTop: 2 }}>
              For when search isn't the right tool — share yours, take theirs.
            </div>
          </div>
          <PIcons.ChevronRight size={16} color="#586552"/>
        </button>
      </div>
    </div>
  );
}


function SearchEmpty({ query }) {
  return (
    <div style={{
      padding: '40px 32px 8px', textAlign: 'center',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: '#111D0A', border: '0.5px solid #2D3A22',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <PIcons.Search size={22} color="#586552"/>
      </div>
      <div style={{ font: '500 15px var(--font-mono)', color: '#C9D2BB' }}>
        No one named “{query}”.
      </div>
      <div style={{ font: 'italic 400 13px/1.55 var(--font-serif)', color: '#8A9678',
                    maxWidth: 260 }}>
        Try a partial handle, or trade handles in person below.
      </div>
    </div>
  );
}


function SectionLabel({ children }) {
  return (
    <div style={{
      font: '500 10.5px var(--font-sans)', color: '#76AB78',
      letterSpacing: '0.12em', textTransform: 'uppercase',
    }}>{children}</div>
  );
}


// A roster folk row — flat, no ladder rail
function FlatFolkRow({ user, proposed, onTap }) {
  const meta = STAGE_META[user.stage];
  return (
    <button onClick={onTap} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px',
      background: '#111D0A', border: '0.5px solid #1F2B16', borderRadius: 10,
      width: '100%', cursor: 'pointer', textAlign: 'left',
    }}>
      <FolkAvatar user={user} size={32} online={user.online}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ font: '500 14px var(--font-mono)', color: '#F2EDE4' }}>{user.handle}</span>
          {proposed && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 3,
              padding: '1px 6px', borderRadius: 999,
              background: 'rgba(212,150,12,0.10)',
              border: '0.5px solid rgba(212,150,12,0.45)',
              color: '#F4DCA0',
              font: '500 9.5px var(--font-sans)',
              letterSpacing: '0.04em', textTransform: 'uppercase',
            }}>
              <PIcons.ArrowUpRight size={9} color="#F4DCA0"/> Proposed
            </span>
          )}
        </div>
        <div style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678', marginTop: 2 }}>
          {user.mutuals} {user.mutuals === 1 ? 'forest' : 'forests'} · {user.lastTouch}
        </div>
      </div>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '3px 8px', borderRadius: 999,
        background: meta.soft,
        font: '500 10.5px var(--font-sans)', color: meta.accent,
        letterSpacing: '0.04em', textTransform: 'uppercase',
      }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: meta.accent }}/>
        {meta.label}
      </span>
    </button>
  );
}


// A forest-folk row — no stage yet, dotted border to signal that
function ForestFolkRow({ user, onTap }) {
  return (
    <button onClick={onTap} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px',
      background: 'transparent',
      border: '0.5px dashed #2D3A22', borderRadius: 10,
      width: '100%', cursor: 'pointer', textAlign: 'left',
    }}>
      <FolkAvatar user={user} size={30}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <span style={{ font: '500 14px var(--font-mono)', color: '#C9D2BB' }}>{user.handle}</span>
        <div style={{ font: 'italic 400 11.5px var(--font-serif)', color: '#586552', marginTop: 2 }}>
          seen in {user.appearsIn}
        </div>
      </div>
      <span style={{
        font: '500 10.5px var(--font-sans)', color: '#586552',
        letterSpacing: '0.04em', textTransform: 'uppercase',
      }}>
        Stranger
      </span>
    </button>
  );
}


// A canopy-folk row — across the network, no shared context.
// Visually quieter than forest-folk: gradient avatar is muted, location
// hint is intentionally generic.
function CanopyFolkRow({ user, onTap }) {
  return (
    <button onClick={onTap} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px',
      background: 'transparent',
      border: '0.5px solid #1F2B16', borderRadius: 10,
      width: '100%', cursor: 'pointer', textAlign: 'left',
    }}>
      <div style={{ opacity: 0.7 }}>
        <FolkAvatar user={user} size={30}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <span style={{ font: '500 14px var(--font-mono)', color: '#C9D2BB' }}>{user.handle}</span>
        <div style={{ font: 'italic 400 11.5px var(--font-serif)', color: '#586552', marginTop: 2 }}>
          {user.whereabouts}
        </div>
      </div>
      <PIcons.ChevronRight size={16} color="#586552"/>
    </button>
  );
}


window.SearchBar = SearchBar;
window.SearchResults = SearchResults;
