"use client";

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

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

export default function OrganizerProfile() {
  const authToken = useAuthStore((s) => s.user?.auth_token);

  const profileQuery = useQuery({
    queryKey: ["organizer-profile"],
    queryFn: getOrganizerProfile,
    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 />;
  // A failed load must not render as an empty organization profile.
  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 = profileQuery.data?.data;
  const accountInfoData = accountQuery.data;

  // Teams and organizations share the redesigned profile; an organization adds
  // sponsorships and the «منظم / راعي» switch (2026-10-15).
  return (
    <IndividualProfileView
      profile={
        profile?.is_volunteer_team
          ? fromOwnTeamProfile(profile, accountInfoData?.data)
          : fromOwnOrganizationProfile(profile, accountInfoData?.data)
      }
      isOwnProfile
    />
  );
}
