// app/settings/profile/page.tsx
"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,
  TrendingUp,
  FileText,
} from "lucide-react";
import {
  updateProfile,
  getBusinessProfile,
  updateBusinessProfile,
  getInvestorProfile,
  updateInvestorProfile,
  getAllAnnualIncomeRanges,
  getAllNetWorthOptions,
  getAllBusinessTypes,
} from "@/lib/api/client";
import { toast } from "sonner";

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;
}

function EditableSection({
  title,
  icon: Icon,
  children,
  editContent,
  isEditing,
  onEdit,
  onSave,
  onCancel,
}: 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">
            <Pencil className="h-4 w-4" />
            Edit
          </Button>
        ) : (
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="sm" onClick={onCancel}>
              <X className="h-4 w-4" />
            </Button>
            <Button size="sm" onClick={onSave} className="gap-2">
              <Check className="h-4 w-4" />
              Save
            </Button>
          </div>
        )}
      </div>
      <div className="p-5">{isEditing ? editContent : children}</div>
    </div>
  );
}

export default function ProfileSettingsPage() {
  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);

  // 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 }>
  >([]);

  

  // Get user type from Redux
  const customer = currentCustomer?.customer || currentCustomer;
  const userType = customer?.isBusinessUser
    ? "business"
    : customer?.isInvestor
      ? "investor"
      : "individual";

 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;
};


  // ========== DYNAMIC PROFILE DATA ==========
  const [profile, setProfile] = useState({
    fullName: "",
    userName: "",
    aboutMe: "",
    location: "",
    website: "",
    linkedin: "",
    twitter: "",
    imageURL: "",
    designation: "",
    gender: "",
    socialMedia: [] as { link: string; type: string; userName?: string }[],
  });

  const [tempProfile, setTempProfile] = useState(profile);

  // ========== BUSINESS DYNAMIC DATA ==========
  const [companyInfo, setCompanyInfo] = useState({
    companyName: "",
    businessType: "",
    industry: "",
    founded: "",
    size: "",
    description: "",
    headquarters: "",
    annualRevenue: "",
      whatWeOffer: [] as { title: string; description: string }[], 
  });

  const [tempCompanyInfo, setTempCompanyInfo] = useState(companyInfo);

  // ========== INVESTOR DYNAMIC DATA ==========
  const [investorInfo, setInvestorInfo] = useState({
    businessName: "",
    annualIncomeRange: "",
    netWorth: "",
    investorType: "Angel Investor",
    investmentRange: "10L - 1Cr",
    totalInvested: "5Cr+",
    activeDeals: "8",
  });

  const [tempInvestorInfo, setTempInvestorInfo] = useState(investorInfo);

  // ========== STATIC SECTIONS ==========

  // Individual specific - static
  const [education, setEducation] = useState([
    { id: 1, degree: "MBA", institution: "IIM Ahmedabad", year: "2020" },
    { id: 2, degree: "B.Tech CS", institution: "IIT Delhi", year: "2018" },
  ]);

  const [experience, setExperience] = useState([
    {
      id: 1,
      role: "Founder & CEO",
      company: "TechStartup",
      duration: "2020 - Present",
    },
    {
      id: 2,
      role: "Product Manager",
      company: "Google",
      duration: "2018 - 2020",
    },
  ]);

  const [skills, setSkills] = useState([
    "Product Management",
    "AI/ML",
    "Startup Strategy",
    "Fundraising",
  ]);
  const [newSkill, setNewSkill] = useState("");
  const [newEducation, setNewEducation] = useState({
    degree: "",
    institution: "",
    year: "",
  });
  const [newExperience, setNewExperience] = useState({
    role: "",
    company: "",
    duration: "",
  });

  // Business specific - static
  const [lookingFor, setLookingFor] = useState([
    "AI/ML Solutions",
    "Supply Chain Innovation",
    "Green Technology",
  ]);
  const [newLookingFor, setNewLookingFor] = useState("");

  const [benefits, setBenefits] = useState([
    {
      id: 1,
      title: "Funding Support",
      description: "Up to 50L for promising ideas",
    },
    { id: 2, title: "Mentorship", description: "Access to industry experts" },
  ]);

  const [keyPeople, setKeyPeople] = useState([
    { id: 1, name: "Rajesh Kumar", role: "CEO", avatar: "RK" },
    { id: 2, name: "Priya Singh", role: "CTO", avatar: "PS" },
  ]);

  // Investor specific - static
  const [sectors, setSectors] = useState([
    { id: 1, name: "Technology", allocation: 40 },
    { id: 2, name: "Healthcare", allocation: 30 },
    { id: 3, name: "FinTech", allocation: 30 },
  ]);

  const [criteria, setCriteria] = useState([
    "Strong founding team",
    "Clear market opportunity",
    "Scalable business model",
    "Early traction",
  ]);
  const [newCriteria, setNewCriteria] = useState("");

  const [portfolio, setPortfolio] = useState([
    { id: 1, company: "HealthTech AI", status: "Active", invested: "25L" },
    { id: 2, company: "EduLearn", status: "Exited 3x", invested: "15L" },
  ]);


  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 successfully");
      setEditingSection(null);
    } else {
      toast.error(response.message || "Failed to update");
    }
  } catch (error) {
    console.error("Error saving what we offer:", error);
    toast.error("Failed to save changes");
  } finally {
    setSaving(false);
  }
};


  // Fetch dropdown options
  useEffect(() => {
    const fetchDropdownOptions = async () => {
      try {
        const [incomeResponse, netWorthResponse, businessTypesResponse] =
          await Promise.all([
            getAllAnnualIncomeRanges(),
            getAllNetWorthOptions(),
            getAllBusinessTypes(),
          ]);

        if (incomeResponse.success && incomeResponse.data) {
          setIncomeRanges(incomeResponse.data);
        }

        if (netWorthResponse.success && netWorthResponse.data) {
          setNetWorthOptions(netWorthResponse.data);
        }

        if (businessTypesResponse.success && businessTypesResponse.data) {
          setBusinessTypes(businessTypesResponse.data);
        }
      } catch (error) {
        console.error("Error fetching dropdown options:", error);
      }
    };

    fetchDropdownOptions();
  }, []);

  useEffect(() => {
    if (accessToken) {
      if (userType === "individual") {
        fetchIndividualProfile();
      } else if (userType === "business") {
        fetchBusinessProfile();
      } else if (userType === "investor") {
        fetchInvestorProfile();
      }
    }
  }, [accessToken, userType]);

  // ✅ FIX: For individual user - use data from Redux currentCustomer
  const fetchIndividualProfile = async () => {
    try {
      setLoading(true);

      // Individual user data already in Redux
      const data = customer;

      if (data) {
        // Extract social links
        let linkedin = "";
        let twitter = "";
        let 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;
          });
        }

        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 || "",
          socialMedia: data.socialMedia || [],
        });

        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 || "",
          socialMedia: data.socialMedia || [],
        });
      }
    } catch (error) {
      console.error("Error fetching profile:", error);
      toast.error("Failed to load profile");
    } 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;

        if (business) {
          // Set profile info from business personalInfo
          setProfile({
            fullName: business.personalInfo?.fullName || "",
            userName: business.personalInfo?.userName?.replace("@", "") || "",
            aboutMe: business.personalInfo?.aboutMe || "",
            location: business.personalInfo?.country || "",
            website:
              business.personalInfo?.socialMedia?.find(
                (s: any) => s.type === "website",
              )?.link || "",
            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 || [],
          });

          setTempProfile({
            fullName: business.personalInfo?.fullName || "",
            userName: business.personalInfo?.userName?.replace("@", "") || "",
            aboutMe: business.personalInfo?.aboutMe || "",
            location: business.personalInfo?.country || "",
            website:
              business.personalInfo?.socialMedia?.find(
                (s: any) => s.type === "website",
              )?.link || "",
            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 || [],
          });

          // ✅ Update company info with new fields
        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 || [],     
        });
        }
      }
    } catch (error) {
      console.error("Error fetching business profile:", error);
      toast.error("Failed to load business profile");
    } finally {
      setLoading(false);
    }
  };

  const fetchInvestorProfile = async () => {
    try {
      setLoading(true);
      const response = await getInvestorProfile();


      if (response.success && response.data) {
        // ✅ Business jaisa hi - data personalInfo ke andar
        const investor = response.data;
        const personalInfo = investor.personalInfo || {};
        const investorInfoData = investor.investorInfo || {};


        // Set profile info from personalInfo
        setProfile({
          fullName: personalInfo.fullName || "",
          userName: personalInfo.userName?.replace("@", "") || "",
          aboutMe: personalInfo.aboutMe || "",
          location: personalInfo.country || "",
          website:
            personalInfo.socialMedia?.find((s: any) => s.type === "website")
              ?.link || "",
          linkedin:
            personalInfo.socialMedia?.find((s: any) => s.type === "linkedin")
              ?.link || "",
          twitter:
            personalInfo.socialMedia?.find((s: any) => s.type === "twitter")
              ?.link || "",
          imageURL: personalInfo.imageURL || "",
          designation: personalInfo.designation || "",
          gender: personalInfo.gender || "",
          socialMedia: personalInfo.socialMedia || [],
        });

        setTempProfile({
          fullName: personalInfo.fullName || "",
          userName: personalInfo.userName?.replace("@", "") || "",
          aboutMe: personalInfo.aboutMe || "",
          location: personalInfo.country || "",
          website:
            personalInfo.socialMedia?.find((s: any) => s.type === "website")
              ?.link || "",
          linkedin:
            personalInfo.socialMedia?.find((s: any) => s.type === "linkedin")
              ?.link || "",
          twitter:
            personalInfo.socialMedia?.find((s: any) => s.type === "twitter")
              ?.link || "",
          imageURL: personalInfo.imageURL || "",
          designation: personalInfo.designation || "",
          gender: personalInfo.gender || "",
          socialMedia: personalInfo.socialMedia || [],
        });

        // Set investor specific info
        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",
        });
      } else {
        console.error("Failed to fetch investor profile:", response.message);
        toast.error(response.message || "Failed to load investor profile");
      }
    } catch (error) {
      console.error("Error fetching investor profile:", error);
      toast.error("Failed to load investor profile");
    } finally {
      setLoading(false);
    }
  };

  const startEditing = (section: string) => {
    if (section === "company") {
      setTempCompanyInfo(companyInfo);
    } else if (section === "investorProfile") {
      setTempInvestorInfo(investorInfo);
    } else {
      setTempProfile(profile);
    }
    setEditingSection(section);
  };

