const { useState } = React;

const CandidateAvatarTool = () => {
    console.log("Candidate Avatar Tool component is mounting");
    
    const [jobTitle, setJobTitle] = useState("");
    const [avatarData, setAvatarData] = useState({
    technicalSkills: ["", "", ""],
    softSkills: ["", "", ""],
    experience: "",
    education: "",
    certifications: [""],
    workStyle: "",
    });
    const [savedAvatars, setSavedAvatars] = useState([]);
    const [currentView, setCurrentView] = useState("form");
    const [sampleExperience, setSampleExperience] = useState(null);
    const [showSample, setShowSample] = useState(false);

    const handleSkillChange = (type, index, value) => {
    const newAvatarData = { ...avatarData };
    newAvatarData[type][index] = value;
    setAvatarData(newAvatarData);
    };

    const addSkill = (type) => {
    const newAvatarData = { ...avatarData };
    newAvatarData[type] = [...newAvatarData[type], ""];
    setAvatarData(newAvatarData);
    };

    const removeSkill = (type, index) => {
    const newAvatarData = { ...avatarData };
    newAvatarData[type] = newAvatarData[type].filter((_, i) => i !== index);
    setAvatarData(newAvatarData);
    };

    const handleChange = (field, value) => {
    setAvatarData({
        ...avatarData,
        [field]: value,
    });
    };

    const handleAddCertification = () => {
    setAvatarData({
        ...avatarData,
        certifications: [...avatarData.certifications, ""],
    });
    };

    const handleCertificationChange = (index, value) => {
    const newCertifications = [...avatarData.certifications];
    newCertifications[index] = value;
    setAvatarData({
        ...avatarData,
        certifications: newCertifications,
    });
    };

    const handleRemoveCertification = (index) => {
    const newCertifications = avatarData.certifications.filter((_, i) => i !== index);
    setAvatarData({
        ...avatarData,
        certifications: newCertifications,
    });
    };

    const getWorkStyleOptions = (selectedWorkStyle) => {
    const workStyleOptions = {
        "Independent": [
        "Self-motivated professional. Takes initiative on projects.",
        "Works effectively without supervision. Manages priorities independently.",
        "Independent worker. Completes tasks with minimal oversight.",
        "Takes ownership of deliverables. Requires little direction."
        ],
        "Collaborative": [
        "Team player. Builds consensus across departments.",
        "Collaborates effectively with diverse teams.",
        "Values input from all stakeholders.",
        "Thrives in team environments. Shares knowledge freely."
        ],
        "Leader": [
        "Natural leader. Motivates teams effectively.",
        "Guides projects to successful completion.",
        "Develops team capabilities. Sets clear expectations.",
        "Empowers team members. Provides meaningful feedback."
        ],
        "Flexible": [
        "Adapts to changing priorities. Remains productive.",
        "Handles uncertainty with composure.",
        "Pivots quickly as requirements change.",
        "Manages multiple tasks simultaneously."
        ],
        "Structured": [
        "Detail-oriented professional. Follows processes carefully.",
        "Maintains high quality standards.",
        "Thoroughly documents all work.",
        "Approaches problems methodically. Produces reliable results."
        ],
        "": [
        "Balances independence with teamwork.",
        "Professional with strong work ethic.",
        "Focuses on delivering quality outcomes.",
        "Approaches work with consistent professionalism."
        ]
    };
    
    // Return the array of options for the selected work style
    return workStyleOptions[selectedWorkStyle] || workStyleOptions[""];
    };

    const generateName = () => {
    const firstNames = [
        "Alex", "Jordan", "Taylor", "Casey", "Morgan", "Riley", "Avery", 
        "Quinn", "Cameron", "Reese", "Jamie", "Skyler", "Dakota", "Hayden", 
        "Parker", "Emerson", "Rowan", "Finley", "Blake", "Charlie"
    ];
    const lastNames = [
        "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", 
        "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", 
        "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson"
    ];
    
    return `${firstNames[Math.floor(Math.random() * firstNames.length)]} ${lastNames[Math.floor(Math.random() * lastNames.length)]}`;
    };
    
    const getMonthNumber = (monthName) => {
    const months = {
        "January": 0, "February": 1, "March": 2, "April": 3, 
        "May": 4, "June": 5, "July": 6, "August": 7, 
        "September": 8, "October": 9, "November": 10, "December": 11
    };
    return months[monthName] || 0;
    };
    
    const formatDuration = (months) => {
    const years = Math.floor(months / 12);
    const remainingMonths = months % 12;
    
    if (years === 0) {
        return `${remainingMonths} month${remainingMonths !== 1 ? "s" : ""}`;
    } else if (remainingMonths === 0) {
        return `${years} year${years !== 1 ? "s" : ""}`;
    } else {
        return `${years} year${years !== 1 ? "s" : ""}, ${remainingMonths} month${remainingMonths !== 1 ? "s" : ""}`;
    }
    };
    
    const generatePositionTitle = (baseTitle, progress) => {
    // Extract core position without seniority indicators
    let coreTitle = baseTitle
        .replace(/^(Junior|Senior|Lead|Principal|Chief|Head|Associate|Assistant|Executive)\\s+/i, "")
        .replace(/\\s+(Junior|Senior|Lead|Principal|Chief|Head|Associate|Assistant|Executive)$/i, "");
    
    if (progress < 0.2) {
        return `Junior ${coreTitle}`;
    } else if (progress < 0.4) {
        return `${coreTitle}`;
    } else if (progress < 0.6) {
        return `Senior ${coreTitle}`;
    } else if (progress < 0.8) {
        return `Lead ${coreTitle}`;
    } else {
        return `Principal ${coreTitle}`;
    }
    };
    
    const getRelevantSkills = (jobTitle) => {
    const title = jobTitle.toLowerCase();
    
    // Software/Web Development
    if (title.includes("developer") || title.includes("engineer") || title.includes("programmer")) {
        if (title.includes("front") || title.includes("web") || title.includes("ui")) {
        return ["JavaScript", "React", "HTML/CSS", "TypeScript", "Vue.js", "REST APIs"];
        } else if (title.includes("back")) {
        return ["Node.js", "Python", "Java", "API Design", "SQL", "AWS"];
        } else if (title.includes("full")) {
        return ["JavaScript", "React", "Node.js", "MongoDB", "GraphQL", "AWS"];
        } else if (title.includes("mobile")) {
        return ["Swift", "Kotlin", "React Native", "Flutter", "Firebase", "REST APIs"];
        } else if (title.includes("java")) {
        return ["Java", "Spring Boot", "Hibernate", "MySQL", "REST APIs", "Microservices"];
        } else if (title.includes("python")) {
        return ["Python", "Django", "Flask", "SQL", "AWS", "Data Analysis"];
        } else {
        return ["JavaScript", "Python", "SQL", "Git", "AWS", "REST APIs"];
        }
    }
    
    // Data Science/Engineering
    if (title.includes("data")) {
        if (title.includes("scien")) {
        return ["Python", "R", "Machine Learning", "SQL", "Data Visualization", "Statistical Analysis"];
        } else if (title.includes("engineer")) {
        return ["Python", "SQL", "ETL", "Hadoop", "Spark", "AWS/GCP"];
        } else if (title.includes("analyst")) {
        return ["SQL", "Excel", "Tableau", "Python", "Data Visualization", "Statistical Analysis"];
        } else {
        return ["Python", "SQL", "Data Modeling", "ETL Processes", "Data Visualization", "Big Data"];
        }
    }
    
    // Project/Product Management
    if (title.includes("project manager") || title.includes("product manager")) {
        return ["Agile Methodologies", "Scrum", "JIRA", "Product Strategy", "User Stories", "Roadmapping"];
    }
    
    // UX/UI Design
    if ((title.includes("ux") || title.includes("ui")) && title.includes("design")) {
        return ["Figma", "Adobe XD", "User Research", "Wireframing", "Prototyping", "Usability Testing"];
    }
    
    // DevOps/SRE
    if (title.includes("devops") || title.includes("sre") || title.includes("reliability")) {
        return ["Docker", "Kubernetes", "CI/CD", "Infrastructure as Code", "AWS/Azure/GCP", "Monitoring Tools"];
    }
    
    // Marketing
    if (title.includes("market")) {
        if (title.includes("digital")) {
        return ["SEO", "SEM", "Google Analytics", "Social Media Marketing", "Content Strategy", "Email Marketing"];
        } else {
        return ["Marketing Strategy", "Brand Development", "Market Research", "Campaign Management", "Analytics", "CRM"];
        }
    }
    
    // Sales
    if (title.includes("sales")) {
        return ["Sales Strategy", "CRM Software", "Negotiation", "Account Management", "Lead Generation", "Sales Analytics"];
    }
    
    // Default skills for other roles
    return ["Microsoft Office Suite", "Project Management", "Data Analysis", "Process Improvement", "Strategic Planning", "Team Leadership"];
    };
    
    const getRelevantCertifications = (jobTitle) => {
    const title = jobTitle.toLowerCase();
    
    // No certifications by default
    if (Math.random() > 0.7) {
        return [];
    }
    
    // Software/Web Development
    if (title.includes("developer") || title.includes("engineer") || title.includes("programmer")) {
        if (title.includes("aws") || title.includes("cloud")) {
        return ["AWS Certified Solutions Architect", "AWS Certified Developer"];
        } else if (title.includes("microsoft") || title.includes("azure")) {
        return ["Microsoft Certified: Azure Developer Associate", "Microsoft Certified: Azure Solutions Architect"];
        } else if (title.includes("security")) {
        return ["Certified Information Systems Security Professional (CISSP)", "CompTIA Security+"];
        } else {
        return [];
        }
    }
    
    // Data Science/Engineering
    if (title.includes("data")) {
        if (title.includes("scien")) {
        return ["Google Professional Data Engineer", "IBM Data Science Professional"];
        } else if (title.includes("engineer")) {
        return ["Cloudera Certified Professional: Data Engineer", "Microsoft Certified: Azure Data Engineer"];
        } else {
        return [];
        }
    }
    
    // Project/Product Management
    if (title.includes("project manager")) {
        return ["Project Management Professional (PMP)", "Certified ScrumMaster (CSM)"];
    }
    
    if (title.includes("product manager")) {
        return ["Certified Scrum Product Owner (CSPO)", "Professional Scrum Product Owner (PSPO)"];
    }
    
    // DevOps/SRE
    if (title.includes("devops") || title.includes("sre")) {
        return ["AWS Certified DevOps Engineer", "Docker Certified Associate", "Kubernetes Administrator (CKA)"];
    }
    
    // Default - empty certifications
    return [];
    };
    
    const generateRelevantDegree = (jobTitle, level) => {
    const title = jobTitle.toLowerCase();
    
    // Tech fields
    if (title.includes("developer") || title.includes("engineer") || title.includes("programmer")) {
        return "Science in Computer Science";
    }
    
    if (title.includes("data scien")) {
        return "Science in Data Science";
    }
    
    if (title.includes("data engineer") || title.includes("data analyst")) {
        return "Science in Computer Science or Statistics";
    }
    
    // Design fields
    if (title.includes("design")) {
        return "Fine Arts in Design";
    }
    
    // Business fields
    if (title.includes("manager") || title.includes("marketing") || title.includes("sales")) {
        return "Business Administration";
    }
    
    // Default
    if (level === "Associate's") {
        return "Applied Science";
    } else if (level === "Bachelor's") {
        return "Science";
    } else if (level === "Master's") {
        return "Science";
    } else {
        return "Computer Science";
    }
    };
    
    const generateDetailedSummary = (title, techSkills, softSkills, years, workStyle) => {
        const titleLower = title.toLowerCase();
        const summaryStyle = Math.floor(Math.random() * 4);
    
        let experienceLevel = "";
        if (years < 2) {
            experienceLevel = ["entry-level", "early-career"][Math.floor(Math.random() * 2)];
        } else if (years < 5) {
            experienceLevel = ["experienced", "skilled"][Math.floor(Math.random() * 2)];
        } else if (years < 10) {
            experienceLevel = ["seasoned", "senior"][Math.floor(Math.random() * 2)];
        } else {
            experienceLevel = ["veteran", "expert"][Math.floor(Math.random() * 2)];
        }
    
        let skillsPhrase = "";
        if (techSkills.length > 0) {
            let relevantSkills = techSkills;
            if (titleLower.includes("data analyst")) {
                relevantSkills = techSkills.filter(skill =>
                    !skill.includes("SDLC") && !skill.includes("Agile") && skill !== "Data Governance"
                );
                if (relevantSkills.length === 0) {
                    relevantSkills = ["SQL", "Excel", "Tableau"];
                }
            }
            const keySkills = relevantSkills.slice(0, Math.min(5, relevantSkills.length));
            skillsPhrase = `Skilled in ${keySkills.join(", ")}`;
        }
    
        const softSkillPhrase = softSkills.length > 0 
            ? `Strong skills in ${softSkills.slice(0, 3).join(", ")}`
            : "Strong interpersonal and problem-solving skills";
    
        let achievementPhrase = "";
        if (titleLower.includes("develop") || titleLower.includes("engineer")) {
            const devAchievements = [
                "Built scalable enterprise applications",
                "Delivered high-quality code",
                "Optimized critical system performance",
                "Reduced technical debt significantly"
            ];
            achievementPhrase = devAchievements[Math.floor(Math.random() * devAchievements.length)];
        } else if (titleLower.includes("data analyst")) {
            const dataAnalystAchievements = [
                "Delivered actionable business insights",
                "Built effective reporting dashboards",
                "Improved KPI tracking processes",
                "Streamlined data reporting workflows"
            ];
            achievementPhrase = dataAnalystAchievements[Math.floor(Math.random() * dataAnalystAchievements.length)];
        } else if (titleLower.includes("data scien")) {
            const dataScienceAchievements = [
                "Developed predictive models",
                "Improved forecasting accuracy",
                "Implemented machine learning solutions",
                "Extracted insights from complex data"
            ];
            achievementPhrase = dataScienceAchievements[Math.floor(Math.random() * dataScienceAchievements.length)];
        } else if (titleLower.includes("data engineer")) {
            const dataEngineerAchievements = [
                "Built robust data pipelines",
                "Optimized ETL processes",
                "Improved data warehouse performance",
                "Designed scalable data architecture"
            ];
            achievementPhrase = dataEngineerAchievements[Math.floor(Math.random() * dataEngineerAchievements.length)];
        } else if (titleLower.includes("design")) {
            const designAchievements = [
                "Created intuitive user interfaces",
                "Improved product usability metrics",
                "Redesigned customer-facing applications",
                "Enhanced visual brand presence"
            ];
            achievementPhrase = designAchievements[Math.floor(Math.random() * designAchievements.length)];
        } else if (titleLower.includes("market")) {
            const marketingAchievements = [
                "Increased conversion rates",
                "Grew organic traffic",
                "Expanded social media presence",
                "Launched successful marketing campaigns"
            ];
            achievementPhrase = marketingAchievements[Math.floor(Math.random() * marketingAchievements.length)];
        } else if (titleLower.includes("sales")) {
            const salesAchievements = [
                "Exceeded revenue targets",
                "Expanded client base",
                "Improved customer retention rates",
                "Negotiated key enterprise contracts"
            ];
            achievementPhrase = salesAchievements[Math.floor(Math.random() * salesAchievements.length)];
        } else if (titleLower.includes("manager")) {
            const managerAchievements = [
                "Led high-performing teams",
                "Delivered projects on time",
                "Improved operational efficiency",
                "Reduced department costs"
            ];
            achievementPhrase = managerAchievements[Math.floor(Math.random() * managerAchievements.length)];
        } else {
            const generalAchievements = [
                "Improved business processes",
                "Exceeded performance targets",
                "Enhanced team productivity",
                "Delivered measurable results"
            ];
            achievementPhrase = generalAchievements[Math.floor(Math.random() * generalAchievements.length)];
        }
    
        // Instead of paragraph, we return bullets
        const summaryBullets = [
            `${experienceLevel.charAt(0).toUpperCase() + experienceLevel.slice(1)} ${title} with ${years} years of experience.`,
            `${skillsPhrase}.`,
            `${softSkillPhrase} enabling collaboration across teams.`,
            `Notable achievements include: ${achievementPhrase}.`,
            `Committed to continuous technical growth and innovation.`,
            `Dedicated to delivering user-focused, high-quality outcomes.`,
            `Brings strong analytical thinking and a results-driven approach to every project.`
        ];
    
        return summaryBullets.join("\n"); // Later you can render it as <li> items easily
    };
    
    
    
    // IMPROVED: Much more variety in achievement templates by role
    const generateDetailedAchievements = (jobTitle, techSkills, softSkills, years, positionTitle, industry) => {
    const titleLower = jobTitle.toLowerCase();
    let achievements = [];
    
    // Common metrics to use in achievements
    const metrics = {
        percentSmall: `${Math.floor(Math.random() * 20) + 10}%`,
        percentMedium: `${Math.floor(Math.random() * 30) + 20}%`,
        percentLarge: `${Math.floor(Math.random() * 40) + 30}%`,
        percentHuge: `${Math.floor(Math.random() * 50) + 40}%`,
        team: Math.floor(Math.random() * 10) + 3,
        projects: Math.floor(Math.random() * 5) + 2,
        time: Math.floor(Math.random() * 20) + 10,
        cost: Math.floor(Math.random() * 40) + 10,
        users: (Math.floor(Math.random() * 900) + 100) + "K",
        revenue: "$" + (Math.floor(Math.random() * 5) + 1) + "M",
        clients: Math.floor(Math.random() * 20) + 5,
        bugs: Math.floor(Math.random() * 50) + 10,
        features: Math.floor(Math.random() * 10) + 3
    };
    
    // Function to pick from an array of achievement templates and fill in variables
    const generateFromTemplates = (templates, variables = {}) => {
        // Default variables that can be used in all templates
        const allVars = {
        ...metrics,
        ...variables,
        industry: industry
        };
        
        // Pick a random template
        const template = templates[Math.floor(Math.random() * templates.length)];
        
        // Replace variables in the template
        return template.replace(/\{(\w+)\}/g, (match, varName) => {
        return allVars[varName] !== undefined ? allVars[varName] : match;
        });
    };
    
    // Generic templates for all roles
    const genericLeadershipTemplates = [
        "Led a cross-functional team of {team} members to deliver {projects} major initiatives ahead of schedule",
        "Built and mentored a team that improved departmental efficiency by {percentMedium}",
        "Managed a team of {team} professionals, driving innovation and exceeding targets by {percentSmall}",
        "Spearheaded a department reorganization that improved workflow efficiency by {percentMedium}"
    ];
    
    const genericProcessTemplates = [
        "Implemented new processes that reduced operational costs by {percentMedium} while improving quality",
        "Optimized existing workflows resulting in {percentSmall} greater productivity across teams",
        "Redesigned core business processes, saving approximately {time} hours per week in manual work",
        "Standardized documentation practices, reducing onboarding time by {percentMedium} for new team members"
    ];
    
    const genericProjectTemplates = [
        "Successfully delivered {projects} high-impact projects on time and {cost}% under budget",
        "Managed project timelines and resources to complete deliverables {percentSmall} ahead of schedule",
        "Coordinated complex projects across multiple departments, ensuring alignment with business objectives",
        "Led implementation of strategic initiatives that generated {revenue}+ in additional revenue"
    ];
    
    // Role-specific achievements
    if (titleLower.includes("develop") || titleLower.includes("engineer") || titleLower.includes("program")) {
        // Software development templates
        const codingTemplates = [
        "Developed {feature} that improved system response time by {percentMedium} and user satisfaction by {percentSmall}",
        "Built a scalable {solution} architecture supporting {users} monthly active users",
        "Created microservices architecture that reduced system downtime by {percentLarge}",
        "Refactored legacy codebase, reducing technical debt by {percentMedium} and improving maintainability",
        "Architected and implemented RESTful APIs that streamlined integration with {projects} external systems",
        "Engineered fault-tolerant systems with {percentLarge} uptime guarantee for mission-critical applications"
        ];
        
        const optimizationTemplates = [
        "Optimized database queries that improved application performance by {percentMedium}",
        "Reduced cloud infrastructure costs by {percentMedium} through implementation of serverless architecture",
        "Implemented caching solution that decreased average API response time by {percentLarge}",
        "Enhanced system security protocols, reducing vulnerability incidents by {percentHuge}",
        "Improved CI/CD pipeline, reducing deployment time from hours to minutes"
        ];
        
        const collaborationTemplates = [
        "Collaborated with product team to implement {features} new features that increased user engagement by {percentMedium}",
        "Worked with UX designers to optimize front-end performance, improving page load times by {percentMedium}",
        "Partnered with QA team to implement automated testing, reducing regression bugs by {percentLarge}",
        "Mentored {team} junior developers, improving team velocity by {percentSmall} after one quarter"
        ];
        
        // Choose relevant skill-based achievements
        if (techSkills.length > 0) {
        // Pick 1-2 random skills
        const randomSkillIndexes = [];
        while (randomSkillIndexes.length < Math.min(2, techSkills.length)) {
            const index = Math.floor(Math.random() * techSkills.length);
            if (!randomSkillIndexes.includes(index)) {
            randomSkillIndexes.push(index);
            }
        }
        
        // Generate skill-specific achievements
        randomSkillIndexes.forEach(index => {
            const skill = techSkills[index];
            achievements.push(generateFromTemplates([
            `Implemented ${skill} solutions that improved system performance by ${metrics.percentMedium}`,
            `Utilized ${skill} to build applications that reduced operational costs by ${metrics.percentMedium}`,
            `Leveraged ${skill} expertise to create scalable solutions handling ${metrics.users} daily users`,
            `Applied ${skill} to develop custom features that increased user retention by ${metrics.percentSmall}`
            ]));
        });
        }
        
        // Add role-level based achievements
        if (positionTitle.includes("Senior") || positionTitle.includes("Lead") || positionTitle.includes("Principal")) {
        achievements.push(generateFromTemplates(genericLeadershipTemplates));
        achievements.push(generateFromTemplates(codingTemplates, {
            feature: "microservice architecture",
            solution: "cloud-native"
        }));
        } else if (positionTitle.includes("Junior")) {
        achievements.push(generateFromTemplates(collaborationTemplates));
        achievements.push(generateFromTemplates(codingTemplates, {
            feature: "new feature",
            solution: "component"
        }));
        } else {
        achievements.push(generateFromTemplates(optimizationTemplates));
        achievements.push(generateFromTemplates(codingTemplates, {
            feature: "caching system",
            solution: "service"
        }));
        }
        
        // Add a couple more achievements
        achievements.push(generateFromTemplates(codingTemplates, {
        feature: "authentication system",
        solution: "platform"
        }));
        
        if (achievements.length < 3) {
        achievements.push(`Identified and resolved ${metrics.bugs} critical bugs, improving system reliability by ${metrics.percentLarge}`);
        }
    }
    // Data roles with specialized achievements
    else if (titleLower.includes("data")) {
        const dataAnalyticsTemplates = [
        "Analyzed {dataType} data to identify patterns that led to {percentMedium} increase in {business} efficiency",
        "Designed interactive dashboards used by {team} departments for strategic decision-making",
        "Built predictive models that improved forecasting accuracy by {percentMedium}",
        "Created comprehensive data reports that directly influenced {revenue}+ business decisions",
        "Implemented data quality processes that reduced errors by {percentLarge}",
        "Conducted A/B testing that optimized {business} strategies, resulting in {percentSmall} increased performance"
        ];
        
        const dataPipelineTemplates = [
        "Architected ETL pipelines processing {size}TB of data daily with {percentHuge} reliability",
        "Designed data warehouse schema that reduced query times by {percentLarge}",
        "Implemented data governance frameworks ensuring regulatory compliance across {team} systems",
        "Built real-time analytics infrastructure supporting {users} concurrent users",
        "Optimized data ingestion workflows, reducing processing time by {percentMedium}"
        ];
        
        const dataInsightTemplates = [
        "Translated complex data findings into actionable business recommendations, increasing {business} by {percentMedium}",
        "Developed segmentation analysis that improved targeting precision by {percentMedium}",
        "Created anomaly detection systems that prevented {cost}% in potential losses",
        "Generated {projects} quarterly insights reports used by executive leadership for strategic planning",
        "Discovered key correlations in customer behavior data leading to {percentSmall} increase in conversion rates"
        ];
        
        // Choose appropriate templates based on specific data role
        if (titleLower.includes("scien")) {
        // Data Scientist
        achievements.push(generateFromTemplates(dataAnalyticsTemplates, {
            dataType: "customer behavior",
            business: "marketing"
        }));
        achievements.push(generateFromTemplates([
            "Developed machine learning models that improved prediction accuracy by {percentMedium}",
            "Created NLP algorithms for sentiment analysis with {percentLarge} accuracy rate",
            "Implemented classification models that increased targeting precision by {percentMedium}",
            "Designed recommendation engine that boosted customer engagement by {percentSmall}"
        ]));
        achievements.push(generateFromTemplates(dataInsightTemplates, {
            business: "customer retention"
        }));
        } else if (titleLower.includes("engineer")) {
        // Data Engineer
        achievements.push(generateFromTemplates(dataPipelineTemplates, {
            size: Math.floor(Math.random() * 90) + 10
        }));
        achievements.push(generateFromTemplates([
            "Built scalable data infrastructure capable of handling {size}TB while maintaining sub-second queries",
            "Migrated on-premise data warehouse to cloud, reducing costs by {percentMedium}",
            "Implemented data validation frameworks that ensured {percentHuge} data accuracy",
            "Developed automated data pipelines that reduced manual processing by {percentLarge}"
        ], {
            size: Math.floor(Math.random() * 90) + 10
        }));
        achievements.push(generateFromTemplates(genericProcessTemplates));
        } else if (titleLower.includes("analyst")) {
        // Data Analyst
        achievements.push(generateFromTemplates(dataAnalyticsTemplates, {
            dataType: "sales",
            business: "revenue"
        }));
        achievements.push(generateFromTemplates(dataInsightTemplates, {
            business: "operational efficiency"
        }));
        achievements.push(generateFromTemplates([
            "Created automated reporting systems that saved {time} hours per week while improving accuracy",
            "Developed KPI dashboards that gave leadership visibility into {projects} critical business metrics",
            "Conducted in-depth market analysis that informed product development strategy",
            "Transformed complex datasets into clear visualizations for executive presentations"
        ]));
        } else {
        // Generic data role
        achievements.push(generateFromTemplates(dataAnalyticsTemplates, {
            dataType: "business",
            business: "operational"
        }));
        achievements.push(generateFromTemplates(dataPipelineTemplates, {
            size: Math.floor(Math.random() * 50) + 5
        }));
        achievements.push(generateFromTemplates(dataInsightTemplates, {
            business: "decision-making"
        }));
        }
    }
    // Project/Product Management
    else if (titleLower.includes("manager")) {
        if (titleLower.includes("project")) {
        // Project Manager
        achievements.push(generateFromTemplates(genericProjectTemplates));
        achievements.push(generateFromTemplates([
            "Led {projects} complex projects from initiation to completion, maintaining {percentMedium} on-time delivery rate",
            "Managed cross-functional teams of up to {team} members across multiple time zones and departments",
            "Implemented agile methodologies that improved team velocity by {percentMedium}",
            "Created comprehensive project documentation frameworks that enhanced knowledge transfer by {percentSmall}",
            "Established risk management protocols that reduced project delays by {percentLarge}"
        ]));
        achievements.push(generateFromTemplates([
            "Developed detailed project plans ensuring resource optimization and timely milestone achievement",
            "Coordinated between {team} stakeholders to maintain alignment throughout project execution",
            "Rescued a failing project, bringing it back on schedule and under budget within one quarter",
            "Built project management office (PMO) standards that improved delivery consistency by {percentMedium}"
        ]));
        } else if (titleLower.includes("product")) {
        // Product Manager
        achievements.push(generateFromTemplates([
            "Owned product roadmap and successfully launched {features} major features that increased user retention by {percentMedium}",
            "Conducted market research that identified {projects} new product opportunities worth {revenue}+",
            "Defined product vision and strategy that increased market share by {percentSmall} in one year",
            "Collaborated with UX team to improve user satisfaction scores by {percentMedium}",
            "Led product discovery workshops that generated {projects} validated feature concepts"
        ]));
        achievements.push(generateFromTemplates([
            "Conducted competitive analysis that informed product differentiation strategy",
            "Created detailed user stories and acceptance criteria for {features} new features",
            "Prioritized product backlog to maximize business value and development efficiency",
            "Gathered and synthesized customer feedback to inform product iteration"
        ]));
        achievements.push(generateFromTemplates([
            "Collaborated with engineering to reduce development cycles by {percentMedium}",
            "Developed product metrics framework that improved feature adoption by {percentSmall}",
            "Presented product strategy to C-level executives, securing {revenue} in additional funding",
            "Analyzed user behavior data to identify opportunities that increased engagement by {percentMedium}"
        ]));
        } else {
        // General Manager
        achievements.push(generateFromTemplates(genericLeadershipTemplates));
        achievements.push(generateFromTemplates(genericProcessTemplates));
        achievements.push(generateFromTemplates([
            "Established departmental KPIs that improved performance visibility and accountability",
            "Implemented strategic initiatives that increased revenue by {percentMedium} year-over-year",
            "Reduced operational costs by {percentSmall} while improving service quality metrics",
            "Developed and executed business plan that exceeded growth targets by {percentSmall}"
        ]));
        }
    }
    // Design roles
    else if (titleLower.includes("design")) {
        achievements.push(generateFromTemplates([
        "Redesigned key interfaces that improved user satisfaction scores by {percentMedium}",
        "Created comprehensive design system that ensured consistency across {projects} products",
        "Developed intuitive user flows that increased conversion rates by {percentSmall}",
        "Designed mobile application interface that received {percentHuge} positive user feedback",
        "Transformed complex functionality into intuitive user experiences, improving task completion rates by {percentMedium}"
        ]));
        achievements.push(generateFromTemplates([
        "Conducted user research and usability testing that informed design decisions",
        "Collaborated with development team to ensure pixel-perfect implementation of designs",
        "Created wireframes and prototypes for {features} new features that enhanced user engagement",
        "Established design principles adopted across {team} product teams",
        "Led design sprints that generated {projects} validated concepts for new features"
        ]));
        achievements.push(generateFromTemplates([
        "Improved information architecture, reducing user navigation time by {percentMedium}",
        "Redesigned checkout process, increasing completion rate by {percentSmall}",
        "Created accessible designs that improved compliance with WCAG standards",
        "Designed data visualizations that improved comprehension of complex information by {percentMedium}"
        ]));
    }
    // Marketing roles
    else if (titleLower.includes("market")) {
        achievements.push(generateFromTemplates([
        "Developed marketing campaigns that generated {clients} qualified leads and {percentSmall} ROI",
        "Implemented SEO strategies that improved organic traffic by {percentLarge}",
        "Created content marketing initiatives that increased brand visibility by {percentMedium}",
        "Managed {revenue} annual marketing budget, delivering {percentSmall} over target results",
        "Led rebranding initiative that improved brand recognition by {percentMedium}"
        ]));
        achievements.push(generateFromTemplates([
        "Optimized digital advertising spend, reducing customer acquisition costs by {percentMedium}",
        "Developed social media strategy that increased engagement by {percentLarge}",
        "Created email marketing campaigns with {percentMedium} open rates and {percentSmall} conversion",
        "Conducted market research that informed {projects} successful product launches",
        "Implemented marketing automation that improved lead nurturing efficiency by {percentMedium}"
        ]));
        achievements.push(generateFromTemplates([
        "Analyzed marketing metrics to optimize channel strategy, improving ROI by {percentSmall}",
        "Produced video content that generated {users} views and improved brand sentiment",
        "Managed relationships with {team} external agencies to ensure cohesive marketing execution",
        "Developed customer personas that improved targeting precision by {percentMedium}"
        ]));
    }
    // Sales roles
    else if (titleLower.includes("sales")) {
        achievements.push(generateFromTemplates([
        "Exceeded sales targets by {percentMedium} through effective client relationship management",
        "Developed and implemented sales strategies that resulted in {clients} new enterprise clients",
        "Built and maintained strong client relationships, achieving {percentHuge} renewal rate",
        "Generated {revenue}+ in annual revenue, {percentSmall} above target",
        "Expanded territory sales by {percentLarge} year-over-year"
        ]));
        achievements.push(generateFromTemplates([
        "Implemented consultative selling approach that increased average deal size by {percentMedium}",
        "Developed sales playbooks that improved team performance by {percentSmall}",
        "Revamped lead qualification process, improving conversion rates by {percentMedium}",
        "Established strategic partnerships that opened {projects} new market segments",
        "Negotiated complex contracts with total value of {revenue}+"
        ]));
        achievements.push(generateFromTemplates([
        "Created solutions for clients that addressed critical business challenges and delivered measurable ROI",
        "Managed full sales cycle from prospecting to closing for enterprise accounts",
        "Achieved {percentHuge} of quota consistently for {projects} consecutive quarters",
        "Mentored junior sales representatives, improving team performance by {percentSmall}"
        ]));
    }
    // Default achievements for other roles
    else {
        achievements.push(generateFromTemplates(genericProcessTemplates));
        achievements.push(generateFromTemplates(genericProjectTemplates));
        if (positionTitle.includes("Senior") || positionTitle.includes("Lead") || positionTitle.includes("Principal")) {
        achievements.push(generateFromTemplates(genericLeadershipTemplates));
        } else {
        achievements.push(generateFromTemplates([
            "Collaborated with cross-functional teams to deliver key projects on time and within budget",
            "Developed and implemented best practices that enhanced team performance",
            "Created comprehensive documentation that improved knowledge sharing across teams",
            "Participated in continuous improvement initiatives that enhanced operational efficiency"
        ]));
        }
    }
    
    // Add a soft-skill related achievement if available
    if (softSkills.length > 0) {
        const softSkill = softSkills[Math.floor(Math.random() * softSkills.length)];
        
        if (softSkill.toLowerCase().includes("communicat")) {
        achievements.push(generateFromTemplates([
            "Leveraged strong communication skills to bridge technical and business requirements",
            "Presented complex information to diverse audiences, ensuring clarity and understanding",
            "Facilitated productive meetings between technical and non-technical stakeholders",
            "Created clear documentation that improved cross-team collaboration by {percentSmall}"
        ]));
        } else if (softSkill.toLowerCase().includes("problem")) {
        achievements.push(generateFromTemplates([
            "Applied problem-solving expertise to resolve complex issues, reducing incident response time by {percentSmall}",
            "Identified root causes of recurring problems, implementing solutions that prevented future occurrences",
            "Developed systematic approach to troubleshooting that reduced resolution time by {percentMedium}",
            "Created decision frameworks that improved problem-solving efficiency across the team"
        ]));
        } else if (softSkill.toLowerCase().includes("team")) {
        achievements.push(generateFromTemplates([
            "Demonstrated exceptional teamwork abilities by collaborating across departments",
            "Supported team members during critical project phases, ensuring successful delivery",
            "Built consensus among diverse stakeholders to achieve common objectives",
            "Fostered inclusive team environment that improved collaboration and innovation"
        ]));
        } else if (softSkill.toLowerCase().includes("lead")) {
        achievements.push(generateFromTemplates([
            "Exhibited leadership by mentoring junior team members, improving team capabilities",
            "Led by example, setting high standards for quality and productivity",
            "Guided team through challenging situations, maintaining morale and focus",
            "Provided constructive feedback that enhanced individual and team performance"
        ]));
        } else {
        achievements.push(`Utilized strong ${softSkill} to drive improvements in ${industry} processes, contributing to overall business objectives`);
        }
    }
    
    // Randomize and return 3-5 unique achievements (no duplicates)
    const uniqueAchievements = [...new Set(achievements)];
    const shuffled = uniqueAchievements.sort(() => 0.5 - Math.random());
    return shuffled.slice(0, Math.min(Math.floor(Math.random() * 3) + 3, shuffled.length));
    };

    const generateSampleExperience = () => {
    try {
        console.log("Generating sample experience...");
        if (!jobTitle.trim()) {
        alert("Please enter a job title");
        return;
        }

        // Filter out empty values
        const technicalSkills = avatarData.technicalSkills.filter(skill => skill.trim());
        const softSkills = avatarData.softSkills.filter(skill => skill.trim());
        const certifications = avatarData.certifications.filter(cert => cert.trim());

        // Generate company names and industries
        const companies = [
        {name: "Innovatech Solutions", industry: "Technology Consulting"},
        {name: "Apex Global", industry: "Enterprise Software"},
        {name: "BlueWave Systems", industry: "Cloud Infrastructure"},
        {name: "Quantum Enterprises", industry: "Financial Technology"},
        {name: "Elevate Inc.", industry: "Digital Transformation"},
        {name: "CyberShield Networks", industry: "Cybersecurity"},
        {name: "Fusion Technologies", industry: "Telecommunications"},
        {name: "Precision Analytics", industry: "Data Analytics"},
        {name: "NexGen Innovations", industry: "Product Development"},
        {name: "Meridian Digital", industry: "E-commerce Solutions"}
        ];
        
        // Generate work experience based on experience level
        let workExperience = [];
        let totalYears = 0;
        
        switch(avatarData.experience) {
        case "Entry-level":
            totalYears = Math.floor(Math.random() * 2) + 1; // 1-2 years
            break;
        case "Mid-level":
            totalYears = Math.floor(Math.random() * 3) + 3; // 3-5 years
            break;
        case "Senior":
            totalYears = Math.floor(Math.random() * 4) + 6; // 6-9 years
            break;
        case "Lead/Principal":
            totalYears = Math.floor(Math.random() * 5) + 10; // 10-14 years
            break;
        case "Executive":
            totalYears = Math.floor(Math.random() * 10) + 15; // 15-24 years
            break;
        default:
            totalYears = Math.floor(Math.random() * 5) + 1; // 1-5 years
        }
        
        // Get relevant technical skills based on job title
        let relevantSkills = getRelevantSkills(jobTitle);
        const combinedSkills = [...new Set([...technicalSkills, ...relevantSkills])];
        
        // Current year and month
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth();
        
        let endDate = new Date(currentYear, currentMonth);
        let remainingYears = totalYears;
        
        // Calculate number of jobs based on total years of experience
        // At most 5 jobs, but at least 1 job
        const maxJobs = Math.min(Math.ceil(totalYears / 2), 5);
        
        // Calculate average duration per job
        const averageJobDuration = totalYears / maxJobs;
        
        // Create work experiences - most senior (recent) first, most junior last
        let experienceEntries = [];
        
        // Used to avoid duplicate companies
        const usedCompanyIndexes = [];
        
        for (let i = 0; i < maxJobs; i++) {
        const isCurrentJob = i === 0;
        
        // Select a random company that hasn't been used yet if possible
        let companyIndex;
        let attempts = 0;
        do {
            companyIndex = Math.floor(Math.random() * companies.length);
            attempts++;
        } while (usedCompanyIndexes.includes(companyIndex) && attempts < 10 && usedCompanyIndexes.length < companies.length);
        
        usedCompanyIndexes.push(companyIndex);
        const companyData = companies[companyIndex];
        const company = companyData.name;
        const industry = companyData.industry;
        
        // Generate random duration for this job
        let jobDurationYears = Math.min(
            remainingYears,
            Math.max(0.5, averageJobDuration + (Math.random() - 0.5) * 1.5)
        );
        
        // For the last job, use all remaining years
        if (i === maxJobs - 1) {
            jobDurationYears = remainingYears;
        }
        
        // Convert to months
        const jobDurationMonths = Math.round(jobDurationYears * 12);
        
        // Calculate start date
        const startDate = new Date(endDate);
        startDate.setMonth(startDate.getMonth() - jobDurationMonths);
        
        // Format dates
        const startMonthName = startDate.toLocaleString("default", { month: "long" });
        const startYear = startDate.getFullYear();
        const endMonthName = isCurrentJob ? "Present" : endDate.toLocaleString("default", { month: "long" });
        const endYear = isCurrentJob ? "" : endDate.getFullYear();
        
        const formattedPeriod = isCurrentJob 
            ? `${startMonthName} ${startYear} - Present` 
            : `${startMonthName} ${startYear} - ${endMonthName} ${endYear}`;
        
        const durationText = formatDuration(jobDurationMonths);
        
        // Generate position title based on career progression
        // For career progression, early jobs (higher i) should be junior, recent jobs (low i) should be senior
        // This ensures the chronology is correct - junior roles in the past, senior roles recently
        const careerProgress = 1 - (i / (maxJobs - 1 || 1));
        const positionTitle = generatePositionTitle(jobTitle, careerProgress);
        
        // Generate achievements relevant to the job
        const achievements = generateDetailedAchievements(
            jobTitle, 
            combinedSkills, 
            softSkills, 
            jobDurationYears,
            positionTitle,
            industry
        );
        
        // Add to work experience array
        experienceEntries.push({
            company,
            industry,
            title: positionTitle,
            period: formattedPeriod,
            duration: durationText,
            achievements
        });
        
        // Update for next job
        endDate = new Date(startDate);
        endDate.setDate(0); // Last day of previous month
        remainingYears -= jobDurationYears;
        
        if (remainingYears <= 0) break;
        }
        
        // Already in correct order (most recent/senior first)
        workExperience = experienceEntries;
        
        // Generate education based on selected level
        let education = {
        degree: "",
        institution: "",
        graduationDate: ""
        };
        
        const universities = [
        "State University", 
        "Tech Institute", 
        "National College", 
        "Metropolitan University", 
        "Coastal Academy",
        "Northwestern University",
        "University of Technology",
        "International Business School",
        "Central College",
        "Pacific Institute of Technology"
        ];
        
        const institution = universities[Math.floor(Math.random() * universities.length)];
        
        // Education should typically be before first job
        const lastJob = workExperience[workExperience.length - 1];
        const lastJobStartDate = new Date(
        parseInt(lastJob.period.split(" ")[1]),
        getMonthNumber(lastJob.period.split(" ")[0])
        );
        
        // Graduate 0-3 years before first job
        const gradYearsOffset = Math.floor(Math.random() * 4);
        const graduationDate = new Date(lastJobStartDate);
        graduationDate.setFullYear(graduationDate.getFullYear() - gradYearsOffset);
        
        const gradMonth = graduationDate.toLocaleString("default", { month: "long" });
        const gradYear = graduationDate.getFullYear();
        
        switch(avatarData.education) {
        case "Associate's":
            education = {
            degree: `Associate's Degree in ${generateRelevantDegree(jobTitle, "Associate's")}`,
            institution,
            graduationDate: `${gradMonth} ${gradYear}`
            };
            break;
        case "Bachelor's":
            education = {
            degree: `Bachelor of ${generateRelevantDegree(jobTitle, "Bachelor's")}`,
            institution,
            graduationDate: `${gradMonth} ${gradYear}`
            };
            break;
        case "Master's":
            education = {
            degree: `Master of ${generateRelevantDegree(jobTitle, "Master's")}`,
            institution,
            graduationDate: `${gradMonth} ${gradYear}`
            };
            break;
        case "PhD":
            education = {
            degree: `PhD in ${generateRelevantDegree(jobTitle, "PhD")}`,
            institution,
            graduationDate: `${gradMonth} ${gradYear}`
            };
            break;
        case "High School":
            education = {
            degree: "High School Diploma",
            institution: "Central High School",
            graduationDate: `${gradMonth} ${gradYear}`
            };
            break;
        case "Self-taught":
            education = {
            degree: "Professional Development",
            institution: "Various online platforms including Coursera, Udemy, and self-directed learning",
            graduationDate: `${gradMonth} ${gradYear - 2} - Present`
            };
            break;
        default:
            education = {
            degree: `Bachelor of ${generateRelevantDegree(jobTitle, "Bachelor's")}`,
            institution,
            graduationDate: `${gradMonth} ${gradYear}`
            };
        }
        
        // Generate a random profile with the selected work style
        const workStyleOptions = getWorkStyleOptions(avatarData.workStyle);
        const selectedWorkStylePhrase = workStyleOptions[Math.floor(Math.random() * workStyleOptions.length)];
        
        const generatedSample = {
        name: generateName(),
        title: jobTitle,
        summary: generateDetailedSummary(jobTitle, combinedSkills, softSkills, totalYears, avatarData.workStyle),
        workExperience,
        education,
        skills: {
            technical: combinedSkills.length > 0 ? combinedSkills : getRelevantSkills(jobTitle),
            soft: softSkills.length > 0 ? softSkills : ["Communication", "Problem Solving", "Time Management", "Teamwork", "Adaptability"]
        },
        certifications: certifications.length > 0 ? certifications : getRelevantCertifications(jobTitle),
        workStyle: selectedWorkStylePhrase
        };
        
        console.log("Generated sample:", generatedSample);
        setSampleExperience(generatedSample);
        setShowSample(true);
    } catch (error) {
        console.error("Error generating sample:", error);
        alert(`Error generating sample: ${error.message}`);
    }
    };

    const saveAvatar = () => {
    if (!jobTitle.trim()) {
        alert("Please enter a job title");
        return;
    }
    
    setSavedAvatars([
        ...savedAvatars,
        { 
        title: jobTitle, 
        data: avatarData,
        sample: sampleExperience 
        }
    ]);
    
    // Reset form
    setJobTitle("");
    setAvatarData({
        technicalSkills: ["", "", ""],
        softSkills: ["", "", ""],
        experience: "",
        education: "",
        certifications: [""],
        workStyle: "",
    });
    
    setCurrentView("savedAvatars");
    setShowSample(false);
    };

    const loadAvatar = (index) => {
    const avatar = savedAvatars[index];
    setJobTitle(avatar.title);
    setAvatarData(avatar.data);
    setCurrentView("form");
    setShowSample(false);
    };

    const deleteAvatar = (index) => {
    const newSavedAvatars = savedAvatars.filter((_, i) => i !== index);
    setSavedAvatars(newSavedAvatars);
    };

    const exportAvatarData = () => {
    const dataStr = JSON.stringify(savedAvatars);
    const dataUri = "data:application/json;charset=utf-8,"+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = "candidate-avatars.json";
    
    const linkElement = document.createElement("a");
    linkElement.setAttribute("href", dataUri);
    linkElement.setAttribute("download", exportFileDefaultName);
    linkElement.click();
    };

    // NEW FUNCTION: Export a specific avatar to PDF
    const exportAvatarToPDF = (avatar) => {
    try {
        // Create a new jsPDF instance
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        // if (!window.jsPDF) {
        //     alert("jsPDF is not loaded!");
        //     return;
        // }
        // const doc = new window.jsPDF();
        
        // Use avatar.sample if available, otherwise generate a new sample
        const sample = avatar.sample || generateSampleFromData(avatar.title, avatar.data);

        // Set up formatting
        const pageWidth = doc.internal.pageSize.width;
        const margin = 20;
        const col1Width = 40;
        const col2Width = pageWidth - margin * 2 - col1Width;
        
        // Add title and name
        doc.setFontSize(20);
        doc.setTextColor(0, 0, 150);
        doc.text(sample.name, margin, 20);
        
        doc.setFontSize(16);
        doc.text(sample.title, margin, 30);
        
        // Add summary
        doc.setFontSize(12);
        doc.setTextColor(0, 0, 0);
        doc.text("Professional Summary", margin, 45);

        doc.setFontSize(10);

        // Split summary into lines
        const summaryLines = sample.summary.split("\n");

        let yPos = 55;

        // Add each line with a bullet manually
        summaryLines.forEach((line, index) => {
            if (yPos > 270) { // If near page bottom, create new page
                doc.addPage();
                yPos = 20;
            }
            doc.text(`• ${line.trim()}`, margin + 5, yPos);
            yPos += 7; // Move cursor down
        });

        // Update yPos so next section (Work Experience) starts properly
        yPos += 10;
        
        // Add work experience
        yPos = 65 + summaryLines.length * 7;
        
        doc.setFontSize(12);
        doc.text("Work Experience", margin, yPos);
        yPos += 10;
        
        sample.workExperience.forEach((exp) => {
        doc.setFontSize(11);
        doc.setFont(undefined, "bold");
        doc.text(exp.title, margin, yPos);
        
        doc.setFont(undefined, "normal");
        doc.setFontSize(10);
        doc.text(`${exp.company} • ${exp.industry}`, margin, yPos + 7);
        
        doc.setFontSize(9);
        doc.setTextColor(100, 100, 100);
        const periodText = `${exp.period} (${exp.duration})`;
        const periodWidth = doc.getTextWidth(periodText);
        doc.text(periodText, pageWidth - margin - periodWidth, yPos + 7);
        
        doc.setTextColor(0, 0, 0);
        yPos += 15;
        
        exp.achievements.forEach((achievement) => {
            const lines = doc.splitTextToSize("• " + achievement, pageWidth - margin * 2 - 5);
            doc.text(lines, margin + 5, yPos);
            yPos += lines.length * 5 + 5;
        });
        
        yPos += 5;
        });
        
        // Add education
        doc.setFontSize(12);
        doc.setFont(undefined, "bold");
        doc.text("Education", margin, yPos);
        yPos += 10;
        
        doc.setFontSize(10);
        doc.text(sample.education.degree, margin, yPos);
        yPos += 7;
        doc.setFont(undefined, "normal");
        doc.text(sample.education.institution, margin, yPos);
        yPos += 7;
        doc.setTextColor(100, 100, 100);
        doc.text(sample.education.graduationDate, margin, yPos);
        doc.setTextColor(0, 0, 0);
        yPos += 15;
        
        // Check if we need a new page for skills
        if (yPos > 250) {
        doc.addPage();
        yPos = 20;
        }
        
        // Add skills
        doc.setFontSize(12);
        doc.setFont(undefined, "bold");
        doc.text("Skills", margin, yPos);
        yPos += 10;
        

        // Headings
        doc.setFontSize(10);
        doc.setFont(undefined, "bold");
        doc.text("Technical Skills", margin, yPos);
        doc.text("Soft Skills", margin + (pageWidth / 2), yPos);

        yPos += 7;

        // Lists
        doc.setFont(undefined, "normal");

        let techY = yPos;
        sample.skills.technical.forEach(skill => {
            doc.text(`• ${skill}`, margin + 5, techY);
            techY += 6;
        });

        let softY = yPos;
        sample.skills.soft.forEach(skill => {
            doc.text(`• ${skill}`, margin + (pageWidth / 2) + 5, softY);
            softY += 6;
        });

        // Set yPos to continue below the longer list
        yPos = Math.max(techY, softY) + 10;



        // // Technical skills
        // doc.setFontSize(10);
        // doc.text("Technical Skills", margin, yPos);
        // yPos += 7;
        
        // let skillYPos = yPos;
        // sample.skills.technical.forEach((skill, index) => {
        // doc.setFont(undefined, "normal");
        // doc.text(`• ${skill}`, margin + 5, skillYPos);
        // skillYPos += 7;
        // });
        
        // // Soft skills
        // doc.setFontSize(10);
        // doc.setFont(undefined, "bold");
        // doc.text("Soft Skills", margin + pageWidth / 2 - margin, yPos);
        
        // skillYPos = yPos;
        // sample.skills.soft.forEach((skill, index) => {
        // doc.setFont(undefined, "normal");
        // doc.text(`• ${skill}`, margin + pageWidth / 2 - margin + 5, skillYPos);
        // skillYPos += 7;
        // });
        
        // yPos = Math.max(skillYPos, yPos) + 10;
        
        // Certifications if available
        if (sample.certifications && sample.certifications.length > 0) {
        doc.setFontSize(12);
        doc.setFont(undefined, "bold");
        doc.text("Certifications", margin, yPos);
        yPos += 10;
        
        sample.certifications.forEach((cert) => {
            doc.setFont(undefined, "normal");
            doc.setFontSize(10);
            doc.text(`• ${cert}`, margin + 5, yPos);
            yPos += 7;
        });
        
        yPos += 5;
        }
        
        // Work style
        doc.setFontSize(12);
        doc.setFont(undefined, "bold");
        doc.text("Work Style", margin, yPos);
        yPos += 10;
        
        doc.setFont(undefined, "normal");
        doc.setFontSize(10);
        const workStyleLines = doc.splitTextToSize(sample.workStyle, pageWidth - margin * 2);
        doc.text(workStyleLines, margin, yPos);
        
        // Save the PDF
        doc.save(`${sample.name.replace(/\\s+/g, "_")}_${sample.title.replace(/\\s+/g, "_")}.pdf`);
        
    } catch (error) {
        console.error("Error generating PDF:", error);
        alert("Error generating PDF. Please make sure PDF.js is loaded correctly.");
    }
    };
    
    // Helper function to generate a sample from saved data (used for PDF export)
    const generateSampleFromData = (title, data) => {
    // This is a simplified version of generateSampleExperience that returns the sample
    // without setting state, used when we need a sample for a saved avatar that doesn't have one
    
    // Similar to generateSampleExperience but simplified
    const technicalSkills = data.technicalSkills.filter(skill => skill.trim());
    const softSkills = data.softSkills.filter(skill => skill.trim());
    const certifications = data.certifications.filter(cert => cert.trim());
    
    let totalYears = 5; // Default to 5 years if not specified
    
    switch(data.experience) {
        case "Entry-level": totalYears = 2; break;
        case "Mid-level": totalYears = 4; break;
        case "Senior": totalYears = 8; break;
        case "Lead/Principal": totalYears = 12; break;
        case "Executive": totalYears = 18; break;
    }
    
    const relevantSkills = getRelevantSkills(title);
    const combinedSkills = [...new Set([...technicalSkills, ...relevantSkills])];
    
    // Generate name and workStyle
    const name = generateName();
    const workStyleOptions = getWorkStyleOptions(data.workStyle);
    const workStyle = workStyleOptions[Math.floor(Math.random() * workStyleOptions.length)];
    
    // Create a simplified sample with just enough data for the PDF
    return {
        name: name,
        title: title,
        summary: generateDetailedSummary(title, combinedSkills, softSkills, totalYears, data.workStyle),
        workExperience: [{
        company: "Example Company",
        industry: "Technology",
        title: title,
        period: "January 2020 - Present",
        duration: "3 years, 2 months",
        achievements: ["Example achievement 1", "Example achievement 2"]
        }],
        education: {
        degree: `Bachelor of ${generateRelevantDegree(title, "Bachelor's")}`,
        institution: "University",
        graduationDate: "May 2015"
        },
        skills: {
        technical: combinedSkills.length > 0 ? combinedSkills : getRelevantSkills(title),
        soft: softSkills.length > 0 ? softSkills : ["Communication", "Problem Solving", "Teamwork"]
        },
        certifications: certifications.length > 0 ? certifications : [],
        workStyle: workStyle
    };
    };

    const importAvatarData = (event) => {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
        try {
            const importedData = JSON.parse(e.target.result);
            setSavedAvatars(importedData);
            alert("Avatars imported successfully!");
        } catch (error) {
            alert("Error importing file: " + error.message);
        }
        };
        reader.readAsText(file);
    }
    };

    console.log("Rendering component with currentView:", currentView, "showSample:", showSample);

    return (
    <div className="bg-white rounded-lg shadow-lg p-6 max-w-4xl mx-auto">
        <h1 className="text-2xl font-bold mb-6 text-center text-blue-600">Ideal Candidate Avatar Tool</h1>
        
        <div className="flex justify-center mb-6 space-x-4">
        <button 
            onClick={() => {
            console.log("Switching to form view");
            setCurrentView("form");
            setShowSample(false);
            }} 
            className={`px-4 py-2 rounded ${currentView === "form" && !showSample ? "bg-blue-600 text-white" : "bg-gray-200"}`}
        >
            Create Avatar
        </button>
        <button 
            onClick={() => {
            console.log("Switching to saved avatars view");
            setCurrentView("savedAvatars");
            }} 
            className={`px-4 py-2 rounded ${currentView === "savedAvatars" ? "bg-blue-600 text-white" : "bg-gray-200"}`}
        >
            Saved Avatars ({savedAvatars.length})
        </button>
        </div>
        
        {showSample && sampleExperience ? (
        <div>
            <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold">Sample Candidate Profile</h2>
            <div className="flex space-x-2">
                <button 
                onClick={() => {
                    console.log("Going back to form");
                    setShowSample(false);
                }} 
                className="bg-gray-200 text-gray-800 px-4 py-2 rounded"
                >
                Back to Form
                </button>
                <button 
                onClick={saveAvatar} 
                className="bg-green-600 text-white px-4 py-2 rounded"
                >
                Save Avatar
                </button>
            </div>
            </div>
            
            <div className="border rounded-lg p-6 bg-gray-50">
            <div className="mb-6">
                <h3 className="text-2xl font-bold text-blue-800">{sampleExperience.name}</h3>
                <p className="text-lg text-blue-600">{sampleExperience.title}</p>
            </div>
            
            <div className="mb-6">
                <div className="mb-6">
                    <h4 className="font-bold text-gray-700 mb-2">Professional Summary</h4>
                    <ul className="list-disc pl-5 text-gray-700 space-y-1">
                        {sampleExperience.summary.split("\n").map((line, index) => (
                            <li key={index}>{line.trim()}</li>
                        ))}
                    </ul>
                </div>

            </div>
            
            <div className="mb-6">
                <h4 className="font-bold text-gray-700 mb-2">Work Experience</h4>
                {sampleExperience.workExperience.map((exp, index) => (
                <div key={index} className="mb-4">
                    <div className="flex justify-between items-start">
                    <div>
                        <p className="font-semibold text-lg">{exp.title}</p>
                        <p>{exp.company} • {exp.industry}</p>
                    </div>
                    <div className="text-right">
                        <p className="text-gray-600">{exp.period}</p>
                        <p className="text-gray-600 text-sm">{exp.duration}</p>
                    </div>
                    </div>
                    <ul className="list-disc pl-5 mt-2">
                    {exp.achievements.map((achievement, i) => (
                        <li key={i} className="text-gray-700 mt-1">{achievement}</li>
                    ))}
                    </ul>
                </div>
                ))}
            </div>
            
            <div className="mb-6">
                <h4 className="font-bold text-gray-700 mb-2">Education</h4>
                <p className="font-semibold">{sampleExperience.education.degree}</p>
                <p className="text-gray-700">{sampleExperience.education.institution}</p>
                <p className="text-gray-600">{sampleExperience.education.graduationDate}</p>
            </div>
            
            <div className="mb-6">
                <h4 className="font-bold text-gray-700 mb-2">Skills</h4>
                <div className="flex flex-wrap">
                <div className="w-full md:w-1/2 mb-4">
                    <p className="font-semibold">Technical Skills</p>
                    <ul className="list-disc pl-5">
                    {sampleExperience.skills.technical.map((skill, index) => (
                        <li key={index} className="text-gray-700">{skill}</li>
                    ))}
                    </ul>
                </div>
                <div className="w-full md:w-1/2">
                    <p className="font-semibold">Soft Skills</p>
                    <ul className="list-disc pl-5">
                    {sampleExperience.skills.soft.map((skill, index) => (
                        <li key={index} className="text-gray-700">{skill}</li>
                    ))}
                    </ul>
                </div>
                </div>
            </div>
            
            {sampleExperience.certifications.length > 0 && (
                <div className="mb-6">
                <h4 className="font-bold text-gray-700 mb-2">Certifications</h4>
                <ul className="list-disc pl-5">
                    {sampleExperience.certifications.map((cert, index) => (
                    <li key={index} className="text-gray-700">{cert}</li>
                    ))}
                </ul>
                </div>
            )}
            
            <div className="mb-6">
                <h4 className="font-bold text-gray-700 mb-2">Work Style</h4>
                <p className="text-gray-700">{sampleExperience.workStyle}</p>
            </div>
            </div>
        </div>
        ) : currentView === "form" ? (
        <div>
            <div className="mb-6">
            <label className="block text-gray-700 font-bold mb-2">Job Title:</label>
            <input
                type="text"
                value={jobTitle}
                onChange={(e) => setJobTitle(e.target.value)}
                className="w-full p-2 border rounded"
                placeholder="Senior Software Developer"
            />
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="mb-4">
                <label className="block text-gray-700 font-bold mb-2">Technical Skills:</label>
                {avatarData.technicalSkills.map((skill, index) => (
                <div key={`tech-${index}`} className="flex mb-2">
                    <input
                    type="text"
                    value={skill}
                    onChange={(e) => handleSkillChange("technicalSkills", index, e.target.value)}
                    className="w-full p-2 border rounded"
                    placeholder="e.g., JavaScript"
                    />
                    <button
                    onClick={() => removeSkill("technicalSkills", index)}
                    className="ml-2 text-red-500 px-2"
                    title="Remove skill"
                    >
                    ×
                    </button>
                </div>
                ))}
                <button
                onClick={() => addSkill("technicalSkills")}
                className="bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm"
                >
                + Add technical skill
                </button>
            </div>
            
            <div className="mb-4">
                <label className="block text-gray-700 font-bold mb-2">Soft Skills:</label>
                {avatarData.softSkills.map((skill, index) => (
                <div key={`soft-${index}`} className="flex mb-2">
                    <input
                    type="text"
                    value={skill}
                    onChange={(e) => handleSkillChange("softSkills", index, e.target.value)}
                    className="w-full p-2 border rounded"
                    placeholder="e.g., Communication"
                    />
                    <button
                    onClick={() => removeSkill("softSkills", index)}
                    className="ml-2 text-red-500 px-2"
                    title="Remove skill"
                    >
                    ×
                    </button>
                </div>
                ))}
                <button
                onClick={() => addSkill("softSkills")}
                className="bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm"
                >
                + Add soft skill
                </button>
            </div>
            
            <div className="mb-4">
                <label className="block text-gray-700 font-bold mb-2">Experience Level:</label>
                <select
                value={avatarData.experience}
                onChange={(e) => handleChange("experience", e.target.value)}
                className="w-full p-2 border rounded"
                >
                <option value="">Select experience level</option>
                <option value="Entry-level">Entry-level (0-2 years)</option>
                <option value="Mid-level">Mid-level (3-5 years)</option>
                <option value="Senior">Senior (6-9 years)</option>
                <option value="Lead/Principal">Lead/Principal (10+ years)</option>
                <option value="Executive">Executive</option>
                </select>
            </div>
            
            <div className="mb-4">
                <label className="block text-gray-700 font-bold mb-2">Education:</label>
                <select
                value={avatarData.education}
                onChange={(e) => handleChange("education", e.target.value)}
                className="w-full p-2 border rounded"
                >
                <option value="">Select education level</option>
                <option value="High School">High School</option>
                <option value="Associate's">Associate's Degree</option>
                <option value="Bachelor's">Bachelor's Degree</option>
                <option value="Master's">Master's Degree</option>
                <option value="PhD">PhD/Doctorate</option>
                <option value="Self-taught">Self-taught</option>
                </select>
            </div>
            
            <div className="mb-4">
                <label className="block text-gray-700 font-bold mb-2">Certifications:</label>
                {avatarData.certifications.map((cert, index) => (
                <div key={`cert-${index}`} className="flex mb-2">
                    <input
                    type="text"
                    value={cert}
                    onChange={(e) => handleCertificationChange(index, e.target.value)}
                    className="w-full p-2 border rounded"
                    placeholder="e.g., AWS Certified Solutions Architect"
                    />
                    <button
                    onClick={() => handleRemoveCertification(index)}
                    className="ml-2 text-red-500 px-2"
                    title="Remove certification"
                    >
                    ×
                    </button>
                </div>
                ))}
                <button
                onClick={handleAddCertification}
                className="bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm"
                >
                + Add certification
                </button>
            </div>
            
            <div className="mb-4">
                <label className="block text-gray-700 font-bold mb-2">Work Style:</label>
                <select
                value={avatarData.workStyle}
                onChange={(e) => handleChange("workStyle", e.target.value)}
                className="w-full p-2 border rounded"
                >
                <option value="">Select work style</option>
                <option value="Independent">Independent worker</option>
                <option value="Collaborative">Collaborative team member</option>
                <option value="Leader">Natural leader</option>
                <option value="Flexible">Flexible/Adaptive</option>
                <option value="Structured">Structured/Process-oriented</option>
                </select>
            </div>
            </div>
            
            <div className="mt-6 flex justify-end">
            <button
                onClick={generateSampleExperience}
                className="bg-green-600 text-white px-6 py-2 rounded font-bold"
            >
                Create Avatar
            </button>
            </div>
        </div>
        ) : (
        <div>
            <div className="mb-6 flex justify-between">
            <h2 className="text-xl font-bold">Saved Candidate Avatars</h2>
            <div className="flex space-x-2">
                <button 
                onClick={exportAvatarData}
                className="bg-blue-600 text-white px-4 py-2 rounded text-sm"
                disabled={savedAvatars.length === 0}
                >
                Export All (JSON)
                </button>
                <label className="bg-gray-600 text-white px-4 py-2 rounded text-sm cursor-pointer">
                Import
                <input 
                    type="file" 
                    accept=".json" 
                    onChange={importAvatarData} 
                    className="hidden" 
                />
                </label>
            </div>
            </div>
            
            {savedAvatars.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
                <p>No saved avatars yet. Create your first candidate avatar!</p>
            </div>
            ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {savedAvatars.map((avatar, index) => (
                <div key={index} className="border rounded p-4 hover:shadow-md">
                    <h3 className="font-bold text-lg mb-2">{avatar.title}</h3>
                    <p className="text-sm text-gray-600 mb-1">
                    <span className="font-semibold">Experience:</span> {avatar.data.experience || "Not specified"}
                    </p>
                    <p className="text-sm text-gray-600 mb-1">
                    <span className="font-semibold">Education:</span> {avatar.data.education || "Not specified"}
                    </p>
                    <p className="text-sm text-gray-600 mb-1">
                    <span className="font-semibold">Top Skills:</span> {avatar.data.technicalSkills.filter(s => s).slice(0, 2).join(", ") || "None specified"}
                    </p>
                    <div className="mt-4 flex justify-between">
                    <div className="flex space-x-2">
                        <button
                        onClick={() => loadAvatar(index)}
                        className="bg-blue-100 text-blue-600 px-3 py-1 rounded text-sm"
                        >
                        Edit
                        </button>
                        <button
                        onClick={() => exportAvatarToPDF(avatar)}
                        className="bg-green-100 text-green-600 px-3 py-1 rounded text-sm"
                        title="Export to PDF"
                        >
                        PDF
                        </button>
                    </div>
                    <button
                        onClick={() => deleteAvatar(index)}
                        className="bg-red-100 text-red-600 px-3 py-1 rounded text-sm"
                    >
                        Delete
                    </button>
                    </div>
                </div>
                ))}
            </div>
            )}
        </div>
        )}
    </div>
    );
};

// Render the component when script loads
(function() {
    function renderApp() {
        const rootElement = document.getElementById("candidate-avatar-root");
        if (rootElement && typeof React !== 'undefined' && typeof ReactDOM !== 'undefined') {
            ReactDOM.render(React.createElement(CandidateAvatarTool), rootElement);
            console.log("Candidate Avatar Tool rendered successfully");
        } else {
            console.log("Waiting for dependencies...");
            setTimeout(renderApp, 100);
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', renderApp);
    } else {
        renderApp();
    }
})();

