package com.kbs.kbsintranett;

import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import com.bumptech.glide.Glide;

public class NewsDetailFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Hent data fra argumentene (sendt fra HomeFragment/NewsFullFragment)
        if (getArguments() != null) {
            WpPost post = (WpPost) getArguments().getSerializable("post_data");
            if (post != null) {
                setupViews(view, post);
            }
        }
    }

    private void setupViews(View view, WpPost post) {
        Toolbar toolbar = view.findViewById(R.id.detail_toolbar);
        toolbar.setNavigationOnClickListener(v -> Navigation.findNavController(view).navigateUp());

        ImageView image = view.findViewById(R.id.detail_image);
        TextView title = view.findViewById(R.id.detail_title);
        TextView category = view.findViewById(R.id.detail_category);
        TextView date = view.findViewById(R.id.detail_date);
        TextView author = view.findViewById(R.id.detail_author); // NY
        TextView content = view.findViewById(R.id.detail_content);

        String imgUrl = post.getFeaturedImageUrl();
        if (imgUrl != null) {
            Glide.with(this).load(imgUrl).centerCrop().into(image);
        } else {
            image.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
        }

        title.setText(post.getTitleStr());
        category.setText(post.getCategoryName());
        date.setText("Publisert: " + post.date);

        // NYTT: Sett forfatter
        author.setText("Av: " + post.getAuthorName());

        content.setText(Html.fromHtml(post.getContentStr(), Html.FROM_HTML_MODE_COMPACT));
        content.setMovementMethod(LinkMovementMethod.getInstance());
    }
}