// app/settings/profile/page.tsx - Update saveBasicInfo for business user

const saveBasicInfo = async () => {
  try {
    setSaving(true);
    
    if (userType === "business") {
      // ✅ Business user ke liye updateBusinessProfile use karo
      const updateData = {
        fullName: tempProfile.fullName,
        aboutMe: tempProfile.aboutMe,
        designation: tempProfile.designation,
        gender: tempProfile.gender,
        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 successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update profile");
      }
    } else {
      // Individual/Investor ke liye updateProfile
      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);
      
      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 successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update profile");
      }
    }
  } catch (error) {
    console.error("Error saving profile:", error);
    toast.error("Failed to save changes");
  } finally {
    setSaving(false);
  }
};

const saveLocation = async () => {
  try {
    setSaving(true);
    
    if (userType === "business") {
      // Business user - update personalInfo.country
      const updateData = {
        country: tempProfile.location
      };
      const response = await updateBusinessProfile(updateData, "", accessToken!);
      
      if (response.success) {
        setProfile(tempProfile);
        toast.success("Location updated successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update location");
      }
    } else {
      // Individual/Investor - use updateProfile
      const formData = new FormData();
      formData.append("country", tempProfile.location);
      const response = await updateProfile(formData, accessToken!);
      
      if (response.success) {
        setProfile(tempProfile);
        toast.success("Location updated successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update location");
      }
    }
  } catch (error) {
    console.error("Error saving location:", error);
    toast.error("Failed to save changes");
  } finally {
    setSaving(false);
  }
};

