package com.divyagkquiz.app.ui

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.divyagkquiz.app.data.QuizRepository
import com.divyagkquiz.app.data.Question
import com.divyagkquiz.app.R

class CategoryAdapter(
    private val categories: List<String>,
    private val onItemClick: (String) -> Unit
) : RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder>() {

    class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val cardView: MaterialCardView = itemView.findViewById(R.id.category_card)
        val categoryName: TextView = itemView.findViewById(R.id.category_name)
        val bestScoreText: TextView = itemView.findViewById(R.id.best_score_text)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_category, parent, false)
        return CategoryViewHolder(view)
    }

    override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
        val category = categories[position]
        holder.categoryName.text = category
        
        // Show High Score from SharedPreferences
        val prefs = holder.itemView.context.getSharedPreferences("gk_master_prefs", Context.MODE_PRIVATE)
        val highScore = prefs.getInt("high_score_$category", 0)
        
        if (highScore > 0) {
            val repository = QuizRepository(holder.itemView.context)
            val allQuestions = repository.getQuestions()
            val categoryTotal = allQuestions.count { it.category == category }
            val denominator = minOf(categoryTotal, 10)
            holder.bestScoreText.text = "Best: $highScore/$denominator"
        } else {
            holder.bestScoreText.text = "Not played yet"
        }
        
        holder.cardView.setOnClickListener { onItemClick(category) }
    }

    override fun getItemCount() = categories.size
}
