package com.divyagkquiz.app.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.divyagkquiz.app.R
import com.divyagkquiz.app.viewmodel.QuizViewModel

class ProfileFragment : Fragment() {

    private val viewModel: QuizViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_profile, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val totalQuizzesText = view.findViewById<TextView>(R.id.total_quizzes)
        val totalScoreText = view.findViewById<TextView>(R.id.total_score)
        val badgesCountText = view.findViewById<TextView>(R.id.badges_count)

        val stats = viewModel.getCareerStats()
        totalQuizzesText.text = stats.first.toString()
        totalScoreText.text = stats.second.toString()
        
        // count how many categories have a best score of >= 80%
        val categories = listOf(
            "General Knowledge", "Science", "History", "Geography", 
            "Sports", "Current Affairs", "Technology", "Movies & TV", 
            "Literature", "Space", "Nature", "Art & Culture"
        )
        val allQuestions = viewModel.getCategoryCounts()
        var silverGoldCount = 0
        categories.forEach { cat ->
            val best = viewModel.getHighScore(cat)
            val totalInCat = allQuestions[cat] ?: 0
            if (totalInCat > 0) {
                val perc = (best.toFloat() / totalInCat) * 100
                if (perc >= 80) silverGoldCount++
            }
        }
        badgesCountText.text = silverGoldCount.toString()
    }
}
