"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useSelector } from "react-redux";
import { RootState } from "@/lib/store/store";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sidebar } from "@/components/dashboard/sidebar";
import { ThemeToggle } from "@/components/theme-toggle";
import { cn } from "@/lib/utils";
import {
  User,
  MapPin,
  Briefcase,
  GraduationCap,
  Link2,
  Shield,
  Bell,
  Pencil,
  X,
  Check,
  Camera,
  Globe,
  Linkedin,
  Twitter,
  ArrowLeft,
  Plus,
  Trash2,
  Loader2,
  Award,
  Building2,
  Target,
  Users,
  CircleDollarSign,
  IndianRupee,
  TrendingUp,
  FileText,
  Clock,
  AlertTriangle,
} from "lucide-react";
import {
  updateProfile,
  getBusinessProfile,
  updateBusinessProfile,
  getInvestorProfile,
  updateInvestorProfile,
  getAllAnnualIncomeRanges,
  getAllNetWorthOptions,
  getAllBusinessTypes,
  getAllCategories,
  getAllGender,
  getLabelsByScreenAndType,
  getAllAccountTypes,
  getCustomerProfile
} from "@/lib/api/client";
import { toast } from "sonner";
import ReactCrop, { centerCrop, makeAspectCrop } from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
import { useRef } from "react";
import { useDispatch } from 'react-redux';
import { updateProfileImage, updateUserAchievements, updateUserInterests, updateUserSkills , triggerPostsRefresh } from '@/lib/store/slices/userSlice';

type UserType = "individual" | "business" | "investor";

interface EditableSectionProps {
  title: string;
  icon: React.ElementType;
  children: React.ReactNode;
  editContent: React.ReactNode;
  isEditing: boolean;
  onEdit: () => void;
  onSave: () => void;
  onCancel: () => void;
  saving?: boolean;
}

// ========== SHIMMER SKELETON ==========
const shimmerStyle = `
  @keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
  }
`;

const isAge18OrAbove = (dateOfBirth: string): boolean => {
  if (!dateOfBirth) return false;
  
  let birthDate: Date;
  
  if (dateOfBirth.match(/^\d{4}-\d{2}-\d{2}$/)) {
    birthDate = new Date(dateOfBirth);
  } 
  else if (dateOfBirth.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
    const parts = dateOfBirth.split('/');
    birthDate = new Date(`${parts[2]}-${parts[1]}-${parts[0]}`);
  }
  else {
    birthDate = new Date(dateOfBirth);
  }
  
  if (isNaN(birthDate.getTime())) {
    return false;
  }
  
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age >= 18;
};

const formatDateForAPI = (dateString: string): string => {
  if (!dateString) return "";
  if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) return dateString;
  const parts = dateString.split('/');
  if (parts.length === 3 && parts[2].length === 4) {
    return `${parts[2]}-${parts[1]}-${parts[0]}`;
  }
  return dateString;
};

function ProfilePictureSkeleton() {
  useEffect(() => {
    if (typeof document !== 'undefined' && !document.querySelector('#shimmer-style')) {
      const style = document.createElement('style');
      style.id = 'shimmer-style';
      style.textContent = shimmerStyle;
      document.head.appendChild(style);
    }
  }, []);

  return (
    <div className="rounded-2xl glass glass-border p-6 overflow-hidden relative">
      <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.5s_infinite] bg-gradient-to-r from-transparent via-white/30 dark:via-white/10 to-transparent" />
      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-6">
        <div className="h-24 w-24 rounded-2xl bg-gray-300 dark:bg-gray-700"></div>
        <div className="flex-1 space-y-3">
          <div className="h-6 w-48 bg-gray-300 dark:bg-gray-700 rounded"></div>
          <div className="h-4 w-32 bg-gray-300 dark:bg-gray-700 rounded"></div>
          <div className="h-8 w-24 bg-gray-300 dark:bg-gray-700 rounded-lg"></div>
        </div>
      </div>
    </div>
  );
}

function EditableSectionSkeleton({ title, icon: Icon }: { title: string; icon: React.ElementType }) {
  return (
    <div className="rounded-2xl glass glass-border overflow-hidden relative">
      <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.5s_infinite] bg-gradient-to-r from-transparent via-white/30 dark:via-white/10 to-transparent" />
      <div className="flex items-center justify-between px-5 py-4 border-b border-border/50">
        <div className="flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-300 dark:bg-gray-700"></div>
          <div className="h-5 w-32 bg-gray-300 dark:bg-gray-700 rounded"></div>
        </div>
        <div className="h-8 w-16 bg-gray-300 dark:bg-gray-700 rounded"></div>
      </div>
      <div className="p-5 space-y-3">
        <div className="h-4 w-full bg-gray-300 dark:bg-gray-700 rounded"></div>
        <div className="h-4 w-3/4 bg-gray-300 dark:bg-gray-700 rounded"></div>
        <div className="h-4 w-1/2 bg-gray-300 dark:bg-gray-700 rounded"></div>
      </div>
    </div>
  );
}

function SettingsPageSkeleton() {
  return (
    <div className="min-h-screen bg-background">
      <Sidebar />
      <div className="lg:pl-72">
        <header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b border-border/50 glass px-4 lg:px-6">
          <div className="flex items-center gap-4">
            <div className="h-8 w-8 bg-gray-300 dark:bg-gray-700 rounded animate-pulse"></div>
            <div className="h-6 w-32 bg-gray-300 dark:bg-gray-700 rounded animate-pulse"></div>
          </div>
          <div className="h-9 w-32 bg-gray-300 dark:bg-gray-700 rounded animate-pulse"></div>
        </header>
        <main className="p-4 lg:p-6 max-w-3xl mx-auto space-y-6">
          <ProfilePictureSkeleton />
          {[1, 2, 3, 4, 5].map((i) => (
            <EditableSectionSkeleton key={i} title="Loading..." icon={User} />
          ))}
          <div className="rounded-2xl glass glass-border p-5 overflow-hidden relative">
            <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.5s_infinite] bg-gradient-to-r from-transparent via-white/30 dark:via-white/10 to-transparent" />
            <div className="h-5 w-32 bg-gray-300 dark:bg-gray-700 rounded mb-1"></div>
            <div className="h-3 w-48 bg-gray-300 dark:bg-gray-700 rounded mb-4"></div>
            <div className="h-10 w-32 bg-gray-300 dark:bg-gray-700 rounded-lg"></div>
          </div>
        </main>
      </div>
    </div>
  );
}

function ComingSoonSection({ title, icon: Icon }: { title: string; icon: React.ElementType }) {
  return (
    <div className="rounded-2xl glass glass-border overflow-hidden opacity-60">
      <div className="flex items-center justify-between px-5 py-4 border-b border-border/50 bg-secondary/20">
        <div className="flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-500/20">
            <Icon className="h-5 w-5 text-gray-500" />
          </div>
          <h3 className="font-semibold text-foreground">{title}</h3>
        </div>
        <span className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-gray-500/20 text-gray-500 text-xs">
          <Clock className="h-3 w-3" />
          Coming Soon
        </span>
      </div>
      <div className="p-5">
        <p className="text-sm text-muted-foreground text-center py-4">
          This feature is under development and will be available soon.
        </p>
      </div>
    </div>
  );
}

function EditableSection({
  title,
  icon: Icon,
  children,
  editContent,
  isEditing,
  onEdit,
  onSave,
  onCancel,
  saving = false,
}: EditableSectionProps) {
  return (
    <div className="rounded-2xl glass glass-border overflow-hidden">
      <div className="flex items-center justify-between px-5 py-4 border-b border-border/50">
        <div className="flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
            <Icon className="h-5 w-5 text-primary" />
          </div>
          <h3 className="font-semibold text-foreground">{title}</h3>
        </div>
        {!isEditing ? (
          <Button variant="ghost" size="sm" onClick={onEdit} className="gap-2 cursor-pointer">
            <Pencil className="h-4 w-4" />
            Edit
          </Button>
        ) : (
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="sm" onClick={onCancel} className="cursor-pointer">
              <X className="h-4 w-4" />
            </Button>
            <Button size="sm" onClick={onSave} className="gap-2 cursor-pointer" disabled={saving}>
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
              {saving ? "Saving..." : "Save"}
            </Button>
          </div>
        )}
      </div>
      <div className="p-5">{isEditing ? editContent : children}</div>
    </div>
  );
}

const formatDateForInput = (dateString: string) => {
  if (!dateString) return "";
  if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) return dateString;
  const parts = dateString.split(/[/-]/);
  if (parts.length === 3) {
    if (parts[0].length === 2 && parts[1].length === 2 && parts[2].length === 4) {
      return `${parts[2]}-${parts[1]}-${parts[0]}`;
    }
    if (parts[1].length === 2 && parts[0].length === 2) {
      return `${parts[2]}-${parts[0]}-${parts[1]}`;
    }
  }
  return dateString;
};

const formatDateForDisplay = (dateString: string) => {
  if (!dateString) return "";
  if (dateString.match(/^\d{2}\/\d{2}\/\d{4}$/)) return dateString;
  const parts = dateString.split('-');
  if (parts.length === 3) {
    return `${parts[2]}/${parts[1]}/${parts[0]}`;
  }
  return dateString;
};

export default function ProfileSettingsPage() {
  const dispatch = useDispatch();
  const { accessToken, currentCustomer } = useSelector((state: RootState) => state.user);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editingSection, setEditingSection] = useState<string | null>(null);
const [sectorFocus, setSectorFocus] = useState<Array<{ name: string }>>([]);
const [tempSectorFocus, setTempSectorFocus] = useState<Array<{ name: string }>>([]);
const [newSector, setNewSector] = useState({ name: "" });
  


  // ========== DYNAMIC LABELS ==========
  const [labels, setLabels] = useState<Record<string, string>>({});
  const [sectionTitles, setSectionTitles] = useState<Record<string, string>>({});
  const [labelsLoading, setLabelsLoading] = useState(true);
  const [labelsError, setLabelsError] = useState<string | null>(null);

  // Dropdown options
  const [incomeRanges, setIncomeRanges] = useState<Array<{ _id: string; rangeName: string }>>([]);
  const [netWorthOptions, setNetWorthOptions] = useState<Array<{ _id: string; netWorthName: string }>>([]);
  const [businessTypes, setBusinessTypes] = useState<Array<{ _id: string; businessTypeName: string; businessTypeSlug: string }>>([]);
  const [investorEducation, setInvestorEducation] = useState<Array<{ degree: string; institution: string; year: string }>>([]);
  const [tempInvestorEducation, setTempInvestorEducation] = useState<Array<{ degree: string; institution: string; year: string }>>([]);
  const [newInvestorEducation, setNewInvestorEducation] = useState({ degree: "", institution: "", year: "" });
 const [investorExperience, setInvestorExperience] = useState<Array<{ 
  role: string; 
  company: string; 
  fromYear: string; 
  toYear: string; 
}>>([]);

const [tempInvestorExperience, setTempInvestorExperience] = useState<Array<{ 
  role: string; 
  company: string; 
  fromYear: string; 
  toYear: string; 
}>>([]);
  const [newInvestorExperience, setNewInvestorExperience] = useState({ role: "", company: "", duration: "" });
const [qualifications, setQualifications] = useState<Array<{ 
  type: string; 
  title: string; 
  institution: string; 
  year: string;
  fromYear?: string;      // ✅ ADD
  toYear?: string;        // ✅ ADD
  isCurrent?: boolean;    // ✅ ADD
}>>([]);

// tempQualifications state - UPDATE THIS
const [tempQualifications, setTempQualifications] = useState<Array<{ 
  type: string; 
  title: string; 
  institution: string; 
  year: string;
  fromYear?: string;      // ✅ ADD
  toYear?: string;        // ✅ ADD
  isCurrent?: boolean;    // ✅ ADD
}>>([]);
  const [allCategories, setAllCategories] = useState<any[]>([]);
  const [genderOptions, setGenderOptions] = useState<Array<{ _id: string; genderValue: string; sortId: number }>>([]);

  // Image states
  const fileInputRef = useRef<HTMLInputElement>(null);
  const imgRef = useRef<HTMLImageElement>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [cropModalOpen, setCropModalOpen] = useState(false);
  const [crop, setCrop] = useState<any>();
  const [completedCrop, setCompletedCrop] = useState<any>(null);
  const [imgSrc, setImgSrc] = useState("");
  const [uploadingPhoto, setUploadingPhoto] = useState(false);

  const [businessIdeasLookingFor, setBusinessIdeasLookingFor] = useState<string[]>([]);
const [newBusinessIdea, setNewBusinessIdea] = useState("");