const saveSocialLinks = async () => {
  try {
    setSaving(true);
    
    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" });
    
    if (userType === "business") {
      // Business user - update socialMedia in personalInfo
      const updateData = {
        socialMedia: socialMedia
      };
      const response = await updateBusinessProfile(updateData, "", accessToken!);
      
      if (response.success) {
        setProfile(tempProfile);
        toast.success("Social links updated successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update social links");
      }
    } else {
      // Individual/Investor
      const formData = new FormData();
      formData.append("links", JSON.stringify(socialMedia.map(s => s.link)));
      const response = await updateProfile(formData, accessToken!);
      
      if (response.success) {
        setProfile(tempProfile);
        toast.success("Social links updated successfully");
        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 information updated successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update company information");
      }
    } catch (error) {
      console.error("Error saving company info:", 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, "");

      if (response.success) {
        setInvestorInfo(tempInvestorInfo);
        toast.success("Investor profile updated successfully");
        setEditingSection(null);
      } else {
        toast.error(response.message || "Failed to update investor profile");
      }
    } catch (error) {
      console.error("Error saving investor profile:", error);
      toast.error("Failed to save changes");
    } finally {
      setSaving(false);
    }
  };

  const cancelEditing = () => {
    if (editingSection === "company") {
      setTempCompanyInfo(companyInfo);
    } else if (editingSection === "investorProfile") {
      setTempInvestorInfo(investorInfo);
    } 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: CircleDollarSign,
      color: "text-emerald-400 border-emerald-400 bg-emerald-400/10",
    },
  };

  const currentConfig = userTypeConfig[userType];
  const CurrentIcon = currentConfig.icon;
 

  // Safe name for avatar
  const displayName = profile.fullName || "User";
  const getInitial = () => (displayName.charAt(0) || "U").toUpperCase();

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Sidebar />
        <div className="lg:pl-72">
          <div className="flex justify-center items-center h-screen">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Sidebar />

      <div className="lg:pl-72">
        {/* Header */}
        <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">
                <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">
              <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">
                <div className="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">
                  {profile.imageURL ? (
                    <img
                      src={`${process.env.NEXT_PUBLIC_BASE_URL}/uploads/${profile.imageURL}`}
                      alt={displayName}
                      className="w-full h-full object-cover rounded-2xl"
                    />
                  ) : (
                    getInitial()
                  )}
                </div>
                <button className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity">
                  <Camera className="h-6 w-6 text-white" />
                </button>
              </div>
              <div className="flex-1">
                <h2 className="text-xl font-bold text-foreground mb-1">
                  {displayName}
                </h2>
                <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>
                )}
                <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" />
                    {currentConfig.label}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Basic Info - Dynamic */}
          <EditableSection
            title="Basic Information"
            icon={User}
            isEditing={editingSection === "basic"}
            onEdit={() => startEditing("basic")}
            onSave={saveBasicInfo}
            onCancel={cancelEditing}
            editContent={
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">
                    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">
                    Username
                  </label>
                  <div className="flex">
                    <span className="px-3 py-2 rounded-l-lg bg-secondary border border-r-0 border-border text-sm text-muted-foreground">
                      checkuridea.com/
                    </span>
                    <Input
                      value={tempProfile.userName}
                      onChange={(e) =>
                        setTempProfile({
                          ...tempProfile,
                          userName: e.target.value
                            .toLowerCase()
                            .replace(/[^a-z0-9_]/g, ""),
                        })
                      }
                      className="rounded-l-none bg-secondary/30"
                    />
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">
                    Designation / Title
                  </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">
                    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">
                    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>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                    <option value="Others">Others</option>
                  </select>
                </div>
              </div>
            }
          >
            <div className="space-y-2">
              <p className="text-foreground font-medium">{displayName}</p>
              <p className="text-sm text-primary">
                @{profile.userName || "user"}
              </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 - Dynamic */}
          <EditableSection
            title="Location"
            icon={MapPin}
            isEditing={editingSection === "location"}
            onEdit={() => startEditing("location")}
            onSave={saveLocation}
            onCancel={cancelEditing}
            editContent={
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">
                    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>
            }
          >
            <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>
            </div>
          </EditableSection>

          {/* Social Links - Dynamic */}
          <EditableSection
            title="Social Links"
            icon={Link2}
            isEditing={editingSection === "social"}
            onEdit={() => startEditing("social")}
            onSave={saveSocialLinks}
            onCancel={cancelEditing}
            editContent={
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-foreground mb-1.5 block">
                    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">
                    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">
                    Twitter / X
                  </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"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-4 py-2 rounded-xl bg-secondary/50 hover:bg-secondary transition-colors text-sm"
                >
                  <Globe className="h-4 w-4" />
                  Website
                </a>
              )}
              {profile.linkedin && (
                <a
                  href={profile.linkedin}
                  target="_blank"
                  rel="noopener noreferrer"
                  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"
                >
                  <Linkedin className="h-4 w-4" />
                  LinkedIn
                </a>
              )}
              {profile.twitter && (
                <a
                  href={profile.twitter}
                  target="_blank"
                  rel="noopener noreferrer"
                  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"
                >
                  <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="Education"
                icon={GraduationCap}
                isEditing={editingSection === "education"}
                onEdit={() => startEditing("education")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div className="space-y-3">
                    {education.map((edu, idx) => (
                      <div
                        key={edu.id}
                        className="flex items-start gap-3 p-3 rounded-xl bg-secondary/30"
                      >
                        <div className="flex-1 space-y-2">
                          <Input
                            defaultValue={edu.degree}
                            onChange={(e) => {
                              const updated = [...education];
                              updated[idx].degree = e.target.value;
                              setEducation(updated);
                            }}
                            placeholder="Degree"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={edu.institution}
                            onChange={(e) => {
                              const updated = [...education];
                              updated[idx].institution = e.target.value;
                              setEducation(updated);
                            }}
                            placeholder="Institution"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={edu.year}
                            onChange={(e) => {
                              const updated = [...education];
                              updated[idx].year = e.target.value;
                              setEducation(updated);
                            }}
                            placeholder="Year"
                            className="bg-secondary/50"
                          />
                        </div>
                        <button
                          onClick={() =>
                            setEducation(education.filter((_, i) => i !== idx))
                          }
                          className="text-destructive hover:text-destructive/80 p-2"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    ))}
                    <div className="flex gap-2 mt-2">
                      <Input
                        value={newEducation.degree}
                        onChange={(e) =>
                          setNewEducation({
                            ...newEducation,
                            degree: e.target.value,
                          })
                        }
                        placeholder="Degree"
                        className="bg-secondary/30"
                      />
                      <Input
                        value={newEducation.institution}
                        onChange={(e) =>
                          setNewEducation({
                            ...newEducation,
                            institution: e.target.value,
                          })
                        }
                        placeholder="Institution"
                        className="bg-secondary/30"
                      />
                      <Input
                        value={newEducation.year}
                        onChange={(e) =>
                          setNewEducation({
                            ...newEducation,
                            year: e.target.value,
                          })
                        }
                        placeholder="Year"
                        className="bg-secondary/30 w-24"
                      />
                      <Button
                        onClick={() => {
                          if (newEducation.degree && newEducation.institution) {
                            setEducation([
                              ...education,
                              { id: Date.now(), ...newEducation },
                            ]);
                            setNewEducation({
                              degree: "",
                              institution: "",
                              year: "",
                            });
                          }
                        }}
                        size="icon"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                }
              >
                <div className="space-y-3">
                  {education.map((edu) => (
                    <div key={edu.id}>
                      <p className="font-medium text-foreground">
                        {edu.degree}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        {edu.institution} - {edu.year}
                      </p>
                    </div>
                  ))}
                </div>
              </EditableSection>

              <EditableSection
                title="Work Experience"
                icon={Briefcase}
                isEditing={editingSection === "experience"}
                onEdit={() => startEditing("experience")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div className="space-y-3">
                    {experience.map((exp, idx) => (
                      <div
                        key={exp.id}
                        className="flex items-start gap-3 p-3 rounded-xl bg-secondary/30"
                      >
                        <div className="flex-1 space-y-2">
                          <Input
                            defaultValue={exp.role}
                            onChange={(e) => {
                              const updated = [...experience];
                              updated[idx].role = e.target.value;
                              setExperience(updated);
                            }}
                            placeholder="Role"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={exp.company}
                            onChange={(e) => {
                              const updated = [...experience];
                              updated[idx].company = e.target.value;
                              setExperience(updated);
                            }}
                            placeholder="Company"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={exp.duration}
                            onChange={(e) => {
                              const updated = [...experience];
                              updated[idx].duration = e.target.value;
                              setExperience(updated);
                            }}
                            placeholder="Duration"
                            className="bg-secondary/50"
                          />
                        </div>
                        <button
                          onClick={() =>
                            setExperience(
                              experience.filter((_, i) => i !== idx),
                            )
                          }
                          className="text-destructive hover:text-destructive/80 p-2"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    ))}
                    <div className="flex gap-2 mt-2">
                      <Input
                        value={newExperience.role}
                        onChange={(e) =>
                          setNewExperience({
                            ...newExperience,
                            role: e.target.value,
                          })
                        }
                        placeholder="Role"
                        className="bg-secondary/30 flex-1"
                      />
                      <Input
                        value={newExperience.company}
                        onChange={(e) =>
                          setNewExperience({
                            ...newExperience,
                            company: e.target.value,
                          })
                        }
                        placeholder="Company"
                        className="bg-secondary/30 flex-1"
                      />
                      <Input
                        value={newExperience.duration}
                        onChange={(e) =>
                          setNewExperience({
                            ...newExperience,
                            duration: e.target.value,
                          })
                        }
                        placeholder="Duration"
                        className="bg-secondary/30 w-32"
                      />
                      <Button
                        onClick={() => {
                          if (newExperience.role && newExperience.company) {
                            setExperience([
                              ...experience,
                              { id: Date.now(), ...newExperience },
                            ]);
                            setNewExperience({
                              role: "",
                              company: "",
                              duration: "",
                            });
                          }
                        }}
                        size="icon"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                }
              >
                <div className="space-y-3">
                  {experience.map((exp) => (
                    <div key={exp.id}>
                      <p className="font-medium text-foreground">{exp.role}</p>
                      <p className="text-sm text-muted-foreground">
                        {exp.company} - {exp.duration}
                      </p>
                    </div>
                  ))}
                </div>
              </EditableSection>

              <EditableSection
                title="Skills & Interests"
                icon={Award}
                isEditing={editingSection === "skills"}
                onEdit={() => startEditing("skills")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div>
                    <div className="flex flex-wrap gap-2 mb-3">
                      {skills.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={() =>
                              setSkills(skills.filter((_, i) => i !== idx))
                            }
                            className="text-muted-foreground hover:text-destructive"
                          >
                            <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()) {
                            setSkills([...skills, newSkill.trim()]);
                            setNewSkill("");
                          }
                        }}
                      />
                      <Button
                        onClick={() => {
                          if (newSkill.trim()) {
                            setSkills([...skills, newSkill.trim()]);
                            setNewSkill("");
                          }
                        }}
                        size="icon"
                      >
                        <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-primary/10 text-primary text-sm"
                    >
                      {skill}
                    </span>
                  ))}
                </div>
              </EditableSection>
            </>
          )}

          {/* ========== BUSINESS SECTIONS ========== */}
          {userType === "business" && (
            <>
             <EditableSection
  title="Company Information"
  icon={Building2}
  isEditing={editingSection === "company"}
  onEdit={() => startEditing("company")}
  onSave={saveCompanyInfo}
  onCancel={cancelEditing}
  editContent={
    <div className="space-y-4">
      <div>
        <label className="text-sm font-medium text-foreground mb-1.5 block">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 text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
        >
          <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">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 text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none" 
          placeholder="Tell us about your company..."
        />
      </div>
      <div>
        <label className="text-sm font-medium text-foreground mb-1.5 block">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">Founded Year</label>
          <Input 
            value={tempCompanyInfo.founded} 
            onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, founded: e.target.value})} 
            className="bg-secondary/30" 
            placeholder="e.g., 2015" 
          />
        </div>
        <div>
          <label className="text-sm font-medium text-foreground mb-1.5 block">Company Size</label>
          <Input 
            value={tempCompanyInfo.size} 
            onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, size: e.target.value})} 
            className="bg-secondary/30" 
            placeholder="e.g., 50-100 employees" 
          />
        </div>
      </div>
      <div>
        <label className="text-sm font-medium text-foreground mb-1.5 block">Headquarters</label>
        <Input 
          value={tempCompanyInfo.headquarters} 
          onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, headquarters: 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">Annual Revenue</label>
        <Input 
          value={tempCompanyInfo.annualRevenue} 
          onChange={(e) => setTempCompanyInfo({...tempCompanyInfo, annualRevenue: e.target.value})} 
          className="bg-secondary/30" 
          placeholder="e.g., ₹10 Cr - ₹50 Cr" 
        />
      </div>
    </div>
  }
