"use client";
import React, { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "../../hooks/hooks";
import { setFirstPostImage } from "../../store/Slice/SecondUserFirstPostImage";
import { useGetMyAllPostQuery } from "../../store/api/GetMyAllPost";
import Cookies from "js-cookie";
import MyPost from "./MyPost";
import SecondUserAllPost from "./SecondUserAllPost";

function Post() {
  // Logic updated to use viewedUser state
  const isOwnProfile = useAppSelector((state) => state.viewedUser.isOwnProfile);
  const dispatch = useAppDispatch();
  
  const token = Cookies.get("Snapta_auth_token");
  const { data: MyPostData } = useGetMyAllPostQuery({ token: token || "" });

  // Correcting the logic to handle first post image dispatch
  useEffect(() => {
    // If we are looking at "My Profile", get first image from MyPostData
    if (isOwnProfile && MyPostData?.post?.[0]?.image?.[0]?.url) {
      dispatch(setFirstPostImage(MyPostData.post[0].image[0].url));
    }
  }, [isOwnProfile, MyPostData, dispatch]);

  return (
    <div className="w-full flex justify-center">
      {/* Render based on isOwnProfile flag */}
      {isOwnProfile ? (
        <MyPost />
      ) : (
        <SecondUserAllPost />
      )}
    </div>
  );
}

export default Post;