"use client";

import "react-multi-carousel/lib/styles.css";
import { HOME_CONTENT_WIDTH_CLASS } from "./homeCarouselLayout";
import { useTranslation } from "react-i18next";
import Title from "@/components/shared/Title";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import apiClient from "@/lib/api/client";
import CommunityCard from "./CommunityCard";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import { useState } from "react";
import type { CommunityPost } from "@/features/home/types";

interface VolunteerContributionsProps {
  /** Pre-fetched posts from the server (optional — client fetches if absent) */
  initialPosts?: CommunityPost[];
}

export default function VolunteerContributions({
  initialPosts = [],
}: VolunteerContributionsProps) {
  const { t } = useTranslation();
  const [navigationVisibility, setNavigationVisibility] = useState(false);

  // Client-side query initialised with server data — no extra network call on mount
  const { data: postsData, refetch, isError, error } = useQuery({
    queryKey: ["community-posts-homepage"],
    queryFn: async () => {
      const { data } = await apiClient.get("/posts/", {
        params: { page: 1, limit: 6 },
      });
      return data;
    },
    // Only a non-empty server list is seeded: `initialData` counts as fresh for
    // `staleTime`, so seeding [] would pin the section empty for two minutes.
    initialData: initialPosts.length > 0 ? { data: initialPosts } : undefined,
    staleTime: 2 * 60 * 1000, // treat server data as fresh for 2 min
  });

  return (
    <div className="bg-[#1A1A66] home-section-spacing relative volunteercontributions dotlist">
      <div className={`${HOME_CONTENT_WIDTH_CLASS} mx-auto relative`}>
        {/* Heading */}
        <div className="flex justify-between items-center home-section-heading-gap 2xl:px-5 px-3 mobilescreen:px-[13px]">
          <h2>
            <Title
              text={t("COMMON.FORSA.COMMUNITY-")}
              variant="white"
              hasMargin={false}
            />
          </h2>

          {navigationVisibility && (
            <Link
              href="/Community-List"
              className="text-white font-bold lg:text-lg md:text-lg text-base 2xl:text-xl"
              aria-label={t("COMMON.SHOW_ALL_COMMUNITY_POSTS")}
            >
              {t("COMMON.SHOW.ALL")}
            </Link>
          )}
        </div>
        {/* A failed load is not "no posts" (p.37): say so and offer a retry. */}
        {isError && !postsData ? (
          <div className="rounded-xl bg-white px-4">
            <QueryErrorNotice error={error} onRetry={() => void refetch()} />
          </div>
        ) : (
          <CommunityCard
            posts={postsData?.data || []}
            onNavigationVisibilityChange={(isVisible) =>
              setNavigationVisibility(isVisible)
            }
            refetch={refetch}
          />
        )}
      </div>
    </div>
  );
}
