"use client";

import { useQuery } from "@tanstack/react-query";

import Loader from "@/components/ui/Loader";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import { getAccountInfo, getVolunteerProfile } from "@/features/profile/services/profileApi";
import { useAuthStore } from "@/store/authStore";
import IndividualProfileView from "./individual/IndividualProfileView";
import { fromOwnProfile } from "./individual/individualProfile";

/**
 * The signed-in volunteer's own profile. Identity and avatar come from
 * /account/, everything else from /volunteer-profile/; both are normalized
 * into the shape the redesigned view shares with the public profile.
 */
export default function VolunteerProfile() {
  const user = useAuthStore((s) => s.user);
  const authToken = user?.auth_token;

  const profileQuery =
    useQuery({
      queryKey: ["volunteer-profile"],
      queryFn: getVolunteerProfile,
      enabled: Boolean(authToken),
      refetchOnMount: "always",
    });

  const accountQuery = useQuery({
    queryKey: ["account-info"],
    queryFn: getAccountInfo,
    enabled: Boolean(authToken),
    refetchOnMount: "always",
  });

  if (profileQuery.isLoading || accountQuery.isLoading) return <Loader />;
  // Never render an empty profile (zero counters, no tabs data) for a failed load.
  const failed = profileQuery.isError ? profileQuery : accountQuery.isError ? accountQuery : null;
  if (failed) {
    return <QueryErrorNotice error={failed.error} onRetry={() => { void profileQuery.refetch(); void accountQuery.refetch(); }} />;
  }

  const profile = fromOwnProfile(
    profileQuery.data?.data,
    accountQuery.data?.data,
    user
  );

  return <IndividualProfileView profile={profile} isOwnProfile />;
}