const [searchTerm, setSearchTerm] = useState("");



  // Get user type
  const customer = currentCustomer?.customer || currentCustomer;
  const userType = customer?.isBusinessUser ? "business" : customer?.isInvestor ? "investor" : "individual";
  // Profile state
  const [profile, setProfile] = useState({
    fullName: "", userName: "", aboutMe: "", location: "", website: "", linkedin: "", twitter: "",
    imageURL: "", designation: "", gender: "", address: "", phone: "", dateOfBirth: "", tempDateOfBirth: "",
    socialMedia: [] as { link: string; type: string; userName?: string }[],
  });
  const [tempProfile, setTempProfile] = useState(profile);

  // Individual states
  const [skills, setSkills] = useState<string[]>([]);
  const [tempSkills, setTempSkills] = useState<string[]>([]);
  const [newSkill, setNewSkill] = useState("");
  const [interests, setInterests] = useState<string[]>([]);
  const [tempInterests, setTempInterests] = useState<string[]>([]);
  const [newInterest, setNewInterest] = useState("");
  const [achievements, setAchievements] = useState<{ title: string }[]>([]);
  const [tempAchievements, setTempAchievements] = useState<{ title: string }[]>([]);
  const [lookingFor, setLookingFor] = useState<string[]>([]);
  const [newLookingFor, setNewLookingFor] = useState("");
  const [originalLookingFor, setOriginalLookingFor] = useState<string[]>([]);


  // Business states
  const [companyInfo, setCompanyInfo] = useState({
    companyName: "", businessType: "", industry: "", founded: "", size: "", description: "",
    headquarters: "", annualRevenue: "", whatWeOffer: [] as { title: string; description: string }[],
  });
  const [tempCompanyInfo, setTempCompanyInfo] = useState(companyInfo);

  // Investor states
  const [investorInfo, setInvestorInfo] = useState({
    businessName: "", annualIncomeRange: "", netWorth: "", investorType: "Angel Investor",
    investmentRange: "10L - 1Cr", totalInvested: "5Cr+", activeDeals: "8",
  });
  const [tempInvestorInfo, setTempInvestorInfo] = useState(investorInfo);
  const [keyPeople, setKeyPeople] = useState([
    { id: 1, name: "Rajesh Kumar", role: "CEO", avatar: "RK" },
    { id: 2, name: "Priya Singh", role: "CTO", avatar: "PS" },
  ]);

  useEffect(() => {
  const fetchAccountTypeLabel = async () => {
    try {
      const result = await getAllAccountTypes(process.env.NEXT_PUBLIC_SECURITY_KEY);
      if (result.success && result.data) {
        const typeMap: Record<string, string> = {
          individual: "innovator",
          business: "business",
          investor: "investor"
        };
        const apiTypeId = typeMap[userType] || userType;
        const matched = result.data.find((type: any) => type.id === apiTypeId);
        if (matched) {
          setAccountTypeLabel(matched.label);
        }
      }
    } catch (error) {
      console.error("Error fetching account type label:", error);
    }
  };
  fetchAccountTypeLabel();
}, [userType]);

  // Crop functions
  function getCroppedImg(image: HTMLImageElement, crop: any, fileName: string): Promise<Blob> {
    const canvas = document.createElement("canvas");
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext("2d")!;
    ctx.drawImage(image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width, crop.height);
    return new Promise((resolve, reject) => {
      canvas.toBlob((blob) => {
        if (!blob) { reject(new Error("Canvas is empty")); return; }
        resolve(blob);
      }, "image/jpeg", 0.95);
    });
  }

  const onImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const { width, height } = e.currentTarget;
    setCrop(centerCrop(makeAspectCrop({ unit: "%", width: 90 }, 1, width, height), width, height));
  };

  const uploadImageHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    if (file.size > 1 * 1024 * 1024) { toast.error("Image size should not exceed 1 MB"); return; }
    if (!file.type.startsWith("image/")) { toast.error("Please select an image file"); return; }
    const reader = new FileReader();
    reader.addEventListener("load", () => { setImgSrc(reader.result?.toString() || ""); setCropModalOpen(true); });
    reader.readAsDataURL(file);
  };

  const applyCrop = async () => {
    if (imgRef.current && completedCrop?.width && completedCrop?.height) {
      try {
        const blob = await getCroppedImg(imgRef.current, completedCrop, "profile.jpg");
        const url = URL.createObjectURL(blob);
        setImagePreview(url);
        const file = new File([blob], "profile.jpg", { type: "image/jpeg", lastModified: Date.now() });
        setImageFile(file);
        setCropModalOpen(false);
        setImgSrc("");
        setCrop(undefined);
        setCompletedCrop(null);
        toast.success("Image cropped!");
      } catch (err) {
        toast.error("Unable to crop image. Please try again.");
      }
    }
  };

  const cancelCrop = () => {
    setCropModalOpen(false);
    setImgSrc("");
    setCrop(undefined);
    setCompletedCrop(null);
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const getProfileUrl = () => {
  console.log("🔍 currentCustomer:", currentCustomer);
  console.log("🔍 userType:", userType);
  
  if (!currentCustomer) return `/profile/innovator`;
  
  const userId = currentCustomer?.customer?._id || currentCustomer?._id;
  console.log("🔍 userId:", userId);
  
  let urlType = "";
  if (userType === "individual") {
    urlType = "innovator";
  } else if (userType === "business") {
    urlType = "business";
  } else if (userType === "investor") {
    urlType = "investor";
  }
  
  const finalUrl = `/profile/${urlType}/${userId || ''}`;
  console.log("🔍 finalUrl:", finalUrl);
  
  return finalUrl;
};

 const saveProfilePhoto = async () => {
  if (!imageFile) return;
  try {
    setUploadingPhoto(true);
    const formData = new FormData();
    formData.append("imageURL", imageFile);
    let response;
    if (userType === "business") {
      response = await updateBusinessProfile(formData, "", accessToken!);
    } else if (userType === "investor") {
      const investorFormData = new FormData();
      investorFormData.append("imageURL", imageFile);
      response = await updateInvestorProfile(investorFormData, accessToken!);
    } else {
      response = await updateProfile(formData, accessToken!);
    }
    if (response.success) {
      toast.success("Profile photo updated successfully!");
      const newImageURL = response.data?.imageURL || response.data?.data?.imageURL;
      if (newImageURL) {
        setProfile(prev => ({ ...prev, imageURL: newImageURL }));
        setTempProfile(prev => ({ ...prev, imageURL: newImageURL }));
        dispatch(updateProfileImage(newImageURL));
        
        // ✅ TRIGGER POSTS REFRESH - This will refresh IdeaFeed
        dispatch(triggerPostsRefresh());
      }
      setImagePreview(null);
      setImageFile(null);
    } else {
      toast.error(response.message || "Failed to update photo");
    }
  } catch (err) {
    console.error("Error saving photo:", err);
    toast.error("Failed to save photo");
  } finally {
    setUploadingPhoto(false);
  }
};

  // Fetch dropdown options
  useEffect(() => {
    const fetchDropdownOptions = async () => {
      try {
        const [incomeResponse, netWorthResponse, businessTypesResponse, categoriesResponse, genderResponse] = await Promise.all([
          getAllAnnualIncomeRanges(),
          getAllNetWorthOptions(),
          getAllBusinessTypes(),
          getAllCategories(),
          getAllGender(),
        ]);

        if (incomeResponse?.success) {
          const incomeData = incomeResponse.data?.data || incomeResponse.data || [];
          setIncomeRanges(incomeData);
        } else {
          setIncomeRanges([]);
        }

        if (netWorthResponse?.success) {
          const netWorthData = netWorthResponse.data?.data || netWorthResponse.data || [];
          setNetWorthOptions(netWorthData);
        } else {
          setNetWorthOptions([]);
        }

        if (businessTypesResponse?.success && businessTypesResponse?.data) {
          const typesData = Array.isArray(businessTypesResponse.data) ? businessTypesResponse.data : [];
          setBusinessTypes(typesData);
        } else {
          setBusinessTypes([]);
        }
        
        if (categoriesResponse.success && categoriesResponse.data) {
          setAllCategories(categoriesResponse.data);
        }
        
        if (genderResponse.success && genderResponse.data) {
          const sortedGender = [...genderResponse.data].sort((a, b) => a.sortId - b.sortId);
          setGenderOptions(sortedGender);
        }
      } catch (error) {
        console.error("Error fetching dropdown options:", error);
      }
    };
    fetchDropdownOptions();
  }, []);

  // ========== FETCH DYNAMIC LABELS ==========
  useEffect(() => {
    const fetchLabels = async () => {
      if (!accessToken) return;
      
      setLabelsLoading(true);
      setLabelsError(null);
      try {
        let screenName = "";
        if (userType === "individual") {
          screenName = "innovatorEdit";
        } else if (userType === "business") {
          screenName = "businessEdit";
        } else if (userType === "investor") {
          screenName = "investorEdit";
        }

        const response = await getLabelsByScreenAndType(screenName, "");
        
        if (response.success && response.data && response.data.length > 0) {
          const labelsMap: Record<string, string> = {};
          const sectionMap: Record<string, string> = {};
          
          response.data.forEach((label: any) => {
            labelsMap[label.label] = label.value;
            if (label.label === "section_title") {
              sectionMap[label.section] = label.value;
            }
          });
          
          setLabels(labelsMap);
          setSectionTitles(sectionMap);
        } else {
          setLabelsError(response.message || `No labels found for ${userType}`);
        }
      } catch (error) {
        console.error("Error fetching labels:", error);
        setLabelsError("Failed to load labels from server");
      } finally {
        setLabelsLoading(false);
      }
    };
    
    if (accessToken && userType) {
      fetchLabels();
    }
  }, [accessToken, userType]);

  const getLabel = (key: string): string => {
    return labels[key] || key;
  };

  const getSectionTitle = (section: string): string => {
    return sectionTitles[section] || section.replace(/_/g, " ").replace(/\b\w/g, l => l.toUpperCase());
  };

  // Fetch profile based on user type
  useEffect(() => {
    if (accessToken) {
      if (userType === "individual") fetchIndividualProfile();
      else if (userType === "business") fetchBusinessProfile();
      else if (userType === "investor") fetchInvestorProfile();
    }
  }, [accessToken, userType]);

 const fetchIndividualProfile = async () => {
  try {
    setLoading(true);
    
    // ✅ Direct API call karo - Business/Investor ki tarah
    const response = await getCustomerProfile(accessToken!);
    
    if (response.success && response.data) {
      const data = response.data;
      
      let linkedin = "", twitter = "", website = "";
      if (data.socialMedia && Array.isArray(data.socialMedia)) {
        data.socialMedia.forEach((social: any) => {
          if (social.type === "linkedin") linkedin = social.link;
          if (social.type === "twitter") twitter = social.link;
          if (social.type === "website") website = social.link;
        });
      }
      
      const formattedDateForInput = formatDateForInput(data.dateOfBirth || "");
      const formattedDateForDisplay = formatDateForDisplay(data.dateOfBirth || "");
      const addressFromApi = data.address || "";
      
      setProfile({
        fullName: data.fullName || "", userName: data.userName?.replace("@", "") || "",
        aboutMe: data.aboutMe || "", location: data.country || "", website: website || "",
         linkedin: linkedin || "", twitter: twitter || "",
        imageURL: data.imageURL || "", designation: data.designation || "", gender: data.gender || "",
        phone: data.phone || "", dateOfBirth: formattedDateForDisplay, tempDateOfBirth: formattedDateForInput,
        socialMedia: data.socialMedia || [],
        address: addressFromApi,
        
      });
      
      setTempProfile({
        fullName: data.fullName || "", userName: data.userName?.replace("@", "") || "",
        aboutMe: data.aboutMe || "", location: data.country || "", website: website || "",
         linkedin: linkedin || "", twitter: twitter || "",
        imageURL: data.imageURL || "", designation: data.designation || "", gender: data.gender || "",
        phone: data.phone || "", dateOfBirth: formattedDateForDisplay, tempDateOfBirth: formattedDateForInput,
        socialMedia: data.socialMedia || [],
         address: addressFromApi, 
      });
      
      setSkills(data.skills || []);
      setTempSkills(data.skills || []);
      setInterests(data.interests || []);
      setTempInterests(data.interests || []);
      setAchievements(data.achievements || []);
      setTempAchievements(data.achievements || []);
      
      const mappedQualifications = (data.qualifications || []).map((q: any) => ({
        type: q.type,
        title: q.title || "",
        institution: q.institution || "",
        year: q.year || "",
        fromYear: q.fromYear || "",
        toYear: q.toYear || "",
        isCurrent: q.isCurrent || false
      }));
      
      setQualifications(mappedQualifications);
      setTempQualifications(mappedQualifications);
      
      const postCategories = data.postCategories || [];
      const categoryNames = postCategories.map((cat: any) => typeof cat === 'object' ? cat.mainCategoryName : cat);
      setLookingFor(categoryNames);
      
      dispatch(updateUserSkills(data.skills || []));
      dispatch(updateUserInterests(data.interests || []));
      dispatch(updateUserAchievements(data.achievements || []));
    }
  } catch (error) {
    console.error("Error fetching individual profile:", error);
  } finally {
    setLoading(false);
  }
};

  const fetchBusinessProfile = async () => {
    try {
      setLoading(true);
      const response = await getBusinessProfile();
      if (response.success && response.data) {
        const business = response.data.businessProfile || response.data;
        const formattedDateForDisplay = formatDateForDisplay(business.personalInfo?.dateOfBirth || "");
        const formattedDateForInput = formatDateForInput(business.personalInfo?.dateOfBirth || "");
        const websiteUrl = business.organization?.website || 
                          business.personalInfo?.socialMedia?.find((s: any) => s.type === "website")?.link || "";
        setProfile({
          fullName: business.personalInfo?.fullName || "", userName: business.personalInfo?.userName?.replace("@", "") || "",
          aboutMe: business.personalInfo?.aboutMe || "", location: business.personalInfo?.country || "",
          website: websiteUrl, linkedin: business.personalInfo?.socialMedia?.find((s: any) => s.type === "linkedin")?.link || "",
          twitter: business.personalInfo?.socialMedia?.find((s: any) => s.type === "twitter")?.link || "",
          imageURL: business.personalInfo?.imageURL || "", designation: business.personalInfo?.designation || "",
          gender: business.personalInfo?.gender || "", socialMedia: business.personalInfo?.socialMedia || [],
          phone: business.personalInfo?.phone || "", dateOfBirth: formattedDateForDisplay,
          tempDateOfBirth: formattedDateForInput, address: business.personalInfo?.address || "",
        });
        setTempProfile({
          fullName: business.personalInfo?.fullName || "", userName: business.personalInfo?.userName?.replace("@", "") || "",
          aboutMe: business.personalInfo?.aboutMe || "", location: business.personalInfo?.country || "",
          website: websiteUrl, linkedin: business.personalInfo?.socialMedia?.find((s: any) => s.type === "linkedin")?.link || "",
          twitter: business.personalInfo?.socialMedia?.find((s: any) => s.type === "twitter")?.link || "",
          imageURL: business.personalInfo?.imageURL || "", designation: business.personalInfo?.designation || "",
          gender: business.personalInfo?.gender || "", socialMedia: business.personalInfo?.socialMedia || [],
          phone: business.personalInfo?.phone || "", dateOfBirth: formattedDateForDisplay,
          tempDateOfBirth: formattedDateForInput, address: business.personalInfo?.address || "",
        });
        setCompanyInfo({
          companyName: business.organization?.name || "", businessType: business.organization?.type || "",
          description: business.organization?.description || "", industry: business.organization?.industry || "",
          founded: business.organization?.foundedYear?.toString() || "", size: business.organization?.employeeCount || "",
          headquarters: business.organization?.headquarters || "", annualRevenue: business.organization?.annualRevenue || "",
          whatWeOffer: business.organization?.whatWeOffer || [],
        });
        setTempCompanyInfo({
          companyName: business.organization?.name || "", businessType: business.organization?.type || "",
          description: business.organization?.description || "", industry: business.organization?.industry || "",
          founded: business.organization?.foundedYear?.toString() || "", size: business.organization?.employeeCount || "",
          headquarters: business.organization?.headquarters || "", annualRevenue: business.organization?.annualRevenue || "",
          whatWeOffer: business.organization?.whatWeOffer || [],
        });
        const postCategories = business.personalInfo?.postCategories || [];
      const categoryNames = postCategories.map((cat: any) => typeof cat === 'object' ? cat.mainCategoryName : cat);
      setLookingFor(categoryNames);
      
      // ✅ NEW: Ideas We're Looking For (separate field)
      setBusinessIdeasLookingFor(business.ideasLookingFor || []);
      }
    } catch (error) {
      console.error("Error fetching business profile:", error);
    } finally {
      setLoading(false);
    }
  };

const fetchInvestorProfile = async () => {
  try {
    setLoading(true);
    const response = await getInvestorProfile();
   
    if (response.success && response.data) {
      const investor = response.data;
      const personalInfo = investor.personalInfo || {};
      const investorInfoData = investor.investorInfo || {};
      const formattedDateForDisplay = formatDateForDisplay(personalInfo.dateOfBirth || "");
      const formattedDateForInput = formatDateForInput(personalInfo.dateOfBirth || "");
      const displayBusinessName = investorInfoData.businessName || personalInfo.fullName || "";

      console.log("investorInfoData full:", investorInfoData);
      console.log("sectorFocus from investorInfoData:", investorInfoData.sectorFocus)
      
      let userName = personalInfo.userName || "";
      if (userName.startsWith('@')) {
        userName = userName.substring(1);
      }

      // ✅ Extract social links properly
      const socialMediaData = personalInfo.socialMedia || [];
      let website = "", linkedin = "", twitter = "";
      
      socialMediaData.forEach((social: any) => {
        if (social.type === "website") website = social.link || "";
        if (social.type === "linkedin") linkedin = social.link || "";
        if (social.type === "twitter") twitter = social.link || "";
      });

      setProfile({
        fullName: displayBusinessName,
        userName: userName,
        aboutMe: personalInfo.aboutMe || "", 
        location: personalInfo.country || "",
        website: website,
        linkedin: linkedin,
        twitter: twitter,
        imageURL: personalInfo.imageURL || "", 
        designation: personalInfo.designation || "",
        gender: personalInfo.gender || "", 
        socialMedia: socialMediaData,
        phone: personalInfo.phone || "", 
        dateOfBirth: formattedDateForDisplay,
        tempDateOfBirth: formattedDateForInput, 
        address: personalInfo.address || "",
      });
      
      setTempProfile({
        fullName: personalInfo.fullName || "", 
        userName: personalInfo.userName?.replace("@", "") || "",
        aboutMe: personalInfo.aboutMe || "", 
        location: personalInfo.country || "",
        website: website,
        linkedin: linkedin,
        twitter: twitter,
        imageURL: personalInfo.imageURL || "", 
        designation: personalInfo.designation || "",
        gender: personalInfo.gender || "", 
        socialMedia: socialMediaData,
        phone: personalInfo.phone || "", 
        dateOfBirth: formattedDateForDisplay,
        tempDateOfBirth: formattedDateForInput, 
        address: personalInfo.address || "",
      });
      
      setInvestorInfo({
        businessName: investorInfoData.businessName || "", 
        annualIncomeRange: investorInfoData.annualIncomeRange || "",
        netWorth: investorInfoData.netWorth || "", 
        investorType: investorInfoData.investorType || "Angel Investor",
        investmentRange: investorInfoData.investmentRange || "10L - 1Cr",
        totalInvested: investorInfoData.stats?.totalInvested || "5Cr+",
        activeDeals: investorInfoData.stats?.activeDeals?.toString() || "8",
      });
      setTempInvestorInfo({
        businessName: investorInfoData.businessName || "", 
        annualIncomeRange: investorInfoData.annualIncomeRange || "",
        netWorth: investorInfoData.netWorth || "", 
        investorType: investorInfoData.investorType || "Angel Investor",
        investmentRange: investorInfoData.investmentRange || "10L - 1Cr",
        totalInvested: investorInfoData.stats?.totalInvested || "5Cr+",
        activeDeals: investorInfoData.stats?.activeDeals?.toString() || "8",
      });
      
      // ✅ Fetch education and experience
      const educationData = (personalInfo.education || []).map((edu: any) => ({
        degree: edu.degree || edu.title || "",
        institution: edu.institution || "",
        fromYear: edu.fromYear || "",
        toYear: edu.toYear || "",
      }));
      
      const experienceData = (personalInfo.experience || []).map((exp: any) => ({
        role: exp.role || exp.title || "",
        company: exp.company || "",
        fromYear: exp.fromYear || "",
        toYear: exp.toYear || "",
      }));
      
      setInvestorEducation(educationData);
      setTempInvestorEducation(educationData);
      setInvestorExperience(experienceData);
      setTempInvestorExperience(experienceData);
     setSectorFocus(investorInfoData.sectorFocus || []);



      // ✅ ✅ ✅ ADD THIS - Fetch categories for investor
      const postCategories = personalInfo.postCategories || [];
      const categoryNames = postCategories.map((cat: any) => {
        if (typeof cat === 'object' && cat.mainCategoryName) {
          return cat.mainCategoryName;
        } else if (typeof cat === 'string') {
          return cat;
        }
        return cat;
      });
      setLookingFor(categoryNames);
    }
  } catch (error) {
    console.error("Error fetching investor profile:", error);
  } finally {
    setLoading(false);
  }
};
  const startEditing = (section: string) => {
    if (section === "company") setTempCompanyInfo(companyInfo);
    else if (section === "investorProfile") setTempInvestorInfo(investorInfo);
    else if (editingSection === "sectorFocus") {
  setTempSectorFocus([...sectorFocus]);
}
    else if (section === "investorEducation") setTempInvestorEducation(investorEducation);
    else if (section === "investorExperience") setTempInvestorExperience(investorExperience);
     else if (section === "investorLookingFor") {
    // ✅ Store original categories before editing
    setOriginalLookingFor([...lookingFor]);
    setEditingSection(section);
    return;
  }
    else if (section === "individualEducation") setTempQualifications(qualifications);
    else if (section === "individualExperience") setTempQualifications(qualifications);
    else if (section === "skills") setTempSkills(skills);
    else if (section === "interests") setTempInterests(interests);
    else if (section === "achievements") setTempAchievements(achievements);
    else if (section === "whatWeOffer") setTempCompanyInfo(companyInfo);
    else setTempProfile(profile);
    setEditingSection(section);
  };

  const saveBusinessIdeasLookingFor = async () => {
  // Agar input field mein kuch likha hai but add nahi kiya
  if (newBusinessIdea.trim() !== "") {
    toast.error(`Please click the + button to add "${newBusinessIdea}" before saving`);
    return;
  }
  
  try {
    setSaving(true);
    const updateData = { ideasLookingFor: businessIdeasLookingFor };
    const response = await updateBusinessProfile(updateData, "", accessToken!);
    if (response.success) { 
      toast.success("Ideas We're Looking For updated successfully"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

const saveSectorFocus = async () => {
  try {
    setSaving(true);
    const formData = new FormData();
    formData.append("sectorFocus", JSON.stringify(tempSectorFocus));
    const response = await updateInvestorProfile(formData, accessToken!);
    if (response.success) { 
      setSectorFocus(tempSectorFocus); 
      toast.success("Sector focus updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};


  const saveBasicInfo = async () => {
    const dateToValidate = tempProfile.dateOfBirth || tempProfile.tempDateOfBirth;
    if (dateToValidate && !isAge18OrAbove(dateToValidate)) {
      toast.error("You must be 18 years or older to update your profile");
      return;
    }
  
    try {
      setSaving(true);
      const formattedDate = tempProfile.dateOfBirth || 
        (tempProfile.tempDateOfBirth ? formatDateForDisplay(tempProfile.tempDateOfBirth) : "");

      if (userType === "business") {
        const updateData = {
          fullName: tempProfile.fullName, aboutMe: tempProfile.aboutMe, designation: tempProfile.designation,
          gender: tempProfile.gender, phone: tempProfile.phone, dateOfBirth: formattedDate,
          links: JSON.stringify([tempProfile.website, tempProfile.linkedin, tempProfile.twitter].filter(Boolean))
        };
        const response = await updateBusinessProfile(updateData, "", accessToken!);
        if (response.success) { setProfile(tempProfile); toast.success("Profile updated"); setEditingSection(null); }
        else toast.error(response.message);
      } else if (userType === "investor") {
        const formData = new FormData();
        formData.append("fullName", tempProfile.fullName);
        formData.append("aboutMe", tempProfile.aboutMe);
        if (tempProfile.designation) formData.append("designation", tempProfile.designation);
        if (tempProfile.gender) formData.append("gender", tempProfile.gender);
        if (tempProfile.phone) formData.append("phone", tempProfile.phone);
        if (tempProfile.dateOfBirth) formData.append("dateOfBirth", formattedDate);
        const socialLinks = [tempProfile.website, tempProfile.linkedin, tempProfile.twitter].filter(Boolean);
        formData.append("links", JSON.stringify(socialLinks));
        const response = await updateInvestorProfile(formData, accessToken!);
        if (response.success) { setProfile(tempProfile); toast.success("Profile updated"); setEditingSection(null); }
        else toast.error(response.message);
      } else {
        const formData = new FormData();
        formData.append("fullName", tempProfile.fullName);
        formData.append("aboutMe", tempProfile.aboutMe);
        if (tempProfile.designation) formData.append("designation", tempProfile.designation);
        if (tempProfile.gender) formData.append("gender", tempProfile.gender);
        if (tempProfile.phone) formData.append("phone", tempProfile.phone);
        if (formattedDate) formData.append("dateOfBirth", formattedDate);

        const socialMedia = [];
        if (tempProfile.website) socialMedia.push({ link: tempProfile.website, type: "website" });
        if (tempProfile.linkedin) socialMedia.push({ link: tempProfile.linkedin, type: "linkedin" });
        if (tempProfile.twitter) socialMedia.push({ link: tempProfile.twitter, type: "twitter" });
        formData.append("links", JSON.stringify(socialMedia.map(s => s.link)));
        const response = await updateProfile(formData, accessToken!);
        if (response.success) { setProfile(tempProfile); toast.success("Profile updated"); setEditingSection(null); }
        else toast.error(response.message);
      }
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

  const saveInvestorLookingFor = async () => {
  try {
    setSaving(true);
    const selectedCategoryIds = lookingFor.map((categoryName) => {
      const found = allCategories.find((cat: any) => cat.mainCategoryName === categoryName);
      return found?._id;
    }).filter(Boolean);
    
    const formData = new FormData();
    formData.append("postCategories", JSON.stringify(selectedCategoryIds));
    const response = await updateInvestorProfile(formData, accessToken!);
    
    if (response.success) { 
      toast.success("Categories updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    console.error("Error saving categories:", error);
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

const saveLocation = async () => {
  try {
    setSaving(true);
    if (userType === "business") {
      const response = await updateBusinessProfile({ country: tempProfile.location }, "", accessToken!);
      if (response.success) { setProfile(tempProfile); toast.success("Location updated"); setEditingSection(null); }
    } else if (userType === "investor") {
      const formData = new FormData();
      formData.append("country", tempProfile.location);
      formData.append("address", tempProfile.address || "");
      const response = await updateInvestorProfile(formData, accessToken!);
      console.log("Investor location update response:", response);
      if (response.success) { 
        setProfile(tempProfile); 
        toast.success("Location updated"); 
        setEditingSection(null); 
      } else {
        toast.error(response.message);
      }
    } else {
      const formData = new FormData();
      formData.append("country", tempProfile.location);
      formData.append("address", tempProfile.address || "");
      const response = await updateProfile(formData, accessToken!);
      if (response.success) { setProfile(tempProfile); toast.success("Location updated"); setEditingSection(null); }
    }
  } catch (error) { 
    console.error("Error saving location:", error);
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};


const saveSocialLinks = async () => {
  try {
    setSaving(true);
    
    // Build social media array
    const socialMedia = [];
    if (tempProfile.website) socialMedia.push({ link: tempProfile.website, type: "website" });
    if (tempProfile.linkedin) socialMedia.push({ link: tempProfile.linkedin, type: "linkedin" });
    if (tempProfile.twitter) socialMedia.push({ link: tempProfile.twitter, type: "twitter" });
    
    let response;
    
    // ✅ INVESTOR KE LIYE updateInvestorProfile USE KARO
    if (userType === "investor") {
      const formData = new FormData();
      formData.append("socialMedia", JSON.stringify(socialMedia));
      response = await updateInvestorProfile(formData, accessToken!);
      console.log("Investor social links response:", response);
    } 
    // ✅ BUSINESS KE LIYE updateBusinessProfile USE KARO
    else if (userType === "business") {
      const updateData = { socialMedia: socialMedia };
      response = await updateBusinessProfile(updateData, "", accessToken!);
      console.log("Business social links response:", response);
    } 
    // ✅ CUSTOMER KE LIYE updateProfile USE KARO
    else {
      const formData = new FormData();
      formData.append("socialMedia", JSON.stringify(socialMedia));
      response = await updateProfile(formData, accessToken!);
      console.log("Customer social links response:", response);
    }
    
    if (response?.success) { 
      setProfile(tempProfile);
      toast.success("Social links updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response?.message || "Failed to update social links");
    }
  } catch (error) { 
    console.error("Error saving social links:", error);
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

  const saveCompanyInfo = async () => {
    try {
      setSaving(true);
      const updateData = {
        organization: {
          name: tempCompanyInfo.companyName, type: tempCompanyInfo.businessType,
          description: tempCompanyInfo.description, industry: tempCompanyInfo.industry,
          foundedYear: parseInt(tempCompanyInfo.founded) || undefined, employeeCount: tempCompanyInfo.size,
          headquarters: tempCompanyInfo.headquarters, annualRevenue: tempCompanyInfo.annualRevenue,
        },
      };
      const response = await updateBusinessProfile(updateData, "", accessToken!);
      if (response.success) { setCompanyInfo(tempCompanyInfo); toast.success("Company info updated"); setEditingSection(null); }
      else toast.error(response.message);
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

  const saveWhatWeOffer = async () => {
    try {
      setSaving(true);
      const updateData = { whatWeOffer: tempCompanyInfo.whatWeOffer };
      const response = await updateBusinessProfile(updateData, "", accessToken!);
      if (response.success) { setCompanyInfo(tempCompanyInfo); toast.success("What We Offer updated"); setEditingSection(null); }
      else toast.error(response.message);
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

  const saveLookingFor = async () => {
    try {
      setSaving(true);
      const selectedCategoryIds = lookingFor.map((categoryName) => {
        const found = allCategories.find((cat: any) => cat.mainCategoryName === categoryName);
        return found?._id;
      }).filter(Boolean);
      
      if (userType === "business") {
        const response = await updateBusinessProfile({ postCategories: selectedCategoryIds }, "", accessToken!);
        if (response.success) { toast.success("Categories updated"); setEditingSection(null); }
        else toast.error(response.message);
      } else {
        const formData = new FormData();
        formData.append("postCategories", JSON.stringify(selectedCategoryIds));
        const response = await updateProfile(formData, accessToken!);
        if (response.success) { toast.success("Categories updated"); setEditingSection(null); }
        else toast.error(response.message);
      }
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

  // In EditableSection for skills - update the save function
const saveSkills = async () => {
   // ✅ Agar input field mein kuch likha hai but add nahi kiya
  if (newSkill.trim() !== "") {
    toast.error(`Please click the + button to add "${newSkill}" before saving`);
    return;
  }
  
  // ✅ Agar koi skill add nahi ki hai
  if (tempSkills.length === 0) {
    toast.error("Please add at least one skill before saving");
    return;
  }
  
  try {
    setSaving(true);
    const formData = new FormData();
    formData.append("skills", JSON.stringify(tempSkills));
    const response = await updateProfile(formData, accessToken!);
    if (response.success) { 
      setSkills(tempSkills); 
      dispatch(updateUserSkills(tempSkills)); 
      toast.success("Skills updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

 const saveInterests = async () => {
   // ✅ Agar input field mein kuch likha hai but add nahi kiya
  if (newInterest.trim() !== "") {
    toast.error(`Please click the + button to add "${newInterest}" before saving`);
    return;
  }
  
  // ✅ Agar koi interest add nahi ki hai
  if (tempInterests.length === 0) {
    toast.error("Please add at least one interest before saving");
    return;
  }
  
  try {
    setSaving(true);
    const formData = new FormData();
    formData.append("interests", JSON.stringify(tempInterests));
    const response = await updateProfile(formData, accessToken!);
    if (response.success) { 
      setInterests(tempInterests); 
      dispatch(updateUserInterests(tempInterests)); 
      toast.success("Interests updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

  const saveAchievements = async () => {
    try {
      setSaving(true);
      const formData = new FormData();
      formData.append("achievements", JSON.stringify(tempAchievements));
      const response = await updateProfile(formData, accessToken!);
      if (response.success) { setAchievements(tempAchievements); dispatch(updateUserAchievements(tempAchievements)); toast.success("Achievements updated"); setEditingSection(null); }
      else toast.error(response.message);
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

 const saveQualifications = async () => {
  try {
    setSaving(true);
    
    // ✅ Filter out empty entries
    const filteredQualifications = tempQualifications.filter(q => {
      if (q.type === "education") {
        return q.title?.trim() !== "" || q.institution?.trim() !== "";
      }
      if (q.type === "experience") {
        return q.title?.trim() !== "" || q.institution?.trim() !== "";
      }
      return false;
    });
    
    // ✅ Format with all fields
    const formattedQualifications = filteredQualifications.map(q => ({
      type: q.type,
      title: q.title,
      institution: q.institution,
      fromYear: q.fromYear || "",
      toYear: q.isCurrent ? "Present" : (q.toYear || ""),
      isCurrent: q.isCurrent || false
    }));
    
    const formData = new FormData();
    formData.append("qualifications", JSON.stringify(formattedQualifications));
    const response = await updateProfile(formData, accessToken!);
    
    if (response.success) { 
      setQualifications(formattedQualifications); 
      setTempQualifications(formattedQualifications);
      toast.success("Qualifications updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

  const saveInvestorProfile = async () => {
    try {
      setSaving(true);
      const updateData = {
        businessName: tempInvestorInfo.businessName, annualIncomeRange: tempInvestorInfo.annualIncomeRange,
        netWorth: tempInvestorInfo.netWorth, investorType: tempInvestorInfo.investorType,
        investmentRange: tempInvestorInfo.investmentRange, activeDeals: tempInvestorInfo.activeDeals,
        totalInvested: tempInvestorInfo.totalInvested,
      };
      const response = await updateInvestorProfile(updateData, accessToken!);
      if (response.success) { setInvestorInfo(tempInvestorInfo); toast.success("Investor profile updated"); setEditingSection(null); }
      else toast.error(response.message);
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

  const saveInvestorEducation = async () => {
    try {
      setSaving(true);
      const formData = new FormData();
      formData.append("education", JSON.stringify(tempInvestorEducation));
      const response = await updateInvestorProfile(formData, accessToken!);
      if (response.success) { setInvestorEducation(tempInvestorEducation); toast.success("Education updated"); setEditingSection(null); }
      else toast.error(response.message);
    } catch (error) { toast.error("Failed to save changes"); }
    finally { setSaving(false); }
  };

 const saveInvestorExperience = async () => {
  try {
    setSaving(true);
    const formData = new FormData();
    formData.append("experience", JSON.stringify(tempInvestorExperience));
    const response = await updateInvestorProfile(formData, accessToken!);
    if (response.success) { 
      setInvestorExperience(tempInvestorExperience); 
      toast.success("Experience updated"); 
      setEditingSection(null); 
    } else {
      toast.error(response.message);
    }
  } catch (error) { 
    toast.error("Failed to save changes"); 
  } finally { 
    setSaving(false); 
  }
};

  const cancelEditing = () => {
    if (editingSection === "company") setTempCompanyInfo(companyInfo);
    else if (editingSection === "whatWeOffer") setTempCompanyInfo(companyInfo);
      else if (editingSection === "businessCategory") {
    setLookingFor(lookingFor);
  }
  else if (editingSection === "businessIdeasLookingFor") {
    setBusinessIdeasLookingFor(businessIdeasLookingFor);
  }
    else if (editingSection === "investorLookingFor") {
      setLookingFor(originalLookingFor);
  }
    else if (editingSection === "investorProfile") setTempInvestorInfo(investorInfo);
    else if (editingSection === "investorEducation") setTempInvestorEducation(investorEducation);
    else if (editingSection === "investorExperience") setTempInvestorExperience(investorExperience);
    else if (editingSection === "individualEducation") setTempQualifications(qualifications);
    else if (editingSection === "individualExperience") setTempQualifications(qualifications);
    else if (editingSection === "skills") setTempSkills(skills);
    else if (editingSection === "interests") setTempInterests(interests);
    else if (editingSection === "achievements") setTempAchievements(achievements);
    else setTempProfile(profile);
    setEditingSection(null);
  };

  const userTypeConfig = {
    individual: { label: "Individual", icon: User, color: "text-primary border-primary bg-primary/10" },
    business: { label: "Business", icon: Building2, color: "text-amber-400 border-amber-400 bg-amber-400/10" },
    investor: { label: "Investor", icon: IndianRupee, color: "text-emerald-400 border-emerald-400 bg-emerald-400/10" },
  };

  const currentConfig = userTypeConfig[userType];
  const CurrentIcon = currentConfig.icon;
  const profileUrl = `/profile/${userType}`;
  const displayName = profile.fullName || "User";
  const getInitial = () => (displayName.charAt(0) || "U").toUpperCase();
  const [accountTypeLabel, setAccountTypeLabel] = useState(currentConfig.label);


  if (loading || labelsLoading) {
    return <SettingsPageSkeleton />;
  }

  if (labelsError) {
    return (
      <div className="min-h-screen bg-background">
        <Sidebar />
        <div className="lg:pl-72">
          <div className="flex flex-col items-center justify-center h-screen">
            <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">
                <AlertTriangle className="h-8 w-8 text-red-500" />
              </div>
              <h2 className="text-xl font-semibold text-foreground mb-2">Configuration Error</h2>
              <p className="text-muted-foreground mb-4">{labelsError}</p>
              <button
                onClick={() => window.location.reload()}
                className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors cursor-pointer"
              >
                Retry
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Sidebar />

      <div className="lg:pl-72">
        {/* Crop Modal */}
        {cropModalOpen && (
          <div className="fixed inset-0 bg-black/80 z-[9999] flex items-center justify-center p-4">
            <div className="bg-background border border-border rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-auto">
              <div className="p-6">
                <div className="flex justify-between items-center mb-4">
                  <h2 className="text-xl font-bold text-foreground">Crop Profile Picture</h2>
                  <button onClick={cancelCrop} className="text-muted-foreground hover:text-foreground cursor-pointer"><X className="h-6 w-6" /></button>
                </div>
                <div className="mb-4">
                  {imgSrc && (
                    <ReactCrop crop={crop} onChange={(_, pct) => setCrop(pct)} onComplete={(c) => setCompletedCrop(c)} aspect={1} circularCrop className="max-h-[60vh]">
                      <img ref={imgRef} src={imgSrc} onLoad={onImageLoad} alt="Crop preview" className="max-h-[60vh] mx-auto" />
                    </ReactCrop>
                  )}
                </div>
                <div className="flex justify-end gap-3">
                  <Button variant="outline" onClick={cancelCrop} className="cursor-pointer">Cancel</Button>
                  <Button onClick={applyCrop} className="cursor-pointer">Apply Crop</Button>
                </div>
              </div>
            </div>
          </div>
        )}

        <header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b border-border/50 glass px-4 lg:px-6">
          <div className="flex items-center gap-4">
            <Link href="/" className="lg:hidden"><Button variant="ghost" size="icon" className="cursor-pointer"><ArrowLeft className="h-5 w-5" /></Button></Link>
            <h1 className="text-lg font-semibold text-foreground">Profile Settings</h1>
          </div>
          <Link href={getProfileUrl()}><Button variant="outline" size="sm" className="gap-2 cursor-pointer"><Globe className="h-4 w-4" />View Public Profile</Button></Link>
        </header>

        <main className="p-4 lg:p-6 max-w-3xl mx-auto space-y-6">
          {/* Profile Picture & User Type */}
<div className="rounded-2xl glass glass-border p-6">
  <div className="flex flex-col sm:flex-row items-start sm:items-center gap-6">
    <div className="relative group">
      {/* Profile Image Container */}
      <div 
        className="relative h-24 w-24 rounded-2xl bg-gradient-to-br from-primary to-accent flex items-center justify-center text-3xl font-bold text-white overflow-hidden cursor-pointer"
        onClick={() => fileInputRef.current?.click()}
      >
        {imagePreview ? (
          <img src={imagePreview} alt="Preview" className="w-full h-full object-cover" />
        ) : profile.imageURL ? (
          <img 
            src={`${process.env.NEXT_PUBLIC_BASE_URL}/uploads/${profile.imageURL}`} 
            alt={displayName} 
            className="w-full h-full object-cover" 
          />
        ) : (
          getInitial()
        )}
        
        {/* 🔥 Hover Overlay with Camera + Pencil */}
        <div className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity">
          <div className="flex flex-col items-center gap-1">
            <Camera className="h-6 w-6 text-white" />
            <span className="text-xs text-white">Change Photo</span>
          </div>
        </div>
      </div>
      
      {/* 🔥 Pencil Icon Button - Separate clickable button */}
      <button
        onClick={() => fileInputRef.current?.click()}
        className="absolute -top-2 -right-2 flex h-8 w-8 items-center justify-center rounded-full bg-primary text-white dark:bg-white dark:text-black shadow-lg hover:bg-primary/90 transition-all cursor-pointer"
        title="Edit profile picture"
      >
        <Pencil className="h-4 w-4" />
      </button>
      
      <input 
        ref={fileInputRef} 
        type="file" 
        hidden 
        accept="image/jpeg,image/jpg,image/png,image/webp" 
        onChange={uploadImageHandler} 
      />
    </div>
    
    <div className="flex-1">
      <div className="flex items-center gap-2">
        <h2 className="text-xl font-bold text-foreground mb-1">{displayName}</h2>
        {/* 🔥 Optional: Add edit name button */}
        <button
          onClick={() => startEditing("basic")}
          className="text-muted-foreground hover:text-primary transition-colors cursor-pointer"
          title="Edit profile info"
        >
          <Pencil className="h-3.5 w-3.5" />
        </button>
      </div>
      <p className="text-sm text-muted-foreground mb-3">checkuridea.com/@{profile.userName || "user"}</p>
      {profile.designation && <p className="text-sm text-primary mb-2">{profile.designation}</p>}
      
      {imageFile && (
        <button 
          onClick={saveProfilePhoto} 
          disabled={uploadingPhoto} 
          className="mt-2 mb-2 cursor-pointer flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
        >
          {uploadingPhoto ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
          {uploadingPhoto ? "Saving..." : "Save Photo"}
        </button>
      )}
      
      <div className="flex flex-wrap gap-2">
        <span className={cn("flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm", currentConfig.color)}>
          <CurrentIcon className="h-4 w-4" /> {accountTypeLabel}
        </span>
      </div>
    </div>
  </div>
</div>

          {/* Basic Info Section - Without Username */}
          <EditableSection 
            title={getSectionTitle("basic_information")} 
            icon={User} 
            isEditing={editingSection === "basic"} 
            onEdit={() => startEditing("basic")} 
            onSave={saveBasicInfo} 
            onCancel={cancelEditing}
            saving={saving}
            editContent={
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("full_name")}</label>
                  <Input value={tempProfile.fullName} onChange={(e) => setTempProfile({ ...tempProfile, fullName: e.target.value })} className="bg-secondary/30" />
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("phone_number")}</label>
                  <Input value={tempProfile.phone || ""} onChange={(e) => setTempProfile({ ...tempProfile, phone: e.target.value })} className="bg-secondary/30" placeholder="e.g., 9876543210" type="tel" />
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("date_of_birth")}</label>
                  <Input 
                    value={tempProfile.tempDateOfBirth || ""} 
                    onChange={(e) => {
                      const selectedDate = e.target.value;
                      setTempProfile({ 
                        ...tempProfile, 
                        tempDateOfBirth: selectedDate, 
                        dateOfBirth: formatDateForDisplay(selectedDate) 
                      });
                    }} 
                    className="bg-secondary/30" 
                    type="date" 
                    max={(() => {
                      const date = new Date();
                      date.setFullYear(date.getFullYear() - 18);
                      return date.toISOString().split('T')[0];
                    })()}
                  />
                  {tempProfile.tempDateOfBirth && !isAge18OrAbove(tempProfile.tempDateOfBirth) && (
                    <p className="text-xs text-red-500 mt-1">You must be 18 years or older</p>
                  )}
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("designation")}</label>
                  <Input value={tempProfile.designation} onChange={(e) => setTempProfile({ ...tempProfile, designation: e.target.value })} className="bg-secondary/30" placeholder="e.g., Product Manager, Founder" />
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("bio")}</label>
                  <textarea value={tempProfile.aboutMe} onChange={(e) => setTempProfile({ ...tempProfile, aboutMe: e.target.value })} rows={3} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none" />
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("gender")}</label>
                  <select value={tempProfile.gender} onChange={(e) => setTempProfile({ ...tempProfile, gender: e.target.value })} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50">
                    <option value="">Select Gender</option>
                    {genderOptions.map((option) => (<option key={option._id} value={option.genderValue}>{option.genderValue}</option>))}
                  </select>
                </div>
              </div>
            }
          >
            <div className="space-y-2">
              <p className="text-foreground font-medium">{displayName}</p>
              {profile.phone && <p className="text-sm text-muted-foreground">📞 {profile.phone}</p>}
              {profile.dateOfBirth && <p className="text-sm text-muted-foreground">🎂 {profile.dateOfBirth}</p>}
              {profile.designation && <p className="text-sm text-muted-foreground">{profile.designation}</p>}
              <p className="text-sm text-muted-foreground">{profile.aboutMe || ""}</p>
              {profile.gender && <p className="text-sm text-muted-foreground">Gender: {profile.gender}</p>}
            </div>
          </EditableSection>

          {/* Location Section */}
          <EditableSection 
            title={getSectionTitle("location")} 
            icon={MapPin} 
            isEditing={editingSection === "location"} 
            onEdit={() => startEditing("location")} 
            onSave={saveLocation} 
            onCancel={cancelEditing}
            saving={saving}
            editContent={
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("country_city")}</label>
                  <Input value={tempProfile.location} onChange={(e) => setTempProfile({ ...tempProfile, location: e.target.value })} className="bg-secondary/30" placeholder="e.g., Mumbai, India" />
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("full_address")}</label>
                  <textarea value={tempProfile.address || ""} onChange={(e) => setTempProfile({ ...tempProfile, address: e.target.value })} rows={2} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm text-foreground resize-none" placeholder="Street, City, State, Pincode..." />
                </div>
              </div>
            }
          >
            <div className="flex flex-wrap gap-4 text-sm">
              <span className="flex items-center gap-2 text-muted-foreground"><MapPin className="h-4 w-4" />{profile.location || "Location not specified"}</span>
              {profile.address && <span className="flex items-center gap-2 text-muted-foreground w-full mt-2">📍 {profile.address}</span>}
            </div>
          </EditableSection>

          {/* Social Links Section */}
          <EditableSection 
            title={getSectionTitle("social_links")} 
            icon={Link2} 
            isEditing={editingSection === "social"} 
            onEdit={() => startEditing("social")} 
            onSave={saveSocialLinks} 
            onCancel={cancelEditing}
            saving={saving}
            editContent={
              <div className="space-y-4">
                <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("website")}</label><Input value={tempProfile.website} onChange={(e) => setTempProfile({ ...tempProfile, website: e.target.value })} className="bg-secondary/30" placeholder="https://yourwebsite.com" /></div>
                <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("linkedin")}</label><Input value={tempProfile.linkedin} onChange={(e) => setTempProfile({ ...tempProfile, linkedin: e.target.value })} className="bg-secondary/30" placeholder="https://linkedin.com/in/username" /></div>
                <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("twitter")}</label><Input value={tempProfile.twitter} onChange={(e) => setTempProfile({ ...tempProfile, twitter: e.target.value })} className="bg-secondary/30" placeholder="https://twitter.com/@username" /></div>
              </div>
            }
          >
            <div className="flex flex-wrap gap-3">
              {profile.website && <a href={profile.website} target="_blank" className="flex items-center gap-2 px-4 py-2 rounded-xl bg-secondary/50 hover:bg-secondary transition-colors text-sm cursor-pointer"><Globe className="h-4 w-4" />Website</a>}
              {profile.linkedin && <a href={profile.linkedin} target="_blank" className="flex items-center gap-2 px-4 py-2 rounded-xl bg-[#0077B5]/10 text-[#0077B5] hover:bg-[#0077B5]/20 transition-colors text-sm cursor-pointer"><Linkedin className="h-4 w-4" />LinkedIn</a>}
              {profile.twitter && <a href={profile.twitter} target="_blank" className="flex items-center gap-2 px-4 py-2 rounded-xl bg-[#1DA1F2]/10 text-[#1DA1F2] hover:bg-[#1DA1F2]/20 transition-colors text-sm cursor-pointer"><Twitter className="h-4 w-4" />Twitter</a>}
              {!profile.website && !profile.linkedin && !profile.twitter && <p className="text-sm text-muted-foreground">No social links added</p>}
            </div>
          </EditableSection>

          {/* INDIVIDUAL SECTIONS */}
          {userType === "individual" && (
            <>
             <EditableSection 
      title={getSectionTitle("education")} 
      icon={GraduationCap} 
      isEditing={editingSection === "individualEducation"} 
      onEdit={() => {
        setTempQualifications(qualifications);
        setEditingSection("individualEducation");
      }} 
      onSave={saveQualifications} 
      onCancel={() => setEditingSection(null)}
      saving={saving}
      editContent={
        <div className="space-y-3">
          {tempQualifications.filter(q => q.type === "education").map((edu, idx) => (
            <div key={idx} className="flex flex-col gap-3 p-4 rounded-xl bg-secondary/30">
              <div className="flex items-start gap-3">
                <div className="flex-1 space-y-2">
                  <Input 
                    value={edu.title} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "education" && q === edu); 
                      updated[i].title = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="Degree/Course" 
                    className="bg-secondary/50" 
                  />
                  <Input 
                    value={edu.institution} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "education" && q === edu); 
                      updated[i].institution = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="Institution/University" 
                    className="bg-secondary/50" 
                  />
                </div>
                <button 
                  onClick={() => setTempQualifications(tempQualifications.filter((_, i) => i !== idx))}
                  className="text-destructive hover:text-destructive/80 p-2 cursor-pointer"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
              
              {/* ✅ FROM - TO YEARS */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">From Year</label>
                  <Input 
                    value={edu.fromYear || ""} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "education" && q === edu); 
                      updated[i].fromYear = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="e.g., 2020" 
                    className="bg-secondary/50" 
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">To Year</label>
                  <Input 
                    value={edu.toYear || ""} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "education" && q === edu); 
                      updated[i].toYear = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="e.g., 2024" 
                    className="bg-secondary/50" 
                    disabled={edu.isCurrent}
                  />
                </div>
              </div>
              
              {/* ✅ CURRENT STUDYING CHECKBOX - ONLY FOR INDIVIDUAL */}
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id={`current-edu-${idx}`}
                  checked={edu.isCurrent || false}
                  onChange={(e) => {
                    const updated = [...tempQualifications];
                    const i = updated.findIndex(q => q.type === "education" && q === edu);
                    updated[i].isCurrent = e.target.checked;
                    if (e.target.checked) {
                      updated[i].toYear = "Present";
                    } else {
                      updated[i].toYear = "";
                    }
                    setTempQualifications(updated);
                  }}
                  className="h-4 w-4 rounded border-border cursor-pointer"
                />
                <label htmlFor={`current-edu-${idx}`} className="text-sm text-foreground cursor-pointer">
                  Currently studying here
                </label>
              </div>
            </div>
          ))}
          
          <button 
            onClick={() => {
              setTempQualifications([...tempQualifications, { 
                type: "education", 
                title: "", 
                institution: "", 
                fromYear: "", 
                toYear: "", 
                isCurrent: false 
              }]);
            }} 
            className="flex items-center gap-2 text-sm text-primary hover:text-primary/80 mt-2 cursor-pointer"
          >
            <Plus className="h-4 w-4" /> Add Education
          </button>
        </div>
      }
    >
      {/* Display Section */}
      <div className="space-y-3">
        {qualifications.filter(q => q.type === "education").length === 0 ? 
          <p className="text-sm text-muted-foreground">No education added yet</p> : 
          qualifications.filter(q => q.type === "education").map((edu, idx) => (
            <div key={idx}>
              <p className="font-medium text-foreground">{edu.title}</p>
              <p className="text-sm text-muted-foreground">{edu.institution}</p>
              <p className="text-xs text-muted-foreground mt-1">
                {edu.fromYear && `${edu.fromYear} - `}{edu.toYear || "Present"}
              </p>
            </div>
          ))
        }
      </div>
    </EditableSection>

    {/* ✅ Work Experience Section - WITH FROM/TO + CHECKBOX */}
    <EditableSection 
      title={getSectionTitle("work_experience")} 
      icon={Briefcase} 
      isEditing={editingSection === "individualExperience"} 
      onEdit={() => {
        setTempQualifications(qualifications);
        setEditingSection("individualExperience");
      }} 
      onSave={saveQualifications} 
      onCancel={() => setEditingSection(null)}
      saving={saving}
      editContent={
        <div className="space-y-3">
          {tempQualifications.filter(q => q.type === "experience").map((exp, idx) => (
            <div key={idx} className="flex flex-col gap-3 p-4 rounded-xl bg-secondary/30">
              <div className="flex items-start gap-3">
                <div className="flex-1 space-y-2">
                  <Input 
                    value={exp.title} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "experience" && q === exp); 
                      updated[i].title = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="Role/Position" 
                    className="bg-secondary/50" 
                  />
                  <Input 
                    value={exp.institution} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "experience" && q === exp); 
                      updated[i].institution = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="Company Name" 
                    className="bg-secondary/50" 
                  />
                </div>
                <button 
                  onClick={() => setTempQualifications(tempQualifications.filter((_, i) => i !== idx))}
                  className="text-destructive hover:text-destructive/80 p-2 cursor-pointer"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
              
              {/* ✅ FROM - TO YEARS */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">From Year</label>
                  <Input 
                    value={exp.fromYear || ""} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "experience" && q === exp); 
                      updated[i].fromYear = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="e.g., 2020" 
                    className="bg-secondary/50" 
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">To Year</label>
                  <Input 
                    value={exp.toYear || ""} 
                    onChange={(e) => { 
                      const updated = [...tempQualifications]; 
                      const i = updated.findIndex(q => q.type === "experience" && q === exp); 
                      updated[i].toYear = e.target.value; 
                      setTempQualifications(updated); 
                    }} 
                    placeholder="e.g., 2024" 
                    className="bg-secondary/50" 
                    disabled={exp.isCurrent}
                  />
                </div>
              </div>
              
              {/* ✅ CURRENT WORKING CHECKBOX - ONLY FOR INDIVIDUAL */}
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id={`current-exp-${idx}`}
                  checked={exp.isCurrent || false}
                  onChange={(e) => {
                    const updated = [...tempQualifications];
                    const i = updated.findIndex(q => q.type === "experience" && q === exp);
                    updated[i].isCurrent = e.target.checked;
                    if (e.target.checked) {
                      updated[i].toYear = "Present";
                    } else {
                      updated[i].toYear = "";
                    }
                    setTempQualifications(updated);
                  }}
                  className="h-4 w-4 rounded border-border cursor-pointer"
                />
                <label htmlFor={`current-exp-${idx}`} className="text-sm text-foreground cursor-pointer">
                  I currently work here
                </label>
              </div>
            </div>
          ))}
          
          <button 
            onClick={() => {
              setTempQualifications([...tempQualifications, { 
                type: "experience", 
                title: "", 
                institution: "", 
                fromYear: "", 
                toYear: "", 
                isCurrent: false 
              }]);
            }} 
            className="flex items-center gap-2 text-sm text-primary hover:text-primary/80 mt-2 cursor-pointer"
          >
            <Plus className="h-4 w-4" /> Add Experience
          </button>
        </div>
      }
    >
      {/* Display Section */}
      <div className="space-y-3">
        {qualifications.filter(q => q.type === "experience").length === 0 ? 
          <p className="text-sm text-muted-foreground">No experience added yet</p> : 
          qualifications.filter(q => q.type === "experience").map((exp, idx) => (
            <div key={idx}>
              <p className="font-medium text-foreground">{exp.title}</p>
              <p className="text-sm text-muted-foreground">{exp.institution}</p>
              <p className="text-xs text-muted-foreground mt-1">
                {exp.fromYear && `${exp.fromYear} - `}{exp.toYear || "Present"}
              </p>
            </div>
          ))
        }
      </div>
    </EditableSection>


              {/* Skills Section */}
              <EditableSection 
                title={getSectionTitle("skills")} 
                icon={Award} 
                isEditing={editingSection === "skills"} 
                onEdit={() => startEditing("skills")} 
                onSave={saveSkills} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div>
                    <div className="flex flex-wrap gap-2 mb-3">
                      {tempSkills.map((skill, idx) => (<span key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-secondary text-sm">{skill}<button onClick={() => setTempSkills(tempSkills.filter((_, i) => i !== idx))} className="cursor-pointer"><X className="h-3 w-3" /></button></span>))}
                    </div>
                    <div className="flex gap-2"><Input value={newSkill} onChange={(e) => setNewSkill(e.target.value)} placeholder="Add a skill" className="bg-secondary/30" onKeyDown={(e) => { if (e.key === "Enter" && newSkill.trim()) { setTempSkills([...tempSkills, newSkill.trim()]); setNewSkill(""); } }} /><Button onClick={() => { if (newSkill.trim()) { setTempSkills([...tempSkills, newSkill.trim()]); setNewSkill(""); } }} size="icon" className="cursor-pointer"><Plus className="h-4 w-4" /></Button></div>
                  </div>
                }
              >
                <div className="flex flex-wrap gap-2">{skills.map((skill, idx) => (<span key={idx} className="px-3 py-1.5 rounded-full bg-secondary text-sm">{skill}</span>))}{skills.length === 0 && <p className="text-sm text-muted-foreground">No skills added yet</p>}</div>
              </EditableSection>

              {/* Interests Section */}
              <EditableSection 
                title={getSectionTitle("interests")} 
                icon={Target} 
                isEditing={editingSection === "interests"} 
                onEdit={() => startEditing("interests")} 
                onSave={saveInterests} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div>
                    <div className="flex flex-wrap gap-2 mb-3">
                      {tempInterests.map((interest, idx) => (<span key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-primary/10 text-primary text-sm border border-primary/20">{interest}<button onClick={() => setTempInterests(tempInterests.filter((_, i) => i !== idx))} className="cursor-pointer"><X className="h-3 w-3" /></button></span>))}
                    </div>
                    <div className="flex gap-2"><Input value={newInterest} onChange={(e) => setNewInterest(e.target.value)} placeholder="Add an interest" className="bg-secondary/30" onKeyDown={(e) => { if (e.key === "Enter" && newInterest.trim()) { setTempInterests([...tempInterests, newInterest.trim()]); setNewInterest(""); } }} /><Button onClick={() => { if (newInterest.trim()) { setTempInterests([...tempInterests, newInterest.trim()]); setNewInterest(""); } }} size="icon" className="cursor-pointer"><Plus className="h-4 w-4" /></Button></div>
                  </div>
                }
              >
                <div className="flex flex-wrap gap-2">{interests.map((interest, idx) => (<span key={idx} className="px-3 py-1.5 rounded-full bg-primary/10 text-primary text-sm border border-primary/20">{interest}</span>))}{interests.length === 0 && <p className="text-sm text-muted-foreground">No interests added yet</p>}</div>
              </EditableSection>

              {/* Achievements Section */}
              <EditableSection 
                title={getSectionTitle("achievements")} 
                icon={Award} 
                isEditing={editingSection === "achievements"} 
                onEdit={() => startEditing("achievements")} 
                onSave={saveAchievements} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div className="space-y-3">
                    {tempAchievements.map((achievement, idx) => (<div key={idx} className="flex items-start gap-3 p-3 rounded-xl bg-secondary/30"><div className="flex-1"><Input value={achievement.title} onChange={(e) => { const updated = [...tempAchievements]; updated[idx].title = e.target.value; setTempAchievements(updated); }} placeholder="Achievement title" className="bg-secondary/50" /></div><button onClick={() => setTempAchievements(tempAchievements.filter((_, i) => i !== idx))} className="cursor-pointer"><Trash2 className="h-4 w-4" /></button></div>))}
                    <button onClick={() => setTempAchievements([...tempAchievements, { title: "" }])} className="flex items-center gap-2 text-sm text-primary cursor-pointer"><Plus className="h-4 w-4" /> Add Achievement</button>
                  </div>
                }
              >
                <div className="space-y-3">{achievements.map((achievement, 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">{achievement.title}</p></div>))}{achievements.length === 0 && <p className="text-sm text-muted-foreground">No achievements added yet</p>}</div>
              </EditableSection>

              {/* Looking For / Categories Section for Individual */}
              <EditableSection 
                title={getSectionTitle("exploring_categories") || "Category"} 
                icon={Target} 
                isEditing={editingSection === "lookingFor"} 
                onEdit={() => startEditing("lookingFor")} 
                onSave={saveLookingFor} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div>
                    <div className="flex flex-wrap gap-2 mb-3">
                      {lookingFor.map((item, idx) => (
                        <span key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-secondary text-sm">
                          {item}
                          <button onClick={() => setLookingFor(lookingFor.filter((_, i) => i !== idx))} className="cursor-pointer">
                            <X className="h-3 w-3" />
                          </button>
                        </span>
                      ))}
                    </div>
                    <div className="flex gap-2">
                      <select 
                        value={newLookingFor} 
                        onChange={(e) => setNewLookingFor(e.target.value)} 
                        className="flex-1 rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm cursor-pointer"
                      >
                        <option value="">Select a category</option>
                        {allCategories.map((cat) => (
                          <option key={cat._id} value={cat.mainCategoryName}>{cat.mainCategoryName}</option>
                        ))}
                      </select>
                      <Button 
                        onClick={() => { 
                          if (newLookingFor && !lookingFor.includes(newLookingFor) && lookingFor.length < 5) { 
                            setLookingFor([...lookingFor, newLookingFor]); 
                            setNewLookingFor(""); 
                          } else if (lookingFor.length >= 5) { 
                            toast.warning("Maximum 5 categories allowed"); 
                          } 
                        }} 
                        size="icon"
                        className="cursor-pointer"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground mt-2">Maximum 5 categories</p>
                  </div>
                }
              >
                <div className="flex flex-wrap gap-2">
                  {lookingFor.map((item, idx) => (
                    <span key={idx} className="px-3 py-1.5 rounded-full bg-primary/10 text-primary text-sm border border-primary/20">
                      {item}
                    </span>
                  ))}
                  {lookingFor.length === 0 && (
                    <p className="text-sm text-muted-foreground">No categories selected</p>
                  )}
                </div>
              </EditableSection>
            </>
          )}

          {/* BUSINESS SECTIONS */}
          {userType === "business" && (
            <>
              <EditableSection 
                title={getSectionTitle("company_information")} 
                icon={Building2} 
                isEditing={editingSection === "company"} 
                onEdit={() => startEditing("company")} 
                onSave={saveCompanyInfo} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div className="space-y-4">
                    <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("company_name")}</label><Input value={tempCompanyInfo.companyName} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, companyName: e.target.value})} className="bg-secondary/30" /></div>
                    <div><label className="text-sm font-medium text-foreground mb-1.5 block">Business Type</label><select value={tempCompanyInfo.businessType} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, businessType: e.target.value})} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm cursor-pointer"><option value="">Select Business Type</option>{businessTypes.map((type) => (<option key={type._id} value={type.businessTypeSlug}>{type.businessTypeName}</option>))}</select></div>
                    <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("description")}</label><textarea value={tempCompanyInfo.description} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, description: e.target.value})} rows={3} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm" /></div>
                    <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("industry")}</label><Input value={tempCompanyInfo.industry} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, industry: e.target.value})} className="bg-secondary/30" /></div>
                    <div className="grid grid-cols-2 gap-4"><div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("founded_year")}</label><Input value={tempCompanyInfo.founded} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, founded: e.target.value})} placeholder="2015" /></div><div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("company_size")}</label><Input value={tempCompanyInfo.size} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, size: e.target.value})} placeholder="50-100 employees" /></div></div>
                    <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("headquarters")}</label><Input value={tempCompanyInfo.headquarters} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, headquarters: e.target.value})} placeholder="Mumbai, India" /></div>
                    <div><label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("annual_revenue")}</label><Input value={tempCompanyInfo.annualRevenue} onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, annualRevenue: e.target.value})} placeholder="₹10 Cr - ₹50 Cr" /></div>
                  </div>
                }
              >
                <div className="space-y-2"><p className="font-medium text-lg">{companyInfo.companyName || "Not set"}</p>{companyInfo.businessType && <span className="text-sm text-muted-foreground">Type: {companyInfo.businessType.replace(/_/g, ' ')}</span>}{companyInfo.description && <p className="text-sm mt-2">{companyInfo.description}</p>}<div className="grid grid-cols-2 gap-3 text-sm mt-3">{companyInfo.industry && <p>Industry: {companyInfo.industry}</p>}{companyInfo.founded && <p>Founded: {companyInfo.founded}</p>}{companyInfo.size && <p>Size: {companyInfo.size}</p>}{companyInfo.headquarters && <p>HQ: {companyInfo.headquarters}</p>}{companyInfo.annualRevenue && <p>Revenue: {companyInfo.annualRevenue}</p>}</div></div>
              </EditableSection>

              <EditableSection 
                title={getSectionTitle("what_we_offer")} 
                icon={Award} 
                isEditing={editingSection === "whatWeOffer"} 
                onEdit={() => startEditing("whatWeOffer")} 
                onSave={saveWhatWeOffer} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div className="space-y-3">
                    {tempCompanyInfo.whatWeOffer.map((offer, idx) => (<div key={idx} className="flex items-start gap-3 p-3 rounded-xl bg-secondary/30"><div className="flex-1 space-y-2"><Input value={offer.title} onChange={(e) => { const updated = [...tempCompanyInfo.whatWeOffer]; updated[idx].title = e.target.value; setTempCompanyInfo({...tempCompanyInfo, whatWeOffer: updated}); }} placeholder="Offer title" /><textarea value={offer.description} onChange={(e) => { const updated = [...tempCompanyInfo.whatWeOffer]; updated[idx].description = e.target.value; setTempCompanyInfo({...tempCompanyInfo, whatWeOffer: updated}); }} rows={2} placeholder="Description" className="w-full rounded-lg bg-secondary/50 border border-border/50 px-3 py-2 text-sm resize-none" /></div><button onClick={() => { const updated = tempCompanyInfo.whatWeOffer.filter((_, i) => i !== idx); setTempCompanyInfo({...tempCompanyInfo, whatWeOffer: updated}); }} className="cursor-pointer"><Trash2 className="h-4 w-4" /></button></div>))}
                    <button onClick={() => { if (tempCompanyInfo.whatWeOffer.length >= 5) { toast.warning("Maximum 5 offers allowed"); return; } setTempCompanyInfo({ ...tempCompanyInfo, whatWeOffer: [...tempCompanyInfo.whatWeOffer, { title: "", description: "" }] }); }} className="flex items-center gap-2 text-sm text-amber-400 cursor-pointer"><Plus className="h-4 w-4" /> Add Offer</button>
                  </div>
                }
              >
                <div className="space-y-3">{companyInfo.whatWeOffer.length === 0 ? <p className="text-sm text-muted-foreground">No offers added yet</p> : companyInfo.whatWeOffer.map((offer, idx) => (<div key={idx} className="flex items-start gap-3"><div className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-400/10 shrink-0"><Award className="h-4 w-4 text-amber-400" /></div><div><p className="font-medium">{offer.title}</p><p className="text-sm text-muted-foreground">{offer.description}</p></div></div>))}</div>
              </EditableSection>

             {/* Business Category (Post Categories) - Renamed */}
    <EditableSection 
      title="Business Category" 
      icon={Building2} 
      isEditing={editingSection === "businessCategory"} 
      onEdit={() => startEditing("businessCategory")} 
      onSave={saveLookingFor} 
      onCancel={cancelEditing}
      saving={saving}
      editContent={
        <div>
          <div className="flex flex-wrap gap-2 mb-3">{lookingFor.map((item, idx) => (<span key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-secondary text-sm">{item}<button onClick={() => setLookingFor(lookingFor.filter((_, i) => i !== idx))} className="cursor-pointer"><X className="h-3 w-3" /></button></span>))}</div>
          <div className="flex gap-2"><select value={newLookingFor} onChange={(e) => setNewLookingFor(e.target.value)} className="flex-1 rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm cursor-pointer"><option value="">Select Business Category</option>{allCategories.map((cat) => (<option key={cat._id} value={cat.mainCategoryName}>{cat.mainCategoryName}</option>))}</select><Button onClick={() => { if (newLookingFor && !lookingFor.includes(newLookingFor) && lookingFor.length < 5) { setLookingFor([...lookingFor, newLookingFor]); setNewLookingFor(""); } else if (lookingFor.length >= 5) { toast.warning("Maximum 5 categories allowed"); } }} size="icon" className="cursor-pointer"><Plus className="h-4 w-4" /></Button></div>
          <p className="text-xs text-muted-foreground mt-2">Your business industry/domain categories (Max 5)</p>
        </div>
      }
    >
      <div className="flex flex-wrap gap-2">{lookingFor.map((item, idx) => (<span key={idx} className="px-3 py-1.5 rounded-full bg-amber-400/10 text-amber-400 text-sm">{item}</span>))}{lookingFor.length === 0 && <p className="text-sm text-muted-foreground">No business categories selected</p>}</div>
    </EditableSection>

    {/* NEW: Ideas We're Looking For - Separate section */}
    <EditableSection 
      title="Ideas We're Looking For" 
      icon={Target} 
      isEditing={editingSection === "businessIdeasLookingFor"} 
      onEdit={() => startEditing("businessIdeasLookingFor")} 
      onSave={saveBusinessIdeasLookingFor} 
      onCancel={cancelEditing}
      saving={saving}
      editContent={
        <div>
          <div className="flex flex-wrap gap-2 mb-3">
            {businessIdeasLookingFor.map((item, idx) => (
              <span key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-secondary text-sm">
                {item}
                <button onClick={() => setBusinessIdeasLookingFor(businessIdeasLookingFor.filter((_, i) => i !== idx))} className="cursor-pointer">
                  <X className="h-3 w-3" />
                </button>
              </span>
            ))}
          </div>
          <div className="flex gap-2">
            <Input 
              value={newBusinessIdea} 
              onChange={(e) => setNewBusinessIdea(e.target.value)} 
              placeholder="e.g., AI Startups, Fintech Solutions, Green Energy Ideas"
              className="bg-secondary/30" 
            />
            <Button 
              onClick={() => { 
                if (newBusinessIdea.trim() && !businessIdeasLookingFor.includes(newBusinessIdea.trim()) && businessIdeasLookingFor.length < 5) { 
                  setBusinessIdeasLookingFor([...businessIdeasLookingFor, newBusinessIdea.trim()]); 
                  setNewBusinessIdea(""); 
                } else if (businessIdeasLookingFor.length >= 5) { 
                  toast.warning("Maximum 5 ideas allowed"); 
                } else if (businessIdeasLookingFor.includes(newBusinessIdea.trim())) {
                  toast.warning("This idea already exists");
                }
              }} 
              size="icon"
              className="cursor-pointer"
            >
              <Plus className="h-4 w-4" />
            </Button>
          </div>
          <p className="text-xs text-muted-foreground mt-2">What kind of ideas/businesses are you looking for? (Max 5)</p>
        </div>
      }
    >
      <div className="flex flex-wrap gap-2">
        {businessIdeasLookingFor.map((item, idx) => (
          <span key={idx} className="px-3 py-1.5 rounded-full bg-primary/10 text-primary text-sm border border-primary/20">
            💡 {item}
          </span>
        ))}
        {businessIdeasLookingFor.length === 0 && (
          <p className="text-sm text-muted-foreground">No ideas added yet</p>
        )}
      </div>
    </EditableSection>

    <ComingSoonSection title="Key People" icon={Users} />
  </>
)}

          {/* INVESTOR SECTIONS */}
          {userType === "investor" && (
            <>
              <EditableSection 
                title={getSectionTitle("investment_profile")} 
                icon={IndianRupee} 
                isEditing={editingSection === "investorProfile"} 
                onEdit={() => startEditing("investorProfile")} 
                onSave={saveInvestorProfile} 
                onCancel={cancelEditing}
                saving={saving}
                editContent={
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("annual_income_range")}</label>
                      <select value={tempInvestorInfo.annualIncomeRange} onChange={(e) => setTempInvestorInfo({...tempInvestorInfo, annualIncomeRange: e.target.value})} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm cursor-pointer">
                        <option value="">Select Annual Income Range</option>
                        {incomeRanges.map((range) => (<option key={range._id} value={range.rangeName}>{range.rangeName}</option>))}
                      </select>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("net_worth")}</label>
                      <select value={tempInvestorInfo.netWorth} onChange={(e) => setTempInvestorInfo({...tempInvestorInfo, netWorth: e.target.value})} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm cursor-pointer">
                        <option value="">Select Net Worth Range</option>
                        {netWorthOptions.map((option) => (<option key={option._id} value={option.netWorthName}>{option.netWorthName}</option>))}
                      </select>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("total_invested")}</label>
                      <Input value={tempInvestorInfo.totalInvested} onChange={(e) => setTempInvestorInfo({...tempInvestorInfo, totalInvested: e.target.value})} className="bg-secondary/30" placeholder="e.g., 5Cr+" />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">{getLabel("active_deals")}</label>
                      <Input value={tempInvestorInfo.activeDeals} onChange={(e) => setTempInvestorInfo({...tempInvestorInfo, activeDeals: e.target.value})} className="bg-secondary/30" placeholder="e.g., 8" />
                    </div>
                  </div>
                }
              >
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                  <div className="text-center p-3 rounded-xl bg-emerald-500/10">
                    <p className="text-xl font-bold text-emerald-400">{investorInfo.totalInvested || "0"}</p>
                    <p className="text-xs text-muted-foreground">Total Invested</p>
                  </div>
                  <div className="text-center p-3 rounded-xl bg-secondary/50">
                    <p className="text-xl font-bold text-foreground">{investorInfo.activeDeals || "0"}</p>
                    <p className="text-xs text-muted-foreground">Active Deals</p>
                  </div>
                  <div className="text-center p-3 rounded-xl bg-secondary/50">
                    <p className="text-sm font-bold text-foreground">{investorInfo.annualIncomeRange || "Not set"}</p>
                    <p className="text-xs text-muted-foreground">Annual Income</p>
                  </div>
                  <div className="text-center p-3 rounded-xl bg-secondary/50">
                    <p className="text-sm font-bold text-foreground">{investorInfo.netWorth || "Not set"}</p>
                    <p className="text-xs text-muted-foreground">Net Worth</p>
                  </div>
                </div>
              </EditableSection>

<EditableSection 
  title={getSectionTitle("education")} 
  icon={GraduationCap} 
  isEditing={editingSection === "investorEducation"} 
  onEdit={() => startEditing("investorEducation")} 
  onSave={saveInvestorEducation} 
  onCancel={cancelEditing}
  saving={saving}
  editContent={
    <div className="space-y-3">
      {tempInvestorEducation.map((edu, idx) => (
        <div key={idx} className="flex flex-col gap-3 p-4 rounded-xl bg-secondary/30">
          <div className="flex items-start gap-3">
            <div className="flex-1 space-y-2">
              <Input 
                value={edu.degree} 
                onChange={(e) => { 
                  const updated = [...tempInvestorEducation]; 
                  updated[idx].degree = e.target.value; 
                  setTempInvestorEducation(updated); 
                }} 
                placeholder="Degree/Course" 
                className="bg-secondary/50" 
              />
              <Input 
                value={edu.institution} 
                onChange={(e) => { 
                  const updated = [...tempInvestorEducation]; 
                  updated[idx].institution = e.target.value; 
                  setTempInvestorEducation(updated); 
                }} 
                placeholder="Institution/University" 
                className="bg-secondary/50" 
              />
            </div>
            <button 
              onClick={() => setTempInvestorEducation(tempInvestorEducation.filter((_, i) => i !== idx))}
              className="text-destructive hover:text-destructive/80 p-2 cursor-pointer"
            >
              <Trash2 className="h-4 w-4" />
            </button>
          </div>
          
        {/* ✅ CHANGE FROM INPUT TO DATE PICKER (MONTH/YEAR) */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-muted-foreground mb-1 block">From Year</label>
              <input 
                type="month"
                value={edu.fromYear || ""} 
                onChange={(e) => { 
                  const updated = [...tempInvestorEducation]; 
                  updated[idx].fromYear = e.target.value; 
                  setTempInvestorEducation(updated); 
                }} 
                className="w-full rounded-lg bg-secondary/50 border border-border/50 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>
            <div>
              <label className="text-xs text-muted-foreground mb-1 block">To Year</label>
              <input 
                type="month"
                value={edu.toYear || ""} 
                onChange={(e) => { 
                  const updated = [...tempInvestorEducation]; 
                  updated[idx].toYear = e.target.value; 
                  setTempInvestorEducation(updated); 
                }} 
                className="w-full rounded-lg bg-secondary/50 border border-border/50 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>
          </div>
        </div>
      ))}
      
      <button 
        onClick={() => {
          setTempInvestorEducation([
            ...tempInvestorEducation, 
            { degree: "", institution: "", fromYear: "", toYear: "" }
          ]);
        }} 
        className="flex items-center gap-2 text-sm text-primary hover:text-primary/80 mt-2 cursor-pointer"
      >
        <Plus className="h-4 w-4" /> Add Education
      </button>
    </div>
  }
>
  {/* Display Section */}
  <div className="space-y-3">
    {investorEducation.length === 0 ? 
      <p className="text-sm text-muted-foreground">No education added yet</p> : 
      investorEducation.map((edu, idx) => (
        <div key={idx}>
          <p className="font-medium text-foreground">{edu.degree}</p>
          <p className="text-sm text-muted-foreground">{edu.institution}</p>
          <p className="text-xs text-muted-foreground mt-1">
            {edu.fromYear && `${edu.fromYear} - `}{edu.toYear || ""}
          </p>
        </div>
      ))
    }
  </div>
</EditableSection>

   <EditableSection 
  title={getSectionTitle("work_experience")} 
  icon={Briefcase} 
  isEditing={editingSection === "investorExperience"} 
  onEdit={() => startEditing("investorExperience")} 
  onSave={saveInvestorExperience} 
  onCancel={cancelEditing}
  saving={saving}
  editContent={
    <div className="space-y-3">
      {tempInvestorExperience.map((exp, idx) => (
        <div key={idx} className="flex flex-col gap-3 p-4 rounded-xl bg-secondary/30">
          <div className="flex items-start gap-3">
            <div className="flex-1 space-y-2">
              <Input 
                value={exp.role} 
                onChange={(e) => { 
                  const updated = [...tempInvestorExperience]; 
                  updated[idx].role = e.target.value; 
                  setTempInvestorExperience(updated); 
                }} 
                placeholder="Role/Position" 
                className="bg-secondary/50" 
              />
              <Input 
                value={exp.company} 
                onChange={(e) => { 
                  const updated = [...tempInvestorExperience]; 
                  updated[idx].company = e.target.value; 
                  setTempInvestorExperience(updated); 
                }} 
                placeholder="Company Name" 
                className="bg-secondary/50" 
              />
            </div>
            <button 
              onClick={() => setTempInvestorExperience(tempInvestorExperience.filter((_, i) => i !== idx))}
              className="text-destructive hover:text-destructive/80 p-2 cursor-pointer"
            >
              <Trash2 className="h-4 w-4" />
            </button>
          </div>
          
          {/* ✅ CHANGE FROM INPUT TO DATE PICKER (MONTH/YEAR) */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-muted-foreground mb-1 block">From Year</label>
              <input 
                type="month"
                value={exp.fromYear || ""} 
                onChange={(e) => { 
                  const updated = [...tempInvestorExperience]; 
                  updated[idx].fromYear = e.target.value; 
                  setTempInvestorExperience(updated); 
                }} 
                className="w-full rounded-lg bg-secondary/50 border border-border/50 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>
            <div>
              <label className="text-xs text-muted-foreground mb-1 block">To Year</label>
              <input 
                type="month"
                value={exp.toYear || ""} 
                onChange={(e) => { 
                  const updated = [...tempInvestorExperience]; 
                  updated[idx].toYear = e.target.value; 
                  setTempInvestorExperience(updated); 
                }} 
                className="w-full rounded-lg bg-secondary/50 border border-border/50 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>
          </div>
        </div>
      ))}
      
      <button 
        onClick={() => {
          setTempInvestorExperience([
            ...tempInvestorExperience, 
            { role: "", company: "", fromYear: "", toYear: "" }
          ]);
        }} 
        className="flex items-center gap-2 text-sm text-primary hover:text-primary/80 mt-2 cursor-pointer"
      >
        <Plus className="h-4 w-4" /> Add Experience
      </button>
    </div>
  }
>
      {/* Display Section */}
      <div className="space-y-3">
        {investorExperience.length === 0 ? 
          <p className="text-sm text-muted-foreground">No experience added yet</p> : 
          investorExperience.map((exp, idx) => (
            <div key={idx}>
              <p className="font-medium text-foreground">{exp.role}</p>
              <p className="text-sm text-muted-foreground">{exp.company}</p>
              <p className="text-xs text-muted-foreground mt-1">
                {exp.fromYear && `${exp.fromYear} - `}{exp.toYear || ""}
              </p>
            </div>
          ))
        }
      </div>
    </EditableSection>


    {/* ✅ NEW: Looking For / Categories Section for Investor */}
    <EditableSection 
      title={getSectionTitle("exploring_categories") || "Interested Categories"} 
      icon={Target} 
      isEditing={editingSection === "investorLookingFor"} 
      onEdit={() => startEditing("investorLookingFor")} 
      onSave={saveInvestorLookingFor} 
      onCancel={cancelEditing}
      saving={saving}
      editContent={
        <div>
          <div className="flex flex-wrap gap-2 mb-3">
            {lookingFor.map((item, idx) => (
              <span key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-secondary text-sm">
                {item}
                <button onClick={() => setLookingFor(lookingFor.filter((_, i) => i !== idx))} className="cursor-pointer">
                  <X className="h-3 w-3" />
                </button>
              </span>
            ))}
          </div>
          <div className="flex gap-2">
            <select 
              value={newLookingFor} 
              onChange={(e) => setNewLookingFor(e.target.value)} 
              className="flex-1 rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm cursor-pointer"
            >
              <option value="">Select a category</option>
              {allCategories.map((cat) => (
                <option key={cat._id} value={cat.mainCategoryName}>{cat.mainCategoryName}</option>
              ))}
            </select>
            <Button 
              onClick={() => { 
                if (newLookingFor && !lookingFor.includes(newLookingFor) && lookingFor.length < 5) { 
                  setLookingFor([...lookingFor, newLookingFor]); 
                  setNewLookingFor(""); 
                } else if (lookingFor.length >= 5) { 
                  toast.warning("Maximum 5 categories allowed"); 
                } 
              }} 
              size="icon"
              className="cursor-pointer"
            >
              <Plus className="h-4 w-4" />
            </Button>
          </div>
          <p className="text-xs text-muted-foreground mt-2">Select categories you're interested in (Max 5)</p>
        </div>
      }
    >
      <div className="flex flex-wrap gap-2">
        {lookingFor.map((item, idx) => (
          <span key={idx} className="px-3 py-1.5 rounded-full bg-primary/10 text-primary text-sm border border-primary/20">
            {item}
          </span>
        ))}
        {lookingFor.length === 0 && (
          <p className="text-sm text-muted-foreground">No categories selected</p>
        )}
      </div>
    </EditableSection>



<EditableSection 
  title="Sector Focus" 
  icon={Target} 
  isEditing={editingSection === "sectorFocus"} 
  onEdit={() => {
    setTempSectorFocus([...sectorFocus]);
    setEditingSection("sectorFocus");
  }} 
  onSave={saveSectorFocus} 
  onCancel={() => {
    setTempSectorFocus([...sectorFocus]);
    setEditingSection(null);
  }}
  saving={saving}
  editContent={
    <div className="space-y-3">
      {/* Selected Categories Preview */}
      {tempSectorFocus.length > 0 && (
        <div className="flex flex-wrap gap-2 mb-3 pb-3 border-b border-border/50">
          {tempSectorFocus.map((sector, idx) => (
            <div key={idx} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-500/10 text-emerald-400 text-sm border border-emerald-500/20">
              {sector.name}
              <button 
                type="button"
                onClick={() => setTempSectorFocus(tempSectorFocus.filter((_, i) => i !== idx))}
                className="cursor-pointer hover:text-red-400 transition-colors"
              >
                <X className="h-3 w-3" />
              </button>
            </div>
          ))}
        </div>
      )}
      
      {/* Search Input */}
      <div className="relative">
        <input
          type="text"
          placeholder="Search sectors..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
        />
      </div>
      
      {/* Categories List with Checkboxes */}
      <div className="max-h-48 overflow-y-auto border border-border/50 rounded-lg custom-scrollbar">
        {allCategories
          .filter((cat) => 
            cat.mainCategoryName.toLowerCase().includes(searchTerm.toLowerCase())
          )
          .map((cat) => {
            const isSelected = tempSectorFocus.some(s => s.name === cat.mainCategoryName);
            return (
              <label 
                key={cat._id} 
                className={`flex items-center gap-3 p-3 cursor-pointer transition-colors hover:bg-secondary/30 ${
                  isSelected ? 'bg-emerald-500/5' : ''
                }`}
              >
                <input
                  type="checkbox"
                  checked={isSelected}
                  onChange={(e) => {
                    if (e.target.checked) {
                      if (tempSectorFocus.length < 5) {
                        setTempSectorFocus([...tempSectorFocus, { name: cat.mainCategoryName }]);
                      } else {
                        toast.warning("Maximum 5 sectors allowed");
                      }
                    } else {
                      setTempSectorFocus(tempSectorFocus.filter(s => s.name !== cat.mainCategoryName));
                    }
                  }}
                  className="h-4 w-4 rounded border-border cursor-pointer accent-emerald-500"
                />
                <span className="text-sm text-foreground">{cat.mainCategoryName}</span>
              </label>
            );
          })}
        
        {allCategories.filter(cat => 
          cat.mainCategoryName.toLowerCase().includes(searchTerm.toLowerCase())
        ).length === 0 && (
          <div className="text-center py-8 text-muted-foreground text-sm">
            No sectors found
          </div>
        )}
      </div>
      
      <div className="flex justify-between items-center text-xs text-muted-foreground">
        <span>Selected: {tempSectorFocus.length}/5</span>
        <span>✓ Select up to 5 sectors</span>
      </div>
    </div>
  }
>
  <div className="flex flex-wrap gap-2">
    {sectorFocus.length === 0 ? (
      <p className="text-sm text-muted-foreground">No sectors added yet</p>
    ) : (
      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>
</EditableSection>
  </>
)}
           

          {/* Common Sections */}
          <div className="rounded-2xl glass glass-border p-5">
            <h3 className="font-semibold text-foreground mb-1">Appearance</h3>
            <p className="text-xs text-muted-foreground mb-4">Choose how CheckUrIdea looks to you.</p>
            <ThemeToggle />
          </div>

          {/* More Settings - Coming Soon */}
          <div className="rounded-2xl glass glass-border p-5 opacity-60">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-foreground">More Settings</h3>
              <span className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-gray-500/20 text-gray-500 text-xs">
                <Clock className="h-3 w-3" />
                Coming Soon
              </span>
            </div>
            <div className="space-y-2">
              <div className="flex items-center gap-3 rounded-xl px-4 py-3 opacity-50 cursor-not-allowed">
                <Shield className="h-5 w-5 text-muted-foreground" />
                <span className="text-sm text-muted-foreground">Privacy Settings</span>
              </div>
              <div className="flex items-center gap-3 rounded-xl px-4 py-3 opacity-50 cursor-not-allowed">
                <Bell className="h-5 w-5 text-muted-foreground" />
                <span className="text-sm text-muted-foreground">Notification Preferences</span>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}