package com.example.defenseapplication.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.example.defenseapplication.R import com.example.defenseapplication.databinding.ItemSwitchFamilyBinding import com.example.defenseapplication.model.FamilyItem class FamilySwitchAdapter( private var familyList: List, private val onItemClickListener: (FamilyItem) -> Unit ) : RecyclerView.Adapter() { private var selectedPosition = 0 fun updateList(newList: List) { familyList = newList selectedPosition = 0 notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FamilyViewHolder { val binding = ItemSwitchFamilyBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return FamilyViewHolder(binding) } override fun onBindViewHolder(holder: FamilyViewHolder, position: Int) { holder.bind(familyList[position], position == selectedPosition) } override fun getItemCount(): Int = familyList.size fun selectPosition(position: Int) { val previousPosition = selectedPosition selectedPosition = position notifyItemChanged(previousPosition) notifyItemChanged(selectedPosition) } fun getSelectedItem(): FamilyItem = familyList[selectedPosition] inner class FamilyViewHolder( private val binding: ItemSwitchFamilyBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(item: FamilyItem, isSelected: Boolean) { val displayName = if (item.role == "appadmin") { binding.root.context.getString(R.string.my_family_admin, item.name) } else { binding.root.context.getString(R.string.family_member, item.name) } binding.tvFamilyName.text = displayName binding.root.setBackgroundColor( ContextCompat.getColor( binding.root.context, if (isSelected) R.color.bg_gray else R.color.white ) ) binding.root.setOnClickListener { val position = bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { selectPosition(position) onItemClickListener(item) } } } } }