# MainBrowseTagCategories Search Logic Reference

## Overview

The MainBrowseTagCategories component (`app/Http/Livewire/MainBrowseTagCategories.php`) provides category-based search functionality, allowing users to browse and filter content by selecting tag categories. Unlike the text-based MainSearchBar, this component focuses on hierarchical category filtering with sophisticated location-based prioritization.

## Search Flow Workflow

### 1. Category Selection (`selectCategory()`, `removeCategory()`)
- **Toggle Selection**: Categories can be selected/deselected
- **Hierarchical Inclusion**: Child categories automatically included when parent selected
- **Validation**: Category ID validation ensures data integrity
- **Automatic Search**: Triggers search immediately upon selection change

### 2. Search Execution (`performSearch()` → `searchByCategories()`)
- **Empty State**: No categories = empty results
- **Category Expansion**: Selected categories expanded to include all children
- **Name Resolution**: Category IDs converted to localized names
- **Elasticsearch Query**: Advanced query construction and execution

### 3. Query Construction (`buildElasticsearchQuery()`)

#### Category Matching Strategy
- **Primary Field**: `tags.contexts.categories.name_{locale}`
- **Exact Match**: 2x category boost from config
- **Fuzzy Match**: 1x category boost with configurable fuzziness
- **Minimum Match**: At least one category must match

#### Model Filtering
- **Source Selection**: Only `id`, `__class_name`, and `_score` returned
- **Index Targeting**: Uses same indices as MainSearchBar
- **Result Limit**: 1.5x max_results for better selection pool

## Result Prioritization System

### 1. Location-Based Boosting (`addLocationBoosts()`)
Same hierarchy as MainSearchBar but applied to category searches:

#### Proximity Levels (best to worst)
1. **same_district**: 5.0x boost (2.5x final multiplier)
2. **same_city**: 3.0x boost (2.0x final multiplier)
3. **same_division**: 2.0x boost (1.5x final multiplier)
4. **same_country**: 1.5x boost (1.2x final multiplier)
5. **different_country**: 1.0x boost (neutral)
6. **no_location**: 0.9x penalty

### 2. Model-Type Prioritization (`sortAndLimitResults()`)
Applied during final processing using config values:
- **Posts**: 4x boost (highest priority)
- **Organizations**: 3x boost
- **Banks**: 3x boost
- **Users**: 1x boost (baseline)

### 3. Dual-Sort Strategy
Results sorted by:
1. **Primary**: Location proximity (distance ascending - closer first)
2. **Secondary**: Combined score (score descending - higher first)

### 4. Category Match Quality
- **Exact category name matches**: 2x boost over fuzzy matches
- **Parent category selection**: Includes all child categories in search
- **Localized matching**: Uses current locale for category names

## Profile and Content Filtering

### 1. Profile Filtering (`filterProfile()`)
Same business rules as MainSearchBar:
- **Inactive profiles**: Hidden based on config (`profile_inactive.profile_search_hidden`)
- **Unverified emails**: Hidden based on config (`profile_email_unverified.profile_search_hidden`)
- **Incomplete profiles**: Hidden based on config (`profile_incomplete.profile_search_hidden`)
- **Deleted profiles**: Always hidden (hard-coded)
- **Admin override**: Can see all profiles regardless of status

### 2. Post Filtering
- **Category restrictions**: Only posts from configured category IDs
- **Publication status**: Respects from/till/deleted_at dates
- **Translation requirements**: Must have translation for current locale

## Output Processing and Display

### 1. Result Caching (`showCategoryResults()`)
- **Cache key**: Same as MainSearchBar (`main_search_bar_results_{user_id}`)
- **Cache duration**: 5 minutes (configurable)
- **Search term**: Built from selected category names
- **Compatibility**: Uses same format as search/show component

### 2. Data Transformation (`transformModelToResult()`)

#### Profile Data
- **Basic info**: Name, photo, type classification
- **Location formatting**: City, division display
- **Relationship loading**: Eager loading for performance

#### Post Data  
- **Content**: Title, subtitle, category information
- **Media**: Hero image extraction
- **Metadata**: Category ID and localized name

### 3. Search Results Display
Results displayed using the same `livewire/search/show` component as MainSearchBar:
- **Profile cards**: Standard profile layout with skills, reactions
- **Post cards**: Event-style cards with images and details
- **Highlighting**: Category-focused highlighting
- **Pagination**: 15 results per page

## Category Hierarchy System

### 1. Hierarchy Loading (`loadTagCategories()`)
- **Caching**: 1-hour cache per locale
- **Translation support**: Current locale translations preferred
- **Tree building**: Recursive parent-child relationship construction

### 2. Category Expansion (`expandCategoryIds()`)
- **Child inclusion**: All descendant categories included automatically
- **Recursive traversal**: Deep hierarchy navigation
- **Deduplication**: Unique category list maintained

### 3. UI Interaction
- **Accordion interface**: Collapsible category browser
- **Single expansion**: Only one parent category open at a time
- **Visual selection**: Selected categories highlighted with rings
- **Remove function**: Easy category deselection

## Highlighting and Display

### 1. Highlight Configuration
- **Target fields**: Category names, profile fields, post content
- **Fragment size**: 50 characters (smaller than MainSearchBar)
- **Priority extraction**: Category fields prioritized over content

### 2. Best Highlight Selection (`extractBestHighlight()`)
Priority order for highlights:
1. Category names (highest priority for category search)
2. Profile names
3. About sections
4. Post titles

## Performance Optimizations

### 1. Caching Strategy
- **Category hierarchy**: 1-hour cache
- **Category names**: 5-minute cache
- **Descendants**: 1-hour cache per category
- **Results**: 5-minute cache (shared with MainSearchBar)

### 2. Query Optimizations
- **Minimal source**: Only essential fields returned
- **Batch processing**: Efficient model loading
- **Eager loading**: Preload necessary relationships

### 3. Analytics Integration
- **Search tracking**: When SearchOptimizationHelper available
- **Performance metrics**: Execution time tracking
- **Location analytics**: Geographic search pattern analysis

## Configuration Impact

### Key Config Sections (`config/timebank-cc.php`)

#### Category Boosting
- `main_search_bar.boosted_fields.categories`: Category field importance
- Fuzziness settings for approximate matching

#### Model Prioritization  
- `main_search_bar.boosted_models`: Same model priority as text search

#### Location Boosting
- Same geographic prioritization as MainSearchBar
- Applied consistently across search methods

#### Filtering Rules
- Profile visibility settings
- Post category inclusion lists
- Business rule configurations

## Search Analytics and Debugging

### 1. Comprehensive Logging
- Query construction details
- Result processing steps
- Performance metrics
- Error handling

### 2. Debug Information
- Selected categories tracked
- Location hierarchy applied
- Model type distribution
- Score calculations

This category-based search system provides a structured alternative to text search, emphasizing geographic relevance and category-specific content discovery while maintaining consistency with the broader search ecosystem.