<?php

/**
 * 文件功能：前台用户成就展示控制器。
 *
 * 展示当前登录用户的成就分类、解锁状态和进度。
 */

namespace App\Http\Controllers;

use App\Services\AchievementService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

/**
 * 类功能：提供“我的成就”页面数据。
 */
class AchievementController extends Controller
{
    /**
     * 创建成就控制器依赖。
     */
    public function __construct(
        private readonly AchievementService $achievementService,
    ) {}

    /**
     * 展示当前登录用户的成就总览。
     */
    public function index(Request $request): View
    {
        $user = Auth::user();
        $this->achievementService->scanUser($user);
        $achievementData = $this->achievementService->displayForUser($user);
        $activeTab = in_array($request->query('status'), ['unlocked', 'locked'], true)
            ? $request->query('status')
            : 'all';
        $allAchievements = $achievementData['achievements'];

        // 页面 tab 只影响展示列表，不影响顶部总进度统计。
        $achievementTabs = [
            'all' => [
                'label' => '全部',
                'count' => $allAchievements->count(),
                'url' => route('achievements.index'),
            ],
            'unlocked' => [
                'label' => '已完成',
                'count' => $allAchievements->where('unlocked', true)->count(),
                'url' => route('achievements.index', ['status' => 'unlocked']),
            ],
            'locked' => [
                'label' => '未达成',
                'count' => $allAchievements->where('unlocked', false)->count(),
                'url' => route('achievements.index', ['status' => 'locked']),
            ],
        ];

        $achievementData['achievements'] = match ($activeTab) {
            'unlocked' => $allAchievements->where('unlocked', true)->values(),
            'locked' => $allAchievements->where('unlocked', false)->values(),
            default => $allAchievements,
        };

        return view('achievements.index', [
            'user' => $user,
            'active_tab' => $activeTab,
            'achievement_tabs' => $achievementTabs,
            ...$achievementData,
        ]);
    }
}
