// components/profile/individual-profile-content.tsx
'use client';

import React, { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { 
  GraduationCap, 
  Briefcase, 
  Award, 
  Globe,
  Linkedin,
  Twitter,
  Mail,
  MapPin,
  Calendar,
  CheckCircle,
  Sparkles,
  Loader,
  Lightbulb,
  Bookmark,
  MessageSquare,
  Activity,
  Instagram
} from "lucide-react";
import Image from "next/image";
import { RootState } from "@/lib/store/store";
import { getFriendDetails, getRecentActivity, getLoggedInCustomerPost, likeDislike } from "@/lib/api/client";
import { PublicHeader } from "./public-header";
import { ProfileHeader } from "./profile-header";
import { ProfileTabs } from "./profile-tabs";
import { toast } from "sonner";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

// Helper functions
const getInitials = (name: string | null | undefined) => {
  if (!name || typeof name !== 'string' || name.trim() === "") return "U";
  return name
    .split(" ")
    .map((word) => word[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
};

const formatDate = (dateString: string) => {
  if (!dateString) return "Unknown";
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
};

// Helper function to format relative time
const formatRelativeTime = (date: Date | string) => {
  if (!date) return "recently";
  
  const now = new Date();
  const past = new Date(date);
  
  // Check if date is valid
  if (isNaN(past.getTime())) {
    return "recently";
  }
  
  const diffMs = now.getTime() - past.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);
  
  if (diffMins < 1) return "just now";
  if (diffMins < 60) return `${diffMins} minute${diffMins === 1 ? '' : 's'} 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' });
};

// Static data (same as original)
const staticSkills = ["Business Strategy", "Market Research", "UI/UX Design", "Data Analysis", "Public Speaking"];
const staticInterests = ["EdTech", "Sustainability", "Social Impact", "AI/ML"];
const staticAchievements = [
  { title: "Winner - IIM B-Plan Competition 2023", icon: Award },
  { title: "Featured in Top 10 Ideas - CheckUrIdea", icon: Award },
];


// Education Section Component - WITH FROM/TO YEARS
function EducationSection({ qualifications }: { qualifications: any[] }) {
  const education = qualifications?.filter(q => q.type === "education") || [];
  
  // Helper to format education years
  const formatEducationYears = (edu: any) => {
    if (edu.fromYear && edu.toYear && edu.toYear !== "Present") {
      return `${edu.fromYear} - ${edu.toYear}`;
    }
    if (edu.fromYear && (!edu.toYear || edu.toYear === "Present")) {
      return `${edu.fromYear} - Present`;
    }
    if (edu.year && edu.year !== "") {
      return edu.year;
    }
    return "";
  };
  
  if (education.length === 0) {
    return (
      <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
        <div className="flex items-center gap-2 mb-3">
          <GraduationCap className="h-5 w-5 text-primary" />
          <h3 className="font-semibold text-foreground">Education</h3>
        </div>
        <p className="text-sm text-muted-foreground">No education added yet</p>
      </div>
    );
  }
  
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <div className="flex items-center gap-2 mb-4">
        <GraduationCap className="h-5 w-5 text-primary" />
        <h3 className="font-semibold text-foreground">Education</h3>
      </div>
      <div className="space-y-4">
        {education.map((edu, idx) => {
          const yearsDisplay = formatEducationYears(edu);
          return (
            <div key={idx} className="flex items-start gap-3">
              <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                <GraduationCap className="h-4 w-4 text-primary" />
              </div>
              <div>
                <p className="text-sm font-medium text-foreground">{edu.title || edu.degree}</p>
                <p className="text-xs text-muted-foreground">
                  {edu.institution}
                  {yearsDisplay && (
                    <span className="ml-1">• {yearsDisplay}</span>
                  )}
                </p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Work Experience Section Component - WITH FROM/TO YEARS
function ExperienceSection({ qualifications }: { qualifications: any[] }) {
  const experience = qualifications?.filter(q => q.type === "experience") || [];
  
  // Helper to format experience years
  const formatExperienceYears = (exp: any) => {
    if (exp.fromYear && exp.toYear && exp.toYear !== "Present") {
      return `${exp.fromYear} - ${exp.toYear}`;
    }
    if (exp.fromYear && (!exp.toYear || exp.toYear === "Present")) {
      return `${exp.fromYear} - Present`;
    }
    if (exp.year && exp.year !== "") {
      return exp.year;
    }
    if (exp.duration && exp.duration !== "") {
      return exp.duration;
    }
    return "";
  };
  
  if (experience.length === 0) {
    return (
      <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
        <div className="flex items-center gap-2 mb-3">
          <Briefcase className="h-5 w-5 text-primary" />
          <h3 className="font-semibold text-foreground">Work Experience</h3>
        </div>
        <p className="text-sm text-muted-foreground">No work experience added yet</p>
      </div>
    );
  }
  
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <div className="flex items-center gap-2 mb-4">
        <Briefcase className="h-5 w-5 text-primary" />
        <h3 className="font-semibold text-foreground">Work Experience</h3>
      </div>
      <div className="space-y-4">
        {experience.map((exp, idx) => {
          const yearsDisplay = formatExperienceYears(exp);
          return (
            <div key={idx} className="flex items-start gap-3">
              <div className="w-8 h-8 rounded-lg bg-secondary flex items-center justify-center shrink-0">
                <Briefcase className="h-4 w-4 text-muted-foreground" />
              </div>
              <div>
                <p className="text-sm font-medium text-foreground">{exp.title || exp.role}</p>
                <p className="text-xs text-muted-foreground">
                  {exp.institution || exp.company}
                  {yearsDisplay && (
                    <span className="ml-1">• {yearsDisplay}</span>
                  )}
                </p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Replace the static SkillsSection with this dynamic version
function SkillsSection({ skills, interests }: { skills: string[], interests: string[] }) {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <h3 className="font-semibold text-foreground mb-3">Skills</h3>
      <div className="flex flex-wrap gap-2 mb-4">
        {skills && skills.length > 0 ? (
          skills.map((skill, idx) => (
            <span key={idx} className="px-2.5 py-1 rounded-lg bg-secondary text-xs text-foreground">
              {skill}
            </span>
          ))
        ) : (
          <p className="text-sm text-muted-foreground">No skills added yet</p>
        )}
      </div>
      
      <h3 className="font-semibold text-foreground mb-3">Interests</h3>
      <div className="flex flex-wrap gap-2">
        {interests && interests.length > 0 ? (
          interests.map((interest, idx) => (
            <span key={idx} className="px-2.5 py-1 rounded-lg bg-primary/10 text-xs text-primary border border-primary/20">
              {interest}
            </span>
          ))
        ) : (
          <p className="text-sm text-muted-foreground">No interests added yet</p>
        )}
      </div>
    </div>
  );
}

// Replace the static AchievementsSection with this dynamic version
function AchievementsSection({ achievements }: { achievements: Array<{ title: string }> }) {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4">
      <h3 className="font-semibold text-foreground mb-3">Achievements</h3>
      <div className="space-y-3">
        {achievements && achievements.length > 0 ? (
          achievements.map((item, idx) => (
            <div key={idx} className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-amber-500/10 flex items-center justify-center">
                <Award className="h-4 w-4 text-amber-500" />
              </div>
              <p className="text-sm text-foreground">{item.title}</p>
            </div>
          ))
        ) : (
          <p className="text-sm text-muted-foreground">No achievements added yet</p>
        )}
      </div>
    </div>
  );
}

// Social Links - Updated to handle different data structures
function SocialLinks({ socialMedia, email, website }: { 
  socialMedia?: any[]; 
  email?: string; 
  website?: string;
}) {

  // ✅ Add this to see array contents
  if (socialMedia && Array.isArray(socialMedia)) {
    socialMedia.forEach((item, index) => {
    });
  }
  
  // Helper function to extract social links from different structures
  let linkedin = "", twitter = "", instagram = "", github = "", personalWebsite = "";
  
  // Check if socialMedia is an array
  if (socialMedia && Array.isArray(socialMedia) && socialMedia.length > 0) {
    socialMedia.forEach((s: any) => {
      const type = s.type?.toLowerCase() || "";
      const link = s.link || "";
      
      if (type === "linkedin") linkedin = link;
      else if (type === "twitter") twitter = link;
      else if (type === "instagram") instagram = link;
      else if (type === "github") github = link;
      else if (type === "website") personalWebsite = link;
    });
  }
  
  // Also check for separate fields
  if (!personalWebsite && website) personalWebsite = website;
  
  // Check if any social link exists
  const hasAnySocial = linkedin || twitter || instagram || github || 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>
        )}
        
        {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>
  );
}

// Loading skeleton for profile header
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>
  );
}

// Main Component
export default function IndividualProfileContent() {
  const router = useRouter();
  const { accessToken, currentCustomer, dynamicImages } = useSelector((state: RootState) => state.user);
  const securityKey = dynamicImages?.securityKey;
  const [profile, setProfile] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("ideas");
  
  // State for My Ideas
  const [userIdeas, setUserIdeas] = useState<any[]>([]);
  const [ideasLoading, setIdeasLoading] = useState(false);
  const [ideasPage, setIdeasPage] = useState(1);
  const [hasMoreIdeas, setHasMoreIdeas] = useState(true);
  
  // State for Recent Activity
  const [activities, setActivities] = useState<any[]>([]);
  const [activityLoading, setActivityLoading] = useState(false);
  const [activityPage, setActivityPage] = useState(1);
  const [hasMoreActivities, setHasMoreActivities] = useState(true);

    const [isDarkMode, setIsDarkMode] = useState(false);
  
    
     useEffect(() => {
        const checkDarkMode = () => {
          const isDark = document.documentElement.classList.contains('dark');
          setIsDarkMode(isDark);
        };
    
        checkDarkMode();
    
        // Watch for class changes on html element
        const observer = new MutationObserver(checkDarkMode);
        observer.observe(document.documentElement, { 
          attributes: true, 
          attributeFilter: ['class'] 
        });
    
        return () => observer.disconnect();
      }, []);
    

       const getFilledLikeIcon = () => {
    return isDarkMode ? "/icons/dark-likefilled.svg" : "/icons/like_unfilled.svg";
  };

  const getFilledDislikeIcon = () => {
    return isDarkMode ? "/icons/dark-dislikefilled.svg" : "/icons/dislike_unfilled.svg";
  };
      // Determine which unfilled icon to use
      const getUnfilledLikeIcon = () => {
        return isDarkMode ? "/icons/like-dark.svg" : "/icons/like_unfilled.svg";
      };
    
      const getUnfilledDislikeIcon = () => {
        return isDarkMode ? "/icons/dislike-dark.svg" : "/icons/dislike_unfilled.svg";
      };

  // ✅ Fetch full profile data from API
  const fetchProfile = useCallback(async () => {
    let userName = currentCustomer?.customer?.userName;
    
    if (!accessToken || !userName) {
      setLoading(false);
      return;
    }
    
    if (userName.startsWith('@')) {
      userName = userName.substring(1);
    }
    
    setLoading(true);
    try {
      const response = await getFriendDetails(accessToken, userName, process.env.NEXT_PUBLIC_SECURITY_KEY);
      
      if (response.success) {
        setProfile(response.data);
      } else {
        console.log("❌ API failed:", response.message);
      }
    } catch (error) {
      console.error("Error fetching profile:", error);
    } finally {
      setLoading(false);
    }
  }, [accessToken, currentCustomer]);

  

// ✅ Fetch user's own posts (My Ideas)
const fetchUserIdeas = useCallback(async (pageNum: number = 1, append: boolean = false) => {
  if (!accessToken) return;
  
  setIdeasLoading(true);
  try {
    const response = await getLoggedInCustomerPost(
      "new",
      accessToken,
      pageNum,
      5,
      "",
      process.env.NEXT_PUBLIC_SECURITY_KEY
    );
    
    
    if (response.success && response.posts) {
      const formattedIdeas = response.posts.map((post: any) => {
        // Get category name correctly
        let categoryName = "";
        if (post.postCategory) {
          if (typeof post.postCategory === 'object' && post.postCategory.mainCategoryName) {
            categoryName = post.postCategory.mainCategoryName;
          } else if (typeof post.postCategory === 'string') {
            categoryName = post.postCategory;
          }
        }
        
        return {
          id: post._id,
          type: "idea",
          title: post.description?.substring(0, 100) || "Untitled",
          description: post.description || "",
          timestamp: formatRelativeTime(post.createdAt),
          category: categoryName,
          likes: post.counts?.likes || 0,
          dislikes: post.counts?.dislikes || 0,
          likeStatus: post.likeStatus || null
        };
      });
      
      if (append) {
        setUserIdeas(prev => [...prev, ...formattedIdeas]);
      } else {
        setUserIdeas(formattedIdeas);
      }
      
      setHasMoreIdeas(response.posts.length === 5);
      setIdeasPage(pageNum);
    } else {
      if (!append) setUserIdeas([]);
      setHasMoreIdeas(false);
    }
  } catch (error) {
    console.error("Error fetching user ideas:", error);
    if (!append) setUserIdeas([]);
  } finally {
    setIdeasLoading(false);
  }
}, [accessToken]);

  // ✅ 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, 5, undefined, process.env.NEXT_PUBLIC_SECURITY_KEY);
      
      if (response.success && response.data) {
        const formattedActivities = response.data.activities.map((activity: any) => {
          let validTimestamp = activity.timestamp || activity.createdAt;
          
          if (!validTimestamp || validTimestamp === "Invalid Date") {
            validTimestamp = new Date().toISOString();
          }
          
          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: formatRelativeTime(validTimestamp),
            category: categoryName,
            likes: activity.engagement?.likes || 0
          };
        });
        
        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 recent activity:", error);
      if (!append) setActivities([]);
    } finally {
      setActivityLoading(false);
    }
  }, [accessToken]);

  // Handle like/dislike for ideas
  const handleLike = async (ideaId: string, currentLikeStatus: string | null, currentLikes: number, currentDislikes: number) => {
    if (!accessToken) {
      toast.error("Please login to like posts");
      return;
    }

    const wasLiked = currentLikeStatus === "like";
    
    // Optimistic update
    const updatedIdeas = userIdeas.map(idea => {
      if (idea.id === ideaId) {
        if (wasLiked) {
          return { ...idea, likes: idea.likes - 1, likeStatus: null };
        } else {
          let newLikes = idea.likes + 1;
          let newDislikes = idea.dislikes;
          let newStatus = "like";
          
          if (idea.likeStatus === "dislike") {
            newDislikes = idea.dislikes - 1;
          }
          return { ...idea, likes: newLikes, dislikes: newDislikes, likeStatus: newStatus };
        }
      }
      return idea;
    });
    setUserIdeas(updatedIdeas);

    try {
      const result = await likeDislike(accessToken, ideaId, "like", securityKey);
      
      if (result.success) {
        const finalUpdatedIdeas = userIdeas.map(idea => {
          if (idea.id === ideaId) {
            return {
              ...idea,
              likes: result.data.counts.likes,
              dislikes: result.data.counts.dislikes,
              likeStatus: result.data.userReaction
            };
          }
          return idea;
        });
        setUserIdeas(finalUpdatedIdeas);
      } else {
        // Rollback
        setUserIdeas(userIdeas);
        toast.error(result.message || "Could not like the post");
      }
    } catch (error) {
      setUserIdeas(userIdeas);
      toast.error("Could not like the post");
    }
  };

  const handleDislike = async (ideaId: string, currentLikeStatus: string | null, currentLikes: number, currentDislikes: number) => {
    if (!accessToken) {
      toast.error("Please login to dislike posts");
      return;
    }

    const wasDisliked = currentLikeStatus === "dislike";
    
    // Optimistic update
    const updatedIdeas = userIdeas.map(idea => {
      if (idea.id === ideaId) {
        if (wasDisliked) {
          return { ...idea, dislikes: idea.dislikes - 1, likeStatus: null };
        } else {
          let newDislikes = idea.dislikes + 1;
          let newLikes = idea.likes;
          let newStatus = "dislike";
          
          if (idea.likeStatus === "like") {
            newLikes = idea.likes - 1;
          }
          return { ...idea, likes: newLikes, dislikes: newDislikes, likeStatus: newStatus };
        }
      }
      return idea;
    });
    setUserIdeas(updatedIdeas);

    try {
      const result = await likeDislike(accessToken, ideaId, "dislike", securityKey);
      
      if (result.success) {
        const finalUpdatedIdeas = userIdeas.map(idea => {
          if (idea.id === ideaId) {
            return {
              ...idea,
              likes: result.data.counts.likes,
              dislikes: result.data.counts.dislikes,
              likeStatus: result.data.userReaction
            };
          }
          return idea;
        });
        setUserIdeas(finalUpdatedIdeas);
      } else {
        // Rollback
        setUserIdeas(userIdeas);
        toast.error(result.message || "Could not dislike the post");
      }
    } catch (error) {
      setUserIdeas(userIdeas);
      toast.error("Could not dislike the post");
    }
  };

  // Load more ideas
  const loadMoreIdeas = () => {
    if (!ideasLoading && hasMoreIdeas) {
      fetchUserIdeas(ideasPage + 1, true);
    }
  };

  // Load more activities
  const loadMoreActivities = () => {
    if (!activityLoading && hasMoreActivities) {
      fetchRecentActivity(activityPage + 1, true);
    }
  };

  // Fetch ideas when component mounts or tab changes to "ideas"
 useEffect(() => {
  if (activeTab === "ideas" && !ideasLoading) {
    fetchUserIdeas(1, false);
  }
}, [activeTab]);

  // Fetch activity when tab changes to "activity"
  useEffect(() => {
    if (activeTab === "activity" && activities.length === 0 && !activityLoading) {
      fetchRecentActivity(1, false);
    }
  }, [activeTab, fetchRecentActivity, activities.length, activityLoading]);

  useEffect(() => {
    if (!currentCustomer && !accessToken) {
      router.push("/login");
      return;
    }
    fetchProfile();
  }, [currentCustomer, accessToken, router, fetchProfile]);

  // Get user data from API response
  const userData = profile?.customer || profile;
  
  // Get categories for badges
  const userCategories = userData?.postCategories || [];
  const categoryNames = userCategories.map((cat: any) => {
    if (typeof cat === 'object' && cat.mainCategoryName) {
      return cat.mainCategoryName;
    }
    return cat;
  });
  
  const userStats = {
    ideas: profile?.totalPost || userData?.totalPost ,
    likes: profile?.totalLikes || userData?.totalLikes ,
    dislikes: profile?.totalDisLikes || userData?.totalDisLikes ,
  };
  
  // Check if aboutMe is the default placeholder
  const isDefaultAbout = userData?.aboutMe === "max 200 characters";
  
  // Get bio
  const bioText = isDefaultAbout 
    ? (userData?.bio || "")
    : (userData?.aboutMe || userData?.bio || "");
  
  // Prepare data for ProfileHeader
  const individualData = {
    name: userData?.fullName || "User",
    username: userData?.userName || "username",
     designation: userData?.designation || "", // ✅ ADD THIS
  address: userData?.address || "",
    avatar: userData?.imageURL ? `${BASE_URL}/uploads/${userData.imageURL}` : "",
    bio: bioText,
    location: userData?.city ? `${userData.city}, ${userData.country}` : userData?.country || "Location not set",
    website: userData?.website || "",
    joinedDate: formatDate(userData?.createdAt) || "Unknown",
    isVerified: userData?.isVerified || false,
    isPremium: userData?.isPremium || false,
    userType: "individual" as const,
    aiMatchScore: userData?.aiMatchScore || 0,
    stats: userStats,
    badges: categoryNames,
  };
  
  // Update tabs with actual counts
  const updatedTabs = [
    { id: "ideas", label: "My Ideas", count: userStats.ideas },
    { id: "saved", label: "Saved", count: 0 },
    { id: "activity", label: "Activity" },
  ];
  
  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <PublicHeader />
        <main className="max-w-5xl mx-auto">
          <ProfileHeaderSkeleton />
        </main>
      </div>
    );
  }
  
  if (!currentCustomer && !accessToken) {
    return null;
  }

  const userSkills = userData?.skills || [];
const userInterests = userData?.interests || [];
const userAchievements = userData?.achievements || [];

  return (
    <div className="min-h-screen bg-background">
      <PublicHeader />
      
      <main className="max-w-5xl mx-auto">
        <ProfileHeader {...individualData}
         isPremium={true}    
        userId={userData?._id}
        userModel="customer"  />
        
        <ProfileTabs 
          tabs={updatedTabs} 
          userType="individual" 
          onTabChange={(tabId) => setActiveTab(tabId)}
        />

        <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">
            <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">
                  {activeTab === "ideas" && "My Ideas"}
                  {activeTab === "saved" && "Saved Ideas"}
                  {activeTab === "activity" && "Recent Activity"}
                </h2>
              </div>
              
              {/* My Ideas Tab */}
            {activeTab === "ideas" && (
  <div>
    {/* 🔥 Show skeleton ONLY when loading & no data yet */}
    {ideasLoading && userIdeas.length === 0 ? (
      <div className="p-8 text-center">
        <div className="animate-pulse space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="bg-muted h-24 rounded-lg"></div>
          ))}
        </div>
      </div>
    ) : userIdeas.length === 0 ? (
      /* ❌ No Ideas */
      <div className="p-8 text-center text-muted-foreground">
        <Lightbulb className="h-12 w-12 mx-auto mb-3 opacity-50" />
        <p>No ideas posted yet</p>
        <p className="text-sm mt-2">
          Share your first idea to get started!
        </p>
      </div>
    ) : (
      /* ✅ Ideas List */
      <>
        <div className="divide-y divide-border/50">
          {userIdeas.map((idea) => {
            const isLiked = idea.likeStatus === "like";
            const isDisliked = idea.likeStatus === "dislike";

            return (
              <div
                key={idea.id}
                className="p-4 hover:bg-secondary/30 transition-colors"
              >
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                    <Lightbulb className="h-4 w-4 text-primary" />
                  </div>

                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground">
                      Posted an idea
                    </p>

                    <h4 className="font-semibold text-foreground mt-1">
                      {idea.title}
                    </h4>

                    <div className="flex items-center gap-4 mt-2">
                      {idea.category &&
                        idea.category !== "Uncategorized" && (
                          <span className="px-2 py-0.5 bg-primary/10 text-primary text-xs rounded-full">
                            {idea.category}
                          </span>
                        )}

                      {/* 👍 Like */}
                      <button
                        onClick={() =>
                          handleLike(
                            idea.id,
                            idea.likeStatus,
                            idea.likes,
                            idea.dislikes
                          )
                        }
                        className={`flex items-center gap-1.5 px-2 py-1 rounded-lg transition-all ${
                          isLiked ? "" : "hover:bg-secondary"
                        }`}
                      >
                        <Image
                          src={
                            isLiked
                              ? getFilledLikeIcon()
                              : getUnfilledLikeIcon()
                          }
                          alt="like"
                          width={20}
                          height={20}
                          className="w-5 h-5"
                        />
                        <span
                          className={`text-sm font-medium ${
                            isLiked
                              ? "text-primary"
                              : "text-muted-foreground"
                          }`}
                        >
                          {idea.likes || 0}
                        </span>
                      </button>

                      {/* 👎 Dislike */}
                      <button
                        onClick={() =>
                          handleDislike(
                            idea.id,
                            idea.likeStatus,
                            idea.likes,
                            idea.dislikes
                          )
                        }
                        className={`flex items-center gap-1.5 px-2 py-1 rounded-lg transition-all ${
                          isDisliked ? "" : "hover:bg-secondary"
                        }`}
                      >
                        <Image
                          src={
                            isDisliked
                              ? getFilledDislikeIcon()
                              : getUnfilledDislikeIcon()
                          }
                          alt="dislike"
                          width={20}
                          height={20}
                          className="w-5 h-5"
                        />
                        <span
                          className={`text-sm font-medium ${
                            isDisliked
                              ? "text-primary"
                              : "text-muted-foreground"
                          }`}
                        >
                          {idea.dislikes || 0}
                        </span>
                      </button>
                    </div>

                    <p className="text-xs text-muted-foreground text-end mt-2">
                      {idea.timestamp}
                    </p>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* 🔄 Load More */}
        {hasMoreIdeas && (
          <div className="p-4 text-center border-t border-border/50">
            <button
              onClick={loadMoreIdeas}
              disabled={ideasLoading}
              className="px-4 py-2 text-sm text-primary hover:text-primary/80 disabled:opacity-50"
            >
              {ideasLoading ? "Loading..." : "Load More"}
            </button>
          </div>
        )}
      </>
    )}
  </div>
)}
              
              {/* Saved Tab */}
              {activeTab === "saved" && (
                <div className="p-8 text-center text-muted-foreground">
                  <Bookmark className="h-12 w-12 mx-auto mb-3 opacity-50" />
                  <p>No saved ideas yet</p>
                  <p className="text-sm mt-2">Save interesting ideas to read them later</p>
                </div>
              )}
              
              {/* Activity Tab */}
              {activeTab === "activity" && (
                <div>
                  {activityLoading && activities.length === 0 ? (
                    <div className="p-8 text-center">
                      <div className="animate-pulse space-y-4">
                        {[1, 2, 3].map((i) => (
                          <div key={i} 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">
                            <div className="flex items-start gap-3">
                              <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>
                              <div className="flex-1 min-w-0">
                                {activity.type === "idea" ? (
                                  <>
                                    <p className="text-sm font-medium text-foreground">Posted an idea</p>
                                    <h4 className="font-semibold text-foreground mt-1">{activity.title}</h4>
                                    
                                    {activity.category && activity.category !== "Uncategorized" && (
                                      <span className="inline-block mt-2 px-2 py-0.5 bg-primary/10 text-primary text-xs rounded-full">
                                        {activity.category}
                                      </span>
                                    )}
                                  </>
                                ) : 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.description && (
                                      <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                                        {activity.description}
                                      </p>
                                    )} */}
                                  </>
                                ) : 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>
                                    {/* {activity.description && (
                                      <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                                        {activity.description}
                                      </p>
                                    )} */}
                                  </>
                                ) : null}
                                <p className="text-xs flex items-end text-muted-foreground mt-2">
                                  {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>
          </div>

          {/* Sidebar - All static */}
          <div className="lg:col-span-1">
                      <EducationSection qualifications={userData?.qualifications || []} />
  
  {/* Work Experience Section */}
  <ExperienceSection qualifications={userData?.qualifications || []} />

             <SkillsSection skills={userSkills} interests={userInterests} />
          {/* ✅ Pass the props! */}
          <AchievementsSection achievements={userAchievements} />
              <SocialLinks 
    socialMedia={userData?.socialMedia} 
    email={userData?.email}
    website={userData?.website}
  />
          </div>
        </div>
      </main>
    </div>
  );
}