'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 { cn } from "@/lib/utils"
import { 
  TrendingUp, 
  IndianRupee, 
  Target, 
  PieChart,
  Briefcase,
  GraduationCap,
  Globe,
  Linkedin,
  Twitter,
  Mail,
  Building2,
  CheckCircle,
  Loader2,
  Activity,
  Lightbulb,
  Clock
} from "lucide-react"
import { getInvestorProfile, 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: "portfolio", label: "Portfolio", count: 0 },
  { id: "interests", 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 InvestmentStatsSkeleton() {
  return (
    <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
      {[1, 2, 3, 4].map((i) => (
        <div key={i} className="bg-card rounded-xl border border-border/50 p-4">
          <div className="w-8 h-8 rounded-lg bg-muted animate-pulse mb-2"></div>
          <div className="h-7 w-20 bg-muted rounded animate-pulse mb-1"></div>
          <div className="h-3 w-16 bg-muted rounded animate-pulse"></div>
        </div>
      ))}
    </div>
  );
}

function InvestmentFocusSkeleton() {
  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, 3].map((i) => (
          <div key={i}>
            <div className="flex justify-between mb-1">
              <div className="h-4 w-16 bg-muted rounded animate-pulse"></div>
              <div className="h-4 w-8 bg-muted rounded animate-pulse"></div>
            </div>
            <div className="h-1.5 bg-secondary rounded-full overflow-hidden">
              <div className="h-full bg-muted rounded-full w-3/4"></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function InvestmentCriteriaSkeleton() {
  return (
    <div className="bg-card rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-5 mb-4">
      <div className="flex items-center gap-2 mb-4">
        <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="grid grid-cols-2 gap-4">
        {[1, 2, 3, 4].map((i) => (
          <div key={i}>
            <div className="h-3 w-16 bg-muted rounded animate-pulse mb-1"></div>
            <div className="h-4 w-20 bg-muted rounded animate-pulse"></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function BackgroundSectionSkeleton() {
  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-4">
        {[1, 2].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-4 w-32 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 PortfolioHighlightsSkeleton() {
  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-center justify-between p-3 rounded-lg bg-secondary/50">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-muted animate-pulse"></div>
              <div>
                <div className="h-4 w-24 bg-muted rounded animate-pulse mb-1"></div>
                <div className="h-3 w-16 bg-muted rounded animate-pulse"></div>
              </div>
            </div>
            <div className="h-4 w-12 bg-muted rounded animate-pulse"></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>
  );
}

// Investment Stats Component - DYNAMIC
// Investment Stats Component - With 6 boxes (including Annual Income & Net Worth)
function InvestmentStats({ 
  stats, 
  annualIncomeRange, 
  netWorth 
}: { 
  stats: { totalInvested?: string; activeDeals?: number; avgIRR?: string; exits?: number };
  annualIncomeRange?: string;
  netWorth?: string;
}) {
  const defaultStats = [
    { icon: IndianRupee, label: "Total Invested", value: stats.totalInvested || "Rs 0", color: "text-emerald-400" },
    { icon: Target, label: "Active Deals", value: stats.activeDeals?.toString() || "0", color: "text-emerald-400" },
    { icon: TrendingUp, label: "Avg. IRR", value: stats.avgIRR || "0%", color: "text-emerald-400" },
    { icon: PieChart, label: "Exits", value: stats.exits?.toString() || "0", color: "text-emerald-400" },
    { icon: IndianRupee, label: "Annual Income", value: annualIncomeRange || "Not set", color: "text-emerald-400" },
    { icon: IndianRupee, label: "Net Worth", value: netWorth || "Not set", color: "text-emerald-400" },
  ]

  return (
    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mb-4">
      {defaultStats.map((stat) => (
        <div key={stat.label} className="bg-card rounded-xl border border-border/50 p-4">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-8 h-8 rounded-lg bg-emerald-500/10 flex items-center justify-center">
              <stat.icon className={cn("h-4 w-4", stat.color)} />
            </div>
          </div>
          <p className="text-lg font-bold text-foreground">{stat.value}</p>
          <p className="text-xs text-muted-foreground">{stat.label}</p>
        </div>
      ))}
    </div>
  )
}

// Add this new component after InvestmentCriteria function
function SectorFocusDisplay({ sectorFocus }: { sectorFocus: Array<{ name: string }> }) {
  if (!sectorFocus || sectorFocus.length === 0) {
    return (
      <div className="bg-card rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-5 mb-4 opacity-60">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Target className="h-4 w-4 text-emerald-400" />
            <h3 className="font-semibold text-foreground">Sector Focus</h3>
          </div>
          <div className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-secondary/50">
            <Clock className="h-3 w-3 text-muted-foreground" />
            <span className="text-xs font-medium text-muted-foreground">Coming Soon</span>
          </div>
        </div>
        <div className="text-center py-4">
          <p className="text-xs text-muted-foreground">Select sectors to see them here</p>
        </div>
        <div className="mt-4 pt-3 border-t border-emerald-500/20 text-center">
          <p className="text-xs text-muted-foreground">📊 Update your profile to add sector preferences</p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-card rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-5 mb-4">
      <div className="flex items-center gap-2 mb-4">
        <Target className="h-4 w-4 text-emerald-400" />
        <h3 className="font-semibold text-foreground">Sector Focus</h3>
      </div>
      <div className="flex flex-wrap gap-2">
        {sectorFocus.map((sector, idx) => (
          <span key={idx} className="px-3 py-1.5 rounded-full bg-emerald-500/10 text-emerald-400 text-sm border border-emerald-500/20">
            {sector.name}
          </span>
        ))}
      </div>
    </div>
  );
}

// ✅ Investment Criteria - GRAYED OUT with "Coming Soon"
function InvestmentCriteria({ criteria }: { criteria: { ticketSize?: string; stage?: string; geography?: string; decisionTime?: string } }) {
  return (
    <div className="bg-card rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-5 mb-4 opacity-60">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <Target className="h-4 w-4 text-emerald-400" />
          <h3 className="font-semibold text-foreground">Investment Criteria</h3>
        </div>
        <div className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-secondary/50">
          <Clock className="h-3 w-3 text-muted-foreground" />
          <span className="text-xs font-medium text-muted-foreground">Coming Soon</span>
        </div>
      </div>
      
      <div className="grid grid-cols-2 gap-4">
        <div>
          <p className="text-xs text-muted-foreground mb-1">Ticket Size</p>
          <p className="text-sm font-medium text-foreground">{criteria.ticketSize || "Not specified"}</p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground mb-1">Stage</p>
          <p className="text-sm font-medium text-foreground">{criteria.stage || "Not specified"}</p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground mb-1">Geography</p>
          <p className="text-sm font-medium text-foreground">{criteria.geography || "Not specified"}</p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground mb-1">Decision Time</p>
          <p className="text-sm font-medium text-foreground">{criteria.decisionTime || "Not specified"}</p>
        </div>
      </div>

      <div className="mt-4 pt-3 border-t border-emerald-500/20 text-center">
        <p className="text-xs text-muted-foreground">
          📊 Detailed investment criteria customization coming soon
        </p>
      </div>
    </div>
  )
}

// Replace BackgroundSection with two separate components:

// Education Section
function EducationSection({ education }: { education: any[] }) {
  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) return edu.year;
    return "";
  };

  if (!education || education.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">Education</h3>
      <div className="space-y-4">
        {education.map((edu, idx) => (
          <div key={idx} className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-secondary flex items-center justify-center shrink-0">
              <GraduationCap className="h-4 w-4 text-muted-foreground" />
            </div>
            <div>
              <p className="text-sm font-medium text-foreground">{edu.degree}</p>
              <p className="text-xs text-muted-foreground">
                {edu.institution}
                {formatEducationYears(edu) && ` • ${formatEducationYears(edu)}`}
              </p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Experience Section
function ExperienceSection({ experience }: { experience: any[] }) {
  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.duration) return exp.duration;
    return "";
  };

  if (!experience || experience.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">Experience</h3>
      <div className="space-y-4">
        {experience.map((exp, idx) => (
          <div key={idx} className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-emerald-500/10 flex items-center justify-center shrink-0">
              <Briefcase className="h-4 w-4 text-emerald-400" />
            </div>
            <div>
              <p className="text-sm font-medium text-foreground">{exp.role}</p>
              <p className="text-xs text-muted-foreground">
                {exp.company}
                {formatExperienceYears(exp) && ` • ${formatExperienceYears(exp)}`}
              </p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PortfolioHighlights({ portfolio }: { portfolio: any[] }) {
  return (
    <div className="bg-card rounded-xl border border-border/50 p-5 mb-4 opacity-60 mt-2">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-semibold text-foreground">Portfolio Highlights</h3>
        <div className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-secondary/50">
          <Clock className="h-3 w-3 text-muted-foreground" />
          <span className="text-xs font-medium text-muted-foreground">Coming Soon</span>
        </div>
      </div>
      <div className="space-y-3">
        {portfolio && portfolio.length > 0 ? (
          portfolio.map((item, idx) => (
            <div key={idx} className="flex items-center justify-between p-3 rounded-lg bg-secondary/50">
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 rounded-lg bg-secondary flex items-center justify-center text-xs font-bold">
                  {item.name?.charAt(0) || "?"}
                </div>
                <div>
                  <p className="text-sm font-medium text-foreground">{item.name}</p>
                  <p className="text-xs text-muted-foreground">{item.status}</p>
                </div>
              </div>
              <span className="text-sm font-bold text-emerald-400">{item.return}</span>
            </div>
          ))
        ) : (
          <p className="text-sm text-muted-foreground text-center py-4">
            Portfolio features coming soon
          </p>
        )}
      </div>
      <div className="mt-4 pt-3 border-t border-border/30 text-center">
        <p className="text-xs text-muted-foreground">
          📊 Track your investment portfolio here soon
        </p>
      </div>
    </div>
  );
}

// Contact Section - DYNAMIC (Social Links)
function ContactSection({ socialMedia, email, website }: { socialMedia?: any[]; email?: string; website?: string }) {
  const linkedin = socialMedia?.find((s: any) => s.type === "linkedin")?.link;
  const twitter = socialMedia?.find((s: any) => s.type === "twitter")?.link;
  const personalWebsite = website || socialMedia?.find((s: any) => s.type === "website")?.link;
  
  const hasAnySocial = linkedin || twitter || 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} target="_blank" rel="noopener noreferrer" className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors">
            <Globe className="h-4 w-4 text-muted-foreground" />
            <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">
            <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">
            <Twitter className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm text-foreground">Twitter</span>
          </a>
        )}
        {email && (
          <a href={`mailto:${email}`} className="flex items-center gap-3 p-2 rounded-lg hover:bg-secondary transition-colors">
            <Mail className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm text-foreground">{email}</span>
          </a>
        )}
      </div>
    </div>
  )
}

export default function InvestorProfileContent() {
  const router = useRouter();
  const { accessToken, currentCustomer } = useSelector((state: RootState) => state.user);
  const [headerData, setHeaderData] = useState<any>(null);
  const [investorStats, setInvestorStats] = useState<any>({});
  const [investorCriteria, setInvestorCriteria] = useState<any>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [backgroundData, setBackgroundData] = useState({ education: [], experience: [] });
  const [portfolioData, setPortfolioData] = useState([]);
  const [socialData, setSocialData] = useState({ socialMedia: [], email: "", website: "" });
  const [sectorFocus, setSectorFocus] = useState<Array<{ name: string; percentage: number }>>([]);

  const [postCategories, setPostCategories] = useState<any[]>([]);


    const [activeTab, setActiveTab] = useState("portfolio");  // Default tab



  // Recent Activity States
  const [annualIncomeRange, setAnnualIncomeRange] = useState("");
const [netWorth, setNetWorth] = useState("");
  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();
    const observer = new MutationObserver(checkDarkMode);
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
    return () => observer.disconnect();
  }, []);

  // ✅ 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) => {
          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,
            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 fetchInvestorProfile = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getInvestorProfile();
      
      console.log("Investor API Response:", response);
      
      if (response.success && response.data) {
        const investor = response.data;
        const personalInfo = investor.personalInfo || {};
        const investorInfo = investor.investorInfo || {};
        
        // Header Data
        setHeaderData({
          _id: personalInfo._id || investor._id,
        name: investorInfo.businessName || personalInfo.fullName || "Investor",  
          username: personalInfo.userName || "@investor",
          avatar: personalInfo.imageURL ? `${BASE_URL}/uploads/${personalInfo.imageURL}` : "",
          bio: personalInfo.aboutMe || investorInfo.bio || "",
          location: personalInfo.country || "",
           designation: personalInfo.designation || investorInfo.designation || "",
           address: personalInfo.address || "",
          website: investorInfo.website || "",
joinedDate: investor.createdAt || personalInfo.createdAt || investor.updatedAt
    ? new Date(investor.createdAt || personalInfo.createdAt || investor.updatedAt).toLocaleDateString('en-US', { 
        month: 'long', 
        year: 'numeric' 
      })
    : "Recently",
              isVerified: personalInfo.isVerified || false,
          isPremium: investorInfo.isPremium || false,
          userType: "investor" as const,
          aiMatchScore: 85,
          stats: {
            ideas: investor.stats?.totalPosts || 0,
            likes: investor.stats?.totalLikes || 0,
            dislikes: investor.stats?.totalDisLikes || 0,
          },
          badges: [
            investor.security?.isVerified ? "Verified Investor" : null,
            investorInfo.isPremium ? "Premium Investor" : null,
            investorInfo.topAngel ? "Top 100 Angels" : null,
          ].filter(Boolean)
        });
        
        // Investment Stats
        setInvestorStats({
          totalInvested: investorInfo.stats?.totalInvested || "Rs 0",
          activeDeals: investorInfo.stats?.activeDeals || 0,
          avgIRR: investorInfo.stats?.avgIRR || "0%",
          exits: investorInfo.stats?.exits || 0
        });

        setAnnualIncomeRange(investorInfo.annualIncomeRange || "");
setNetWorth(investorInfo.netWorth || "");
        
        // Investment Criteria
        setInvestorCriteria({
          ticketSize: investorInfo.criteria?.ticketSize || "Not specified",
          stage: investorInfo.criteria?.stage || "Not specified",
          geography: investorInfo.criteria?.geography || "Not specified",
          decisionTime: investorInfo.criteria?.decisionTime || "Not specified"
        });
        
        // Background (Education & Experience)
        setBackgroundData({
          education: personalInfo.education || [],
          experience: personalInfo.experience || []
        });
        
        // Portfolio
        setPortfolioData(investorInfo.portfolio || []);
        
        // Social Links
        setSocialData({
          socialMedia: personalInfo.socialMedia || [],
          email: personalInfo.email,
          website: investorInfo.website
        });
        setPostCategories(personalInfo.postCategories || []);

        
        // Sector Focus (if available from API)
        setSectorFocus(investorInfo.sectorFocus || [
          { name: "FinTech", percentage: 35 },
          { name: "HealthTech", percentage: 25 },
          { name: "Enterprise SaaS", percentage: 20 },
          { name: "CleanTech", percentage: 12 },
          { name: "Others", percentage: 8 },
        ]);
        
        // ✅ Fetch recent activity after profile loads
        await fetchRecentActivity(1, false);
        
      } else {
        setError(response.message || 'Failed to load investor profile');
      }
    } catch (err: any) {
      console.error('Error:', err);
      setError(err?.message || 'Failed to fetch investor profile');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (accessToken) {
      fetchInvestorProfile();
    }
  }, [accessToken]);

  // Update tabs count based on portfolio length
  const updatedTabs = tabs.map(tab => {
    if (tab.id === "portfolio") {
      return { ...tab, count: portfolioData.length };
    }
    return tab;
  });

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <PublicHeader />
        <main className="max-w-5xl mx-auto">
          <ProfileHeaderSkeleton />
          <div className="p-4 md:p-6">
            <InvestmentStatsSkeleton />
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
              <div className="lg:col-span-2">
                <InvestmentCriteriaSkeleton />
                <RecentActivitySkeleton />
              </div>
              <div className="lg:col-span-1">
                 <SectorFocusDisplay sectorFocus={sectorFocus} />
                 {/* Education - separate */}
  <EducationSection education={backgroundData.education} />
  
  {/* Experience - separate */}
  <ExperienceSection experience={backgroundData.experience} />
  
  {/* Portfolio Highlights - Coming Soon */}
  <PortfolioHighlights portfolio={portfolioData} />
                <PortfolioHighlightsSkeleton />
                <ContactSectionSkeleton />
              </div>
            </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">
              <TrendingUp 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 investor profile data'}</p>
            <button
              onClick={fetchInvestorProfile}
              className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-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="investor"
      />
      <ProfileTabs tabs={updatedTabs} userType="investor" onTabChange={(tabId) => setActiveTab(tabId)} />

      <div className="p-4 md:p-6">
        {/* Portfolio Tab - Full Profile */}
       {activeTab === "portfolio" && (
  <>
    {/* 4 boxes - Investment Stats */}
    <InvestmentStats stats={investorStats}    annualIncomeRange={annualIncomeRange}
      netWorth={netWorth} />
    
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
      <div className="lg:col-span-2">
        {/* Sector Focus - AB UPAR */}
        <SectorFocusDisplay sectorFocus={sectorFocus} />
        
        {/* Investment Criteria - AB NICHE */}
        <InvestmentCriteria criteria={investorCriteria} />
        
        {/* <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">Investment Ideas</h2>
          </div>
          <div className="p-8 text-center text-muted-foreground">
            <Lightbulb className="h-12 w-12 mx-auto mb-3 opacity-50" />
            <p>Your investment ideas will appear here</p>
          </div>
        </div> */}
      </div>
      <div className="lg:col-span-1">
        <EducationSection education={backgroundData.education} />
        <ExperienceSection experience={backgroundData.experience} />
        <ContactSection socialMedia={socialData.socialMedia} email={socialData.email} website={socialData.website} />
        <PortfolioHighlights portfolio={portfolioData} />
      </div>
    </div>
  </>
)}

        {/* Interests Tab - No interested ideas yet */}
        {activeTab === "interests" && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <div className="lg:col-span-3">
              <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">Interested Ideas</h2>
                </div>
                <div className="p-8 text-center text-muted-foreground">
                  <Target className="h-12 w-12 mx-auto mb-3 opacity-50" />
                  <p>No interested ideas yet</p>
                  <p className="text-sm mt-2">Ideas you show interest in will appear here</p>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Activity Tab - Recent Activity Only */}
        {activeTab === "activity" && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <div className="lg:col-span-3">
              <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 interact with ideas, 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">
                            <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 line-clamp-2">{activity.title}</h4>
                                  {activity.description && (
                                    <p className="text-sm text-muted-foreground mt-1 line-clamp-2">{activity.description}</p>
                                  )}
                                  {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 line-clamp-2">{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 line-clamp-2">{activity.title}</h4>
                                </>
                              )}
                              <p className="text-xs 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>
        )}
      </div>
    </main>
  </div>
);
}