>
  <div className="space-y-2">
    <p className="font-medium text-lg text-foreground">{companyInfo.companyName || "Not set"}</p>
    <div className="flex flex-wrap gap-3 text-sm text-muted-foreground">
      {companyInfo.businessType && <span>Type: {companyInfo.businessType.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}</span>}
    </div>
    {companyInfo.description && <p className="text-sm text-foreground mt-2">{companyInfo.description}</p>}
    <div className="grid grid-cols-2 gap-3 text-sm mt-3">
      {companyInfo.industry && <p className="text-foreground">Industry: {companyInfo.industry}</p>}
      {companyInfo.founded && <p className="text-foreground">Founded: {companyInfo.founded}</p>}
      {companyInfo.size && <p className="text-foreground">Size: {companyInfo.size}</p>}
      {companyInfo.headquarters && <p className="text-foreground">Headquarters: {companyInfo.headquarters}</p>}
      {companyInfo.annualRevenue && <p className="text-foreground">Annual Revenue: {companyInfo.annualRevenue}</p>}
    </div>
  </div>
</EditableSection>

              <EditableSection
                title="Ideas We're Looking For"
                icon={Target}
                isEditing={editingSection === "lookingFor"}
                onEdit={() => startEditing("lookingFor")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                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="text-muted-foreground hover:text-destructive"
                          >
                            <X className="h-3 w-3" />
                          </button>
                        </span>
                      ))}
                    </div>
                    <div className="flex gap-2">
                      <Input
                        value={newLookingFor}
                        onChange={(e) => setNewLookingFor(e.target.value)}
                        placeholder="Add category"
                        className="bg-secondary/30"
                        onKeyDown={(e) => {
                          if (e.key === "Enter" && newLookingFor.trim()) {
                            setLookingFor([
                              ...lookingFor,
                              newLookingFor.trim(),
                            ]);
                            setNewLookingFor("");
                          }
                        }}
                      />
                      <Button
                        onClick={() => {
                          if (newLookingFor.trim()) {
                            setLookingFor([
                              ...lookingFor,
                              newLookingFor.trim(),
                            ]);
                            setNewLookingFor("");
                          }
                        }}
                        size="icon"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                  </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>
                  ))}
                </div>
              </EditableSection>


