package com.wall.engine.wallpaper;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.wall.engine.wallpaper.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class HomeFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        TabLayout innerTabLayout = view.findViewById(R.id.innerTabLayout);
        ViewPager2 innerViewPager = view.findViewById(R.id.innerViewPager);

        InnerTabAdapter innerTabAdapter = new InnerTabAdapter(requireActivity());
        innerViewPager.setAdapter(innerTabAdapter);

        new TabLayoutMediator(innerTabLayout, innerViewPager, (tab, position) -> {
            View tabView = inflater.inflate(R.layout.custom_tab_item, null);
            TextView tabText = tabView.findViewById(R.id.tab_text);
            switch (position) {
                case 0: tabText.setText("Animals"); break;
                case 1: tabText.setText("Nature"); break;
                case 2: tabText.setText("Experimental"); break;
            }
            tab.setCustomView(tabView);

            // 强制Tab宽度填满父布局（关键！）
            ViewGroup.LayoutParams params = tabView.getLayoutParams();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
            tabView.setLayoutParams(params);
        }).attach();

        innerTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tabText = tab.getCustomView().findViewById(R.id.tab_text);
                tabText.setTextColor(getResources().getColor(android.R.color.white));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tabText = tab.getCustomView().findViewById(R.id.tab_text);
                tabText.setTextColor(getResources().getColor(android.R.color.black));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        innerTabLayout.selectTab(innerTabLayout.getTabAt(0));
        return view;
    }
}