package com.example.myapplication.ui.shop

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R
import kotlinx.coroutines.launch

class ShopStylePageFragment : Fragment(R.layout.fragment_shop_style_page) {

    private var styleId: Int = 0
    private lateinit var rv: RecyclerView
    private val adapter = ThemeCardAdapter()

    // ✅ 拿到父 ShopFragment 的同一个 VM（关键）
    private val vm: ShopViewModel by viewModels({ requireParentFragment() })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        styleId = arguments?.getInt(ARG_STYLE_ID) ?: 0
    }

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

        rv = view.findViewById(R.id.recyclerView)
        rv.layoutManager = GridLayoutManager(requireContext(), 2)
        rv.adapter = adapter

        // 1) 进来就请求一次（有缓存会自动跳过）
        vm.loadStyleIfNeeded(styleId)

        // 2) 观察数据：数据一更新就刷新，永远不会漏
        viewLifecycleOwner.lifecycleScope.launch {
            vm.styleData.collect { map ->
                val list = map[styleId].orEmpty()
                Log.d("1314520-StylePage", "collect styleId=$styleId size=${list.size}")
                adapter.submitList(list)
            }
        }
    }

    companion object {
        private const val ARG_STYLE_ID = "style_id"

        fun newInstance(styleId: Int) = ShopStylePageFragment().apply {
            arguments = Bundle().apply { putInt(ARG_STYLE_ID, styleId) }
        }
    }
}
