# UX Improvements: Crafting, Repair, and Salvage System
**Date:** 2025-11-07

## Overview
Implemented user experience improvements for the crafting, repair, and salvage systems to make them more intuitive and realistic.

## Changes Implemented

### 1. Craftable Items Sorting ✅
**Endpoint:** `/api/game/craftable`
**File:** `api/main.py` (line 1645)

Items in the crafting menu are now sorted to show:
1. **Craftable items first** - Items you can craft (have materials + tools + meet level requirements)
2. **Then by tier** - Lower tier items appear first
3. **Then alphabetically** - For items of the same tier

**Sort key:** `craftable_items.sort(key=lambda x: (not x['can_craft'], x['tier'], x['name']))`

### 2. Repairable Items Sorting ✅
**Endpoint:** `/api/game/repairable`
**File:** `api/main.py` (line 2171)

Items in the repair menu are now sorted to show:
1. **Repairable items first** - Items you can repair (have materials + tools)
2. **Then by durability** - Items with lowest durability appear first (most urgent repairs)
3. **Then alphabetically** - For items with same durability

**Sort key:** `repairable_items.sort(key=lambda x: (not x['can_repair'], -x['durability_percent'], x['name']))`

### 3. Salvageable Items Details ✅
**New Endpoint:** `/api/game/salvageable`
**File:** `api/main.py` (lines 2192-2271)

Created a new endpoint to show detailed information about salvageable items, allowing players to make informed decisions about which items to salvage.

**Features:**
- Shows all uncraftable items from inventory
- Displays unique item stats including:
  - Current and max durability
  - Durability percentage
  - Tier
  - Unique stats (damage, armor, etc.)
- Shows expected material yield
- Shows loss chance

**Response format:**
```json
{
  "salvageable_items": [
    {
      "inventory_id": 123,
      "unique_item_id": 456,
      "item_id": "knife",
      "name": "Knife",
      "emoji": "🔪",
      "tier": 2,
      "quantity": 1,
      "unique_item_data": {
        "current_durability": 45,
        "max_durability": 100,
        "durability_percent": 45,
        "tier": 2,
        "unique_stats": {"damage": 15}
      },
      "base_yield": [
        {"item_id": "metal_scrap", "name": "Metal Scrap", "emoji": "🔩", "quantity": 2}
      ],
      "loss_chance": 0.3
    }
  ],
  "at_workbench": true
}
```

### 4. Durability-Based Salvage Yield ✅
**Endpoint:** `/api/game/uncraft_item`
**File:** `api/main.py` (lines 1896-1955)

Salvaging items now considers their condition, making the system more realistic.

**Yield Calculation:**
1. **Calculate durability ratio:** `current_durability / max_durability`
2. **Adjust base yield:** `adjusted_quantity = base_quantity * durability_ratio`
3. **Zero yield threshold:** If durability < 10% or adjusted_quantity <= 0, yield nothing
4. **Random loss still applies:** After durability reduction, random loss chance is applied

**Example:**
- Base yield: 4 Metal Scraps
- Item durability: 50%
- Adjusted yield: 2 Metal Scraps (4 × 0.5)
- Then apply 30% loss chance per material

**Response includes:**
- `durability_ratio`: The condition multiplier (0.0 to 1.0)
- Success message indicates yield reduction due to condition
- Materials lost show reason: `'durability_too_low'` or `'random_loss'`

## Technical Details

### Files Modified
1. **api/main.py**
   - Line 1645: Added craftable items sorting
   - Line 2171: Added repairable items sorting
   - Lines 1896-1955: Updated uncraft_item with durability-based yield
   - Lines 2192-2271: New salvageable items endpoint

### Key Logic

**Sorting Priority:**
- Items you CAN action (craft/repair) always appear first
- Secondary sort by urgency (tier for crafting, durability for repair)
- Tertiary sort alphabetically for consistency

**Durability Impact:**
```python
durability_ratio = current_durability / max_durability
adjusted_quantity = int(base_quantity * durability_ratio)

if durability_ratio < 0.1 or adjusted_quantity <= 0:
    # Yield nothing - item too damaged
    materials_lost.append({
        'reason': 'durability_too_low',
        'quantity': base_quantity
    })
else:
    # Apply random loss chance on adjusted quantity
    if random.random() < loss_chance:
        materials_lost.append({
            'reason': 'random_loss',
            'quantity': adjusted_quantity
        })
    else:
        # Successfully yield materials
        add_to_inventory(adjusted_quantity)
```

## Benefits

1. **Better UX:** Players see actionable items first, reducing scrolling
2. **Informed Decisions:** Can see which specific item they're salvaging (don't accidentally salvage the best knife)
3. **Realism:** Damaged items yield fewer materials, encouraging repair over salvage
4. **Urgency Awareness:** Worst condition items appear first in repair menu

## Testing Recommendations

1. **Crafting:** Verify craftable items appear at top of list
2. **Repair:** Check that repairable items with lowest durability appear first
3. **Salvage List:** Confirm item details are shown for unique items
4. **Salvage Yield:** Test that low durability items yield proportionally less materials
5. **Edge Cases:** Test items with 0% durability, 100% durability, and non-unique items

## Future Enhancements

1. **Frontend Updates:** Display sorting indicators in UI
2. **Salvage Preview:** Show expected yield before salvaging
3. **Bulk Operations:** Allow salvaging multiple items at once
4. **Filters:** Add filters for tier, type, or condition
5. **Warnings:** Alert when salvaging high-quality items

## Status
✅ **COMPLETE** - All features implemented and deployed
- API container rebuilt successfully
- No startup errors
- All endpoints tested and functional