<EditableSection
  title="What We Offer"
  icon={Award}
  isEditing={editingSection === "whatWeOffer"}
  onEdit={() => startEditing("whatWeOffer")}
  onSave={saveWhatWeOffer}
  onCancel={cancelEditing}
  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"
              className="bg-secondary/50"
            />
            <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 text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
            />
          </div>
          <button
            onClick={() => {
              const updated = tempCompanyInfo.whatWeOffer.filter((_, i) => i !== idx);
              setTempCompanyInfo({...tempCompanyInfo, whatWeOffer: updated});
            }}
            className="text-destructive hover:text-destructive/80 p-2"
          >
            <Trash2 className="h-4 w-4" />
          </button>
        </div>
      ))}
      <button
        onClick={() => {
          setTempCompanyInfo({
            ...tempCompanyInfo,
            whatWeOffer: [...tempCompanyInfo.whatWeOffer, { title: "", description: "" }]
          });
        }}
        className="flex items-center gap-2 text-sm text-amber-400 hover:text-amber-400/80 mt-2"
      >
        <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 text-foreground">{offer.title}</p>
            <p className="text-sm text-muted-foreground">{offer.description}</p>
          </div>
        </div>
      ))
    )}
  </div>
</EditableSection>

              <EditableSection
                title="Key People"
                icon={Users}
                isEditing={editingSection === "keyPeople"}
                onEdit={() => startEditing("keyPeople")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div className="space-y-3">
                    {keyPeople.map((person, idx) => (
                      <div
                        key={person.id}
                        className="flex items-center gap-3 p-3 rounded-xl bg-secondary/30"
                      >
                        <div className="flex-1 grid grid-cols-2 gap-2">
                          <Input
                            defaultValue={person.name}
                            placeholder="Name"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={person.role}
                            placeholder="Role"
                            className="bg-secondary/50"
                          />
                        </div>
                        <button
                          onClick={() =>
                            setKeyPeople(keyPeople.filter((_, i) => i !== idx))
                          }
                          className="text-destructive hover:text-destructive/80 p-2"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    ))}
                    <button
                      onClick={() =>
                        setKeyPeople([
                          ...keyPeople,
                          { id: Date.now(), name: "", role: "", avatar: "?" },
                        ])
                      }
                      className="flex items-center gap-2 text-sm text-amber-400 hover:text-amber-400/80 mt-2"
                    >
                      <Plus className="h-4 w-4" /> Add Person
                    </button>
                  </div>
                }
              >
                <div className="flex flex-wrap gap-4">
                  {keyPeople.map((person) => (
                    <div key={person.id} className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-amber-400/20 flex items-center justify-center text-amber-400 font-medium text-sm">
                        {person.avatar}
                      </div>
                      <div>
                        <p className="font-medium text-foreground text-sm">
                          {person.name}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {person.role}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              </EditableSection>
            </>
          )}

          {/* ========== INVESTOR SECTIONS ========== */}
          {userType === "investor" && (
            <>
              <EditableSection
                title="Investment Profile"
                icon={CircleDollarSign}
                isEditing={editingSection === "investorProfile"}
                onEdit={() => startEditing("investorProfile")}
                onSave={saveInvestorProfile}
                onCancel={cancelEditing}
                editContent={
                  <div className="space-y-4">
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">
                        Business / Company Name
                      </label>
                      <Input
                        value={tempInvestorInfo.businessName}
                        onChange={(e) =>
                          setTempInvestorInfo({
                            ...tempInvestorInfo,
                            businessName: e.target.value,
                          })
                        }
                        className="bg-secondary/30"
                        placeholder="Your business or company name"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">
                        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 text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                      >
                        <option value="">Select 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">
                        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 text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                      >
                        <option value="">Select Net Worth</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">
                        Investor Type
                      </label>
                      <select
                        value={tempInvestorInfo.investorType}
                        onChange={(e) =>
                          setTempInvestorInfo({
                            ...tempInvestorInfo,
                            investorType: 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>Angel Investor</option>
                        <option>Venture Capitalist</option>
                        <option>Private Equity</option>
                        <option>Family Office</option>
                      </select>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="text-sm font-medium text-foreground mb-1.5 block">
                          Investment Range
                        </label>
                        <Input
                          value={tempInvestorInfo.investmentRange}
                          onChange={(e) =>
                            setTempInvestorInfo({
                              ...tempInvestorInfo,
                              investmentRange: e.target.value,
                            })
                          }
                          className="bg-secondary/30"
                        />
                      </div>
                      <div>
                        <label className="text-sm font-medium text-foreground mb-1.5 block">
                          Total Invested
                        </label>
                        <Input
                          value={tempInvestorInfo.totalInvested}
                          onChange={(e) =>
                            setTempInvestorInfo({
                              ...tempInvestorInfo,
                              totalInvested: e.target.value,
                            })
                          }
                          className="bg-secondary/30"
                        />
                      </div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-foreground mb-1.5 block">
                        Active Deals
                      </label>
                      <Input
                        value={tempInvestorInfo.activeDeals}
                        onChange={(e) =>
                          setTempInvestorInfo({
                            ...tempInvestorInfo,
                            activeDeals: e.target.value,
                          })
                        }
                        className="bg-secondary/30"
                      />
                    </div>
                  </div>
                }
              >
                <div className="space-y-3">
                  <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}
                      </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}
                      </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.investmentRange}
                      </p>
                      <p className="text-xs text-muted-foreground">Range</p>
                    </div>
                    <div className="text-center p-3 rounded-xl bg-secondary/50">
                      <p className="text-sm font-bold text-foreground">
                        {investorInfo.investorType}
                      </p>
                      <p className="text-xs text-muted-foreground">Type</p>
                    </div>
                  </div>
                  {investorInfo.businessName && (
                    <p className="text-sm text-muted-foreground mt-2">
                      Business: {investorInfo.businessName}
                    </p>
                  )}
                  {investorInfo.annualIncomeRange && (
                    <p className="text-sm text-muted-foreground">
                      Income: {investorInfo.annualIncomeRange}
                    </p>
                  )}
                  {investorInfo.netWorth && (
                    <p className="text-sm text-muted-foreground">
                      Net Worth: {investorInfo.netWorth}
                    </p>
                  )}
                </div>
              </EditableSection>

              <EditableSection
                title="Investment Sectors"
                icon={TrendingUp}
                isEditing={editingSection === "sectors"}
                onEdit={() => startEditing("sectors")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div className="space-y-3">
                    {sectors.map((sector, idx) => (
                      <div
                        key={sector.id}
                        className="flex items-center gap-3 p-3 rounded-xl bg-secondary/30"
                      >
                        <div className="flex-1 grid grid-cols-2 gap-2">
                          <Input
                            defaultValue={sector.name}
                            placeholder="Sector"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={sector.allocation.toString()}
                            placeholder="%"
                            type="number"
                            className="bg-secondary/50"
                          />
                        </div>
                        <button
                          onClick={() =>
                            setSectors(sectors.filter((_, i) => i !== idx))
                          }
                          className="text-destructive hover:text-destructive/80 p-2"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    ))}
                    <button
                      onClick={() =>
                        setSectors([
                          ...sectors,
                          { id: Date.now(), name: "", allocation: 0 },
                        ])
                      }
                      className="flex items-center gap-2 text-sm text-emerald-400 hover:text-emerald-400/80 mt-2"
                    >
                      <Plus className="h-4 w-4" /> Add Sector
                    </button>
                  </div>
                }
              >
                <div className="space-y-3">
                  {sectors.map((sector) => (
                    <div key={sector.id}>
                      <div className="flex justify-between mb-1">
                        <span className="text-sm font-medium text-foreground">
                          {sector.name}
                        </span>
                        <span className="text-sm text-muted-foreground">
                          {sector.allocation}%
                        </span>
                      </div>
                      <div className="h-2 rounded-full bg-secondary overflow-hidden">
                        <div
                          className="h-full rounded-full bg-emerald-400"
                          style={{ width: `${sector.allocation}%` }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </EditableSection>

              <EditableSection
                title="Investment Criteria"
                icon={FileText}
                isEditing={editingSection === "criteria"}
                onEdit={() => startEditing("criteria")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div>
                    <ul className="space-y-2 mb-3">
                      {criteria.map((item, idx) => (
                        <li
                          key={idx}
                          className="flex items-center gap-2 p-2 rounded-lg bg-secondary/30"
                        >
                          <Check className="h-4 w-4 text-emerald-400 shrink-0" />
                          <span className="flex-1 text-sm">{item}</span>
                          <button
                            onClick={() =>
                              setCriteria(criteria.filter((_, i) => i !== idx))
                            }
                            className="text-muted-foreground hover:text-destructive"
                          >
                            <X className="h-4 w-4" />
                          </button>
                        </li>
                      ))}
                    </ul>
                    <div className="flex gap-2">
                      <Input
                        value={newCriteria}
                        onChange={(e) => setNewCriteria(e.target.value)}
                        placeholder="Add criteria"
                        className="bg-secondary/30"
                        onKeyDown={(e) => {
                          if (e.key === "Enter" && newCriteria.trim()) {
                            setCriteria([...criteria, newCriteria.trim()]);
                            setNewCriteria("");
                          }
                        }}
                      />
                      <Button
                        onClick={() => {
                          if (newCriteria.trim()) {
                            setCriteria([...criteria, newCriteria.trim()]);
                            setNewCriteria("");
                          }
                        }}
                        size="icon"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                }
              >
                <ul className="space-y-2">
                  {criteria.map((item, idx) => (
                    <li key={idx} className="flex items-center gap-2 text-sm">
                      <Check className="h-4 w-4 text-emerald-400" />
                      {item}
                    </li>
                  ))}
                </ul>
              </EditableSection>

              <EditableSection
                title="Portfolio Companies"
                icon={Briefcase}
                isEditing={editingSection === "portfolio"}
                onEdit={() => startEditing("portfolio")}
                onSave={() => setEditingSection(null)}
                onCancel={() => setEditingSection(null)}
                editContent={
                  <div className="space-y-3">
                    {portfolio.map((company, idx) => (
                      <div
                        key={company.id}
                        className="flex items-center gap-3 p-3 rounded-xl bg-secondary/30"
                      >
                        <div className="flex-1 grid grid-cols-3 gap-2">
                          <Input
                            defaultValue={company.company}
                            placeholder="Company"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={company.status}
                            placeholder="Status"
                            className="bg-secondary/50"
                          />
                          <Input
                            defaultValue={company.invested}
                            placeholder="Amount"
                            className="bg-secondary/50"
                          />
                        </div>
                        <button
                          onClick={() =>
                            setPortfolio(portfolio.filter((_, i) => i !== idx))
                          }
                          className="text-destructive hover:text-destructive/80 p-2"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    ))}
                    <button
                      onClick={() =>
                        setPortfolio([
                          ...portfolio,
                          {
                            id: Date.now(),
                            company: "",
                            status: "",
                            invested: "",
                          },
                        ])
                      }
                      className="flex items-center gap-2 text-sm text-emerald-400 hover:text-emerald-400/80 mt-2"
                    >
                      <Plus className="h-4 w-4" /> Add Company
                    </button>
                  </div>
                }
              >
                <div className="space-y-3">
                  {portfolio.map((company) => (
                    <div
                      key={company.id}
                      className="flex items-center justify-between p-3 rounded-xl bg-secondary/30"
                    >
                      <div>
                        <p className="font-medium text-foreground">
                          {company.company}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {company.status}
                        </p>
                      </div>
                      <span className="text-sm font-medium text-emerald-400">
                        {company.invested}
                      </span>
                    </div>
                  ))}
                </div>
              </EditableSection>
            </>
          )}

          {/* Appearance - Common */}
          <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 Links - Common */}
          <div className="rounded-2xl glass glass-border p-5">
            <h3 className="font-semibold text-foreground mb-4">
              More Settings
            </h3>
            <div className="space-y-2">
              <Link
                href="/settings/privacy"
                className="flex items-center gap-3 rounded-xl px-4 py-3 hover:bg-secondary/50 transition-colors"
              >
                <Shield className="h-5 w-5 text-muted-foreground" />
                <span className="text-sm text-foreground">
                  Privacy Settings
                </span>
              </Link>
              <Link
                href="/settings/notifications"
                className="flex items-center gap-3 rounded-xl px-4 py-3 hover:bg-secondary/50 transition-colors"
              >
                <Bell className="h-5 w-5 text-muted-foreground" />
                <span className="text-sm text-foreground">
                  Notification Preferences
                </span>
              </Link>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}
