package com.example.myapplication.ui.home

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.myapplication.R
import com.example.myapplication.network.listByTagWithNotLogin
import com.example.myapplication.network.PersonaClick
import de.hdodenhof.circleimageview.CircleImageView
import android.util.Log

class PersonaAdapter(
    private val onClick: (PersonaClick) -> Unit
) : RecyclerView.Adapter<PersonaAdapter.VH>() {

    private val items = mutableListOf<listByTagWithNotLogin>()

    fun submitList(list: List<listByTagWithNotLogin>) {
        items.clear()
        items.addAll(list)
        notifyDataSetChanged()
    }

    inner class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val ivAvatar: CircleImageView = itemView.findViewById(R.id.ivAvatar)
        val tvName: TextView = itemView.findViewById(R.id.tvName)
        val characterBackground: TextView =
            itemView.findViewById(R.id.characterBackground)
        val download: TextView = itemView.findViewById(R.id.download)
        val operation: TextView = itemView.findViewById(R.id.operation)

        /** ✅ 统一绑定 + 点击逻辑 */
        fun bind(item: listByTagWithNotLogin) {

            tvName.text = item.characterName
            characterBackground.text = item.characterBackground
            download.text = item.download
    
            Glide.with(itemView.context)
                .load(item.avatarUrl)
                .placeholder(R.drawable.default_avatar)
                .error(R.drawable.default_avatar)
                .into(ivAvatar)
    
            // ✅ 整个 item：跳详情
            itemView.setOnClickListener {
                onClick(PersonaClick.Item(item))
            }
    
            // ✅ 添加 / 下载按钮
            operation.setOnClickListener {
                onClick(PersonaClick.Add(item))
            }
        }
    }

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

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount(): Int = items.size
}
