// frontend/src/contexts/ResumeContext.jsx
import React, { createContext, useState, useContext, useCallback } from 'react';
import api from '../services/api';
export const ResumeContext = createContext();
export const useResume = () => useContext(ResumeContext);

export const ResumeProvider = ({ children }) => {
    const [resumeData, setResumeData] = useState({
        fullName: '',
        email: '',
        jobTitle: '',
        yearsOfExperience: '',
        skills: '',
        summary: '',
        experience: [{ company: '', role: '', startDate: '', endDate: '', description: '' }],
        education: [{ school: '', degree: '', year: '' }],
    });
    const [template, setTemplate] = useState('modern');
    const [atsScore, setAtsScore] = useState(0);
    const [jobDescription, setJobDescription] = useState('');
    const [currentResumeId, setCurrentResumeId] = useState(null);

    const loadResume = useCallback((resume) => {
        if (resume && resume.resume_data) {
            setResumeData(resume.resume_data);
            setTemplate(resume.template || 'modern');
            setAtsScore(resume.ats_score || 0);
            setJobDescription(resume.job_description || '');
            setCurrentResumeId(resume.id);
        }
    }, []);

    const saveResume = useCallback(async () => {
        try {
            await api.post('/resume/save', {
                resume_data: resumeData,
                template,
                ats_score: atsScore,
                job_description: jobDescription,
                resume_id: currentResumeId
            });
            return true;
        } catch (error) {
            console.error('Save failed:', error);
            return false;
        }
    }, [resumeData, template, atsScore, jobDescription, currentResumeId]);

    const enhanceWithAI = useCallback(async () => {
        try {
            const response = await api.post('/resume/generate', {
                summary: resumeData.summary,
                experience: resumeData.experience
            });
            if (response.data.success) {
                setResumeData(prev => ({
                    ...prev,
                    summary: response.data.data.summary || prev.summary,
                    experience: response.data.data.experience || prev.experience
                }));
            }
            return true;
        } catch (error) {
            console.error('AI enhancement failed:', error);
            return false;
        }
    }, [resumeData]);

    return (
        <ResumeContext.Provider value={{
            resumeData, setResumeData,
            template, setTemplate,
            atsScore, setAtsScore,
            jobDescription, setJobDescription,
            currentResumeId, setCurrentResumeId,
            loadResume, saveResume, enhanceWithAI
        }}>
            {children}
        </ResumeContext.Provider>
    );
};