// components/profile/business-profile-content.tsx
"use client";

import { useEffect, useState, useCallback } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/lib/store/store";
import { PublicHeader } from "@/components/profile/public-header";
import { ProfileHeader } from "@/components/profile/profile-header";
import { ProfileTabs } from "@/components/profile/profile-tabs";
import {
  Building2,
  Users,
  Globe,
  Linkedin,
  Twitter,
  Mail,
  MapPin,
  Calendar,
  IndianRupee,
  Target,
  Briefcase,
  TrendingUp,
  Loader2,
  Award,
  Lightbulb,
  Activity,
  Instagram,
} from "lucide-react";
import { getBusinessProfile, getRecentActivity } from "@/lib/api/client";
import { toast } from "sonner";
import Image from "next/image";
import { useRouter } from "next/navigation";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

// Static tabs data (counts will be updated dynamically)
const tabs = [
  { id: "opportunities", label: "Opportunities", count: 0 },
  { id: "partnerships", label: "Partnerships", count: 0 },
  { id: "interested", label: "Interested Ideas", count: 0 },
  { id: "activity", label: "Activity" },
];

// Skeleton Components
function ProfileHeaderSkeleton() {
  return (
    <div className="relative bg-gradient-to-br from-primary/20 to-accent/20 rounded-2xl p-6 mb-4">
      <div className="flex flex-col md:flex-row gap-6">
        <div className="relative">
          <div className="w-24 h-24 rounded-full bg-muted animate-pulse"></div>
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <div className="h-8 w-40 bg-muted rounded animate-pulse"></div>
            <div className="h-5 w-16 bg-muted rounded animate-pulse"></div>
          </div>
          <div className="h-4 w-32 bg-muted rounded animate-pulse mb-4"></div>
          <div className="h-4 w-full max-w-md bg-muted rounded animate-pulse"></div>
          <div className="h-4 w-3/4 bg-muted rounded animate-pulse mt-2"></div>
          <div className="flex gap-6 mt-4">
            {[1, 2, 3].map((i) => (
              <div key={i}>
                <div className="h-5 w-12 bg-muted rounded animate-pulse mb-1"></div>
                <div className="h-4 w-8 bg-muted rounded animate-pulse"></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function CompanyOverviewSkeleton() {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <div className="h-5 w-32 bg-muted rounded animate-pulse mb-4"></div>
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <div key={i} className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-muted animate-pulse"></div>
            <div className="flex-1">
              <div className="h-3 w-20 bg-muted rounded animate-pulse mb-1"></div>
              <div className="h-4 w-32 bg-muted rounded animate-pulse"></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function LookingForSectionSkeleton() {
  return (
    <div className="bg-card rounded-xl border border-amber-500/20 bg-amber-500/5 p-5 mb-4">
      <div className="flex items-center gap-2 mb-3">
        <div className="h-4 w-4 bg-muted rounded animate-pulse"></div>
        <div className="h-5 w-32 bg-muted rounded animate-pulse"></div>
      </div>
      <div className="flex flex-wrap gap-2">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-6 w-20 bg-muted rounded-lg animate-pulse"></div>
        ))}
      </div>
    </div>
  );
}

function WhatWeOfferSectionSkeleton() {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <div className="h-5 w-32 bg-muted rounded animate-pulse mb-4"></div>
      <div className="space-y-3">
        {[1, 2].map((i) => (
          <div key={i} className="flex items-start gap-3">
            <div className="w-8 h-8 rounded-lg bg-muted animate-pulse"></div>
            <div className="flex-1">
              <div className="h-4 w-24 bg-muted rounded animate-pulse mb-1"></div>
              <div className="h-3 w-40 bg-muted rounded animate-pulse"></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function KeyPeopleSectionSkeleton() {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <div className="h-5 w-24 bg-muted rounded animate-pulse mb-4"></div>
      <div className="space-y-3">
        {[1, 2].map((i) => (
          <div key={i} className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-muted animate-pulse"></div>
            <div className="flex-1">
              <div className="h-4 w-28 bg-muted rounded animate-pulse mb-1"></div>
              <div className="h-3 w-20 bg-muted rounded animate-pulse"></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ContactSectionSkeleton() {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5">
      <div className="h-5 w-20 bg-muted rounded animate-pulse mb-3"></div>
      <div className="space-y-2">
        {[1, 2, 3].map((i) => (
          <div key={i} className="flex items-center gap-3 p-2">
            <div className="h-4 w-4 bg-muted rounded animate-pulse"></div>
            <div className="h-4 w-24 bg-muted rounded animate-pulse"></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RecentActivitySkeleton() {
  return (
    <div className="bg-card rounded-xl border border-border/50">
      <div className="p-4 border-b border-border/50">
        <div className="h-5 w-32 bg-muted rounded animate-pulse"></div>
      </div>
      <div className="p-8 text-center">
        <div className="animate-pulse space-y-4">
          <div className="bg-muted h-24 rounded-lg"></div>
          <div className="bg-muted h-24 rounded-lg"></div>
        </div>
      </div>
    </div>
  );
}

// Company Overview Section - DYNAMIC
function CompanyOverview({
  organization,
  location,
}: {
  organization: any;
  location: any;
}) {
  const hasData =
    organization?.industry ||
    organization?.type ||
    organization?.employeeCount ||
    organization?.foundedYear ||
    organization?.headquarters ||
    organization?.annualRevenue;

  if (!hasData) return null;

  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <h3 className="font-semibold text-foreground mb-4">Company Overview</h3>

      <div className="space-y-4">
        {organization?.type && (
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-amber-500/10 flex items-center justify-center shrink-0">
              <Building2 className="h-4 w-4 text-amber-500" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Business Type</p>
              <p className="text-sm font-medium text-foreground">
                {organization.type
                  .replace(/_/g, " ")
                  .replace(/\b\w/g, (l) => l.toUpperCase())}
              </p>
            </div>
          </div>
        )}

        {organization?.industry && (
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-amber-500/10 flex items-center justify-center shrink-0">
              <Building2 className="h-4 w-4 text-amber-500" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Industry</p>
              <p className="text-sm font-medium text-foreground">
                {organization.industry}
              </p>
            </div>
          </div>
        )}

        {organization?.employeeCount && (
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-secondary flex items-center justify-center shrink-0">
              <Users className="h-4 w-4 text-muted-foreground" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Company Size</p>
              <p className="text-sm font-medium text-foreground">
                {organization.employeeCount}
              </p>
            </div>
          </div>
        )}

        {organization?.foundedYear && (
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-secondary flex items-center justify-center shrink-0">
              <Calendar className="h-4 w-4 text-muted-foreground" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Founded</p>
              <p className="text-sm font-medium text-foreground">
                {organization.foundedYear}
              </p>
            </div>
          </div>
        )}

        {(organization?.headquarters ||
          (location?.city && location?.country)) && (
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-secondary flex items-center justify-center shrink-0">
              <MapPin className="h-4 w-4 text-muted-foreground" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Headquarters</p>
              <p className="text-sm font-medium text-foreground">
                {organization?.headquarters ||
                  [location?.city, location?.country]
                    .filter(Boolean)
                    .join(", ")}
              </p>
            </div>
          </div>
        )}

        {organization?.annualRevenue && (
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-secondary flex items-center justify-center shrink-0">
              <IndianRupee className="h-4 w-4 text-muted-foreground" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Annual Revenue</p>
              <p className="text-sm font-medium text-foreground">
                {organization.annualRevenue}
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// What We're Looking For - DYNAMIC (from postCategories)
function LookingForSection({ postCategories }: { postCategories: any[] }) {
  const categories =
    postCategories?.map((cat: any) =>
      typeof cat === "object" ? cat.mainCategoryName : cat,
    ) || [];

  if (categories.length === 0) return null;

  return (
    <div className="bg-card rounded-xl border border-amber-500/20 bg-amber-500/5 p-5 mb-4">
      <div className="flex items-center gap-2 mb-3">
        <Target className="h-4 w-4 text-amber-500" />
        <h3 className="font-semibold text-foreground">Looking For Ideas In</h3>
      </div>
      <div className="flex flex-wrap gap-2">
        {categories.map((item) => (
          <span
            key={item}
            className="px-2.5 py-1 rounded-lg bg-amber-500/10 text-xs text-amber-400 border border-amber-500/20"
          >
            {item}
          </span>
        ))}
      </div>
    </div>
  );
}

// What We Offer - DYNAMIC
function WhatWeOfferSection({ whatWeOffer }: { whatWeOffer: any[] }) {
  if (!whatWeOffer || whatWeOffer.length === 0) return null;

  const offerIcons = [
    IndianRupee,
    Briefcase,
    Users,
    TrendingUp,
    Award,
    Lightbulb,
  ];

  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <h3 className="font-semibold text-foreground mb-4">What We Offer</h3>
      <div className="space-y-3">
        {whatWeOffer.map((item, idx) => (
          <div key={idx} className="flex items-start gap-3">
            <div className="w-8 h-8 rounded-lg bg-emerald-500/10 flex items-center justify-center shrink-0">
              {(() => {
                const Icon = offerIcons[idx % offerIcons.length];
                return <Icon className="h-4 w-4 text-emerald-400" />;
              })()}
            </div>
            <div>
              <p className="text-sm font-medium text-foreground">
                {item.title}
              </p>
              {item.description && (
                <p className="text-xs text-muted-foreground">
                  {item.description}
                </p>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Key People - DYNAMIC
function KeyPeopleSection({ keyPeople }: { keyPeople: any[] }) {
  if (!keyPeople || keyPeople.length === 0) return null;

  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <h3 className="font-semibold text-foreground mb-4">Key People</h3>
      <div className="space-y-3">
        {keyPeople.map((person, idx) => (
          <div key={idx} className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-secondary flex items-center justify-center text-sm font-medium text-muted-foreground">
              {person.avatar || person.name?.charAt(0)?.toUpperCase() || "?"}
            </div>
            <div>
              <p className="text-sm font-medium text-foreground">
                {person.name}
              </p>
              <p className="text-xs text-muted-foreground">{person.role}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Contact Section - DYNAMIC (Social Links)
function ContactSection({
  socialMedia,
  email,
  website,
}: {
  socialMedia?: any[];
  email?: string;
  website?: string;
}) {
  // Get social links from the socialMedia array
  const linkedin = socialMedia?.find((s: any) => s.type === "linkedin")?.link;
  const twitter = socialMedia?.find((s: any) => s.type === "twitter")?.link;
  const instagram = socialMedia?.find((s: any) => s.type === "instagram")?.link;
  const facebook = socialMedia?.find((s: any) => s.type === "facebook")?.link;
  const personalWebsite =
    website || socialMedia?.find((s: any) => s.type === "website")?.link;

  // Check if any social link exists
  const hasAnySocial =
    linkedin || twitter || instagram || facebook || personalWebsite || email;

  if (!hasAnySocial) {
    return (
      <div className="bg-card rounded-xl border border-border/50 p-5">
        <h3 className="font-semibold text-foreground mb-3">Connect</h3>
        <p className="text-sm text-muted-foreground">
          No social links added yet
        </p>
      </div>
    );
  }

  return (
    <div className="bg-card rounded-xl border border-border/50 p-5">
      <h3 className="font-semibold text-foreground mb-3">Connect</h3>
      <div className="space-y-2">
        {personalWebsite && (
          <a
            href={
              personalWebsite.startsWith("http")
                ? personalWebsite
                : `https://${personalWebsite}`
            }
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors group"
          >
            <Globe className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
            <span className="text-sm text-foreground">Website</span>
          </a>
        )}

        {linkedin && (
          <a
            href={linkedin}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors group"
          >
            <Linkedin className="h-4 w-4 text-[#0A66C2]" />
            <span className="text-sm text-foreground">LinkedIn</span>
          </a>
        )}

        {twitter && (
          <a
            href={twitter}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors group"
          >
            <Twitter className="h-4 w-4 text-[#1DA1F2]" />
            <span className="text-sm text-foreground">Twitter</span>
          </a>
        )}

        {instagram && (
          <a
            href={instagram}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors group"
          >
            <Instagram className="h-4 w-4 text-[#E4405F]" />
            <span className="text-sm text-foreground">Instagram</span>
          </a>
        )}

        {facebook && (
          <a
            href={facebook}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors group"
          >
            <Facebook className="h-4 w-4 text-[#1877F2]" />
            <span className="text-sm text-foreground">Facebook</span>
          </a>
        )}

        {email && (
          <a
            href={`mailto:${email}`}
            className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors group"
          >
            <Mail className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
            <span className="text-sm text-foreground">{email}</span>
          </a>
        )}
      </div>
    </div>
  );
}

// Facebook icon component (add this if not already imported)
function Facebook({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
    </svg>
  );
}

export default function BusinessProfileContent() {
  const router = useRouter();
  const { accessToken, currentCustomer } = useSelector(
    (state: RootState) => state.user,
  );
  const [headerData, setHeaderData] = useState<any>(null);
  const [organizationData, setOrganizationData] = useState<any>({});
  const [locationData, setLocationData] = useState<any>({});
  const [whatWeOffer, setWhatWeOffer] = useState<any[]>([]);
  const [keyPeople, setKeyPeople] = useState<any[]>([]);
  const [postCategories, setPostCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [activities, setActivities] = useState<any[]>([]);
  const [activityLoading, setActivityLoading] = useState(false);
  const [activityPage, setActivityPage] = useState(1);
  const [hasMoreActivities, setHasMoreActivities] = useState(true);

  const [socialMediaData, setSocialMediaData] = useState<any[]>([]);

  const [isDarkMode, setIsDarkMode] = useState(false);

  useEffect(() => {
    const checkDarkMode = () => {
      const isDark = document.documentElement.classList.contains("dark");
      setIsDarkMode(isDark);
    };
    checkDarkMode();
    const observer = new MutationObserver(checkDarkMode);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["class"],
    });
    return () => observer.disconnect();
  }, []);

  const getFilledLikeIcon = () =>
    isDarkMode ? "/icons/dark-likefilled.svg" : "/icons/like_unfilled.svg";
  const getFilledDislikeIcon = () =>
    isDarkMode
      ? "/icons/dark-dislikefilled.svg"
      : "/icons/dislike_unfilled.svg";
  const getUnfilledLikeIcon = () =>
    isDarkMode ? "/icons/like-dark.svg" : "/icons/like_unfilled.svg";
  const getUnfilledDislikeIcon = () =>
    isDarkMode ? "/icons/dislike-dark.svg" : "/icons/dislike_unfilled.svg";

  // ✅ Format relative time helper
  const formatRelativeTime = (date: Date | string) => {
    if (!date) return "recently";
    const now = new Date();
    const past = new Date(date);
    if (isNaN(past.getTime())) return "recently";
    const diffMins = Math.floor((now.getTime() - past.getTime()) / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);
    if (diffMins < 1) return "just now";
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24)
      return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
    return past.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  };

  // ✅ Fetch Recent Activity
  const fetchRecentActivity = useCallback(
    async (pageNum: number = 1, append: boolean = false) => {
      if (!accessToken) return;

      setActivityLoading(true);
      try {
        const response = await getRecentActivity(
          accessToken,
          pageNum,
          10,
          undefined,   
          process.env.NEXT_PUBLIC_SECURITY_KEY,
        );


        if (response.success && response.data?.activities) {
          const userActivities = response.data.activities;

          const formattedActivities = userActivities.map((activity: any) => {
            const displayTimestamp = activity.timestamp || "recently";

            let categoryName = "";
            if (activity.category) {
              if (
                typeof activity.category === "object" &&
                activity.category.mainCategoryName
              ) {
                categoryName = activity.category.mainCategoryName;
              } else if (typeof activity.category === "string") {
                categoryName = activity.category;
              }
            }

            return {
              id: activity.id,
              type: activity.type,
              title:
                activity.title ||
                activity.description?.substring(0, 60) ||
                "Untitled",
              description: activity.description || "",
              timestamp: displayTimestamp,
              category: categoryName,
              postId: activity.postId,
            };
          });

          if (append) {
            setActivities((prev) => [...prev, ...formattedActivities]);
          } else {
            setActivities(formattedActivities);
          }
          setHasMoreActivities(response.data.pagination?.hasNextPage || false);
          setActivityPage(pageNum);
        } else {
          if (!append) setActivities([]);
          setHasMoreActivities(false);
        }
      } catch (error) {
        console.error("Error fetching activity:", error);
        if (!append) setActivities([]);
      } finally {
        setActivityLoading(false);
      }
    },
    [accessToken],
  );

  // Load more activities
  const loadMoreActivities = () => {
    if (!activityLoading && hasMoreActivities) {
      fetchRecentActivity(activityPage + 1, true);
    }
  };

  const fetchBusinessProfile = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getBusinessProfile();


      if (response.success && response.data) {
        const data = response.data;
        const personalInfo = data.personalInfo || {};
        const organization = data.organization || {};
        const location = data.location || {};
        const stats = data.stats || {};

        // ✅ Extract social media from personalInfo
        const socialMedia = personalInfo.socialMedia || [];


        setHeaderData({
          _id: data._id || data.personalInfo?._id,
          name: organization.name || personalInfo.fullName || "Business",
          username: personalInfo.userName || "",
          designation: personalInfo.designation || "", // ✅ ADD THIS
  address: organization.address?.street && organization.address?.street !== "undefined" 
  ? organization.address?.street 
  : "",
          avatar: personalInfo.imageURL
            ? `${BASE_URL}/uploads/${personalInfo.imageURL}`
            : "",
          bio: personalInfo.aboutMe || organization.description || "",
          location: [
            location.city,
            location.region,
            location.country || personalInfo.country,
          ]
            .filter(Boolean)
            .join(", "),
            website: organization.website || personalInfo?.socialMedia?.find((s: any) => s.type === "website")?.link || "",
          email: personalInfo.email || "", // ✅ Add email to headerData
         joinedDate: data.createdAt || personalInfo?.createdAt || data.updatedAt 
    ? new Date(data.createdAt || personalInfo?.createdAt || data.updatedAt).toLocaleDateString("en-US", {
        month: "long",
        year: "numeric",
      })
    : "Recently",
          isVerified: personalInfo.isVerified || false,
          isPremium: data.subscription?.status === "active",
          userType: "business" as const,
          aiMatchScore: 85,
          stats: {
            ideas: stats.totalPosts || 0,
            likes: stats.totalLikes || 0,
            dislikes: stats.totalDisLikes || 0,
          },
          badges: [
            data.isVerified ? "Verified Business" : null,
            data.subscription?.status === "active" ? "Premium Business" : null,
          ].filter(Boolean),
        });

        setOrganizationData(organization);
        setLocationData(location);
        setWhatWeOffer(organization.whatWeOffer || []);
        setKeyPeople(organization.keyPeople || []);
        setPostCategories(personalInfo.postCategories || []);
        setSocialMediaData(socialMedia); // ✅ Store social media in state

        // ✅ Fetch recent activity after profile loads
        await fetchRecentActivity(1, false);
      } else {
        setError(response.message || "Failed to load business profile");
      }
    } catch (err: any) {
      console.error("❌ Error fetching business profile:", err);
      setError(err?.message || "Failed to fetch business profile");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (accessToken) {
      fetchBusinessProfile();
    }
  }, [accessToken]);

  // Update tabs count based on whatWeOffer length
  const updatedTabs = tabs.map((tab) => {
    if (tab.id === "opportunities") {
      return { ...tab, count: whatWeOffer.length };
    }
    return tab;
  });

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <PublicHeader />
        <main className="max-w-5xl mx-auto">
          <ProfileHeaderSkeleton />
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 p-4 md:p-6">
            <div className="lg:col-span-2">
              <LookingForSectionSkeleton />
              <RecentActivitySkeleton />
            </div>
            <div className="lg:col-span-1">
              <CompanyOverviewSkeleton />
              <WhatWeOfferSectionSkeleton />
              <KeyPeopleSectionSkeleton />
              <ContactSectionSkeleton />
            </div>
          </div>
        </main>
      </div>
    );
  }

  if (error || !headerData) {
    return (
      <div className="min-h-screen bg-background">
        <PublicHeader />
        <div className="flex justify-center items-center h-[calc(100vh-200px)]">
          <div className="text-center">
            <div className="w-16 h-16 rounded-full bg-red-500/10 flex items-center justify-center mx-auto mb-4">
              <Building2 className="h-8 w-8 text-red-500" />
            </div>
            <h2 className="text-xl font-semibold text-foreground mb-2">
              Failed to Load Profile
            </h2>
            <p className="text-muted-foreground mb-4">
              {error || "Unable to fetch business profile data"}
            </p>
            <button
              onClick={fetchBusinessProfile}
              className="px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors"
            >
              Try Again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <PublicHeader />

      <main className="max-w-5xl mx-auto">
        <ProfileHeader {...headerData} 
         isPremium={true} 
         userId={headerData?._id || headerData?.id}
  userModel="business" 
  />
        <ProfileTabs tabs={updatedTabs} userType="business" />

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 p-4 md:p-6">
          {/* Main Content */}
          <div className="lg:col-span-2">
            <LookingForSection postCategories={postCategories} />

            {/* Recent Activity Section - Dynamic */}
<div className="bg-card rounded-xl border border-border/50">
  <div className="p-4 border-b border-border/50">
    <h2 className="font-semibold text-foreground">Recent Activity</h2>
  </div>

  {activityLoading && activities.length === 0 ? (
    <div className="p-8 text-center">
      <div className="animate-pulse space-y-4">
        <div className="bg-muted h-24 rounded-lg"></div>
        <div className="bg-muted h-24 rounded-lg"></div>
      </div>
    </div>
  ) : activities.length === 0 ? (
    <div className="p-8 text-center text-muted-foreground">
      <Activity className="h-12 w-12 mx-auto mb-3 opacity-50" />
      <p>No recent activity yet</p>
      <p className="text-sm mt-2">When you create ideas or like posts, they'll appear here</p>
    </div>
  ) : (
    <>
      <div className="divide-y divide-border/50">
        {activities.map((activity) => (
          <div
            key={activity.id}
            className="p-4 hover:bg-secondary/30 transition-colors cursor-pointer"
            onClick={() =>
              activity.postId &&
              router.push(`/idea/${activity.postId}`)
            }
          >
            <div className="flex items-start gap-3">
              {/* Icon */}
              <div className="w-8 h-8 rounded-full bg-secondary flex items-center justify-center shrink-0">
                {activity.type === "idea" && (
                  <Lightbulb className="h-4 w-4 text-primary" />
                )}
                {activity.type === "like" && (
                  <Image
                    src="/icons/like_filled.svg"
                    alt="like"
                    width={16}
                    height={16}
                    className="w-4 h-4"
                  />
                )}
                {activity.type === "dislike" && (
                  <Image
                    src="/icons/dislike_filled.svg"
                    alt="dislike"
                    width={16}
                    height={16}
                    className="w-4 h-4"
                  />
                )}
              </div>
              
              {/* Content */}
              <div className="flex-1 min-w-0">
                {activity.type === "idea" && (
                  <>
                    <p className="text-sm font-medium text-foreground">Posted an opportunity</p>
                    <h4 className="font-semibold text-foreground mt-1">{activity.title}</h4>
                    
                    {/* ✅ Category Badge - Same as individual profile */}
                    <div className="flex items-center gap-4 mt-2">
                      {activity.category && activity.category !== "Uncategorized" && (
                        <span className="px-2 py-0.5 bg-primary/10 text-primary text-xs rounded-full">
                          {activity.category}
                        </span>
                      )}
                    </div>
                  </>
                )}
                
                {activity.type === "like" && (
                  <>
                    <p className="text-sm font-medium text-foreground">Liked an idea</p>
                    <h4 className="font-semibold text-foreground mt-1">{activity.title}</h4>
                  </>
                )}
                
                {activity.type === "dislike" && (
                  <>
                    <p className="text-sm font-medium text-foreground">Disliked an idea</p>
                    <h4 className="font-semibold text-foreground mt-1">{activity.title}</h4>
                  </>
                )}
                
                {/* ✅ Timestamp - Right aligned like individual profile */}
                <p className="text-xs text-muted-foreground mt-2 text-end">
                  {activity.timestamp}
                </p>
              </div>
            </div>
          </div>
        ))}
      </div>
      
      {hasMoreActivities && (
        <div className="p-4 text-center border-t border-border/50">
          <button
            onClick={loadMoreActivities}
            disabled={activityLoading}
            className="px-4 py-2 text-sm text-primary hover:text-primary/80 disabled:opacity-50"
          >
            {activityLoading ? "Loading..." : "Load More"}
          </button>
        </div>
      )}
    </>
  )}
</div>
          </div>

          {/* Sidebar */}
          <div className="lg:col-span-1">
            <CompanyOverview
              organization={organizationData}
              location={locationData}
            />
            <WhatWeOfferSection whatWeOffer={whatWeOffer} />
            <KeyPeopleSection keyPeople={keyPeople} />
            <ContactSection
              socialMedia={socialMediaData}
              email={headerData?.email || ""}
                website={organizationData?.website || headerData?.website || ""}  // ✅ FIXED - both sources

            />
          </div>
        </div>
      </main>
    </div>
  );
}