"use client";
import { useState, useEffect } from "react";
import ItemTitle from "./ItemTitle";
import { request } from "@/services/response";

function Title({ onTagChange }) {
  const [activeBtn, setActiveBtn] = useState(0);
  const [tags, setTags] = useState([]);

  useEffect(() => {
    const fetchTags = async () => {
      try {
        // Blog tags are stored as names on each blog; build the chip list from
        // the tag names actually present in published blogs.
        const response = await request.getBlogs({ page: 1, limit: 50 });
        const names = (response?.data || []).flatMap((b) =>
          Array.isArray(b.tags) ? b.tags : []
        );
        const uniqueNames = [...new Set(names)];
        setTags(uniqueNames.map((name) => ({ name })));
      } catch (error) {
        console.error("Error fetching tags:", error);
        setTags([]);
      }
    };

    fetchTags();
  }, []);

  const handleTagClick = (idx, tagName) => {
    setActiveBtn(idx);
    if (onTagChange) {
      onTagChange(tagName);
    }
  };

  return (
    <ul className="flex w-full overflow-auto hidden-scroll items-center justify-start gap-[8px] sm:gap-[10px] md:gap-[13px] lg:gap-[16px]">
      <ItemTitle
        setActiveBtn={() => handleTagClick(0, null)}
        activeBtn={activeBtn}
        name="همه"
        idx={0}
        key="all"
      />
      {tags.map((tag, idx) => (
        <ItemTitle
          setActiveBtn={() => handleTagClick(idx + 1, tag.name)}
          activeBtn={activeBtn}
          name={tag.name}
          idx={idx + 1}
          key={tag.name}
        />
      ))}
    </ul>
  );
}

export default Title;
