// frontend/src/components/ATSAnalyzer.jsx
import React, { useState, useEffect } from 'react';
import { useResume } from '../contexts/ResumeContext';
import { ChartBarIcon } from '@heroicons/react/24/outline';

const ATSAnalyzer = () => {
    const { resumeData, jobDescription, setJobDescription, atsScore, setAtsScore } = useResume();
    const [missingKeywords, setMissingKeywords] = useState([]);

    const calculateATSScore = () => {
        if (!jobDescription || !resumeData.skills) {
            setAtsScore(0);
            setMissingKeywords([]);
            return;
        }

        const skills = resumeData.skills.toLowerCase().split(',').map(s => s.trim());
        const jobText = jobDescription.toLowerCase();
        
        const matchedSkills = skills.filter(skill => jobText.includes(skill));
        const score = skills.length > 0 ? (matchedSkills.length / skills.length) * 100 : 0;
        
        const extractedKeywords = extractKeywords(jobDescription);
        const missing = extractedKeywords.filter(keyword => 
            !skills.includes(keyword.toLowerCase()) && 
            !resumeData.summary?.toLowerCase().includes(keyword.toLowerCase())
        );
        
        setAtsScore(Math.round(score));
        setMissingKeywords(missing.slice(0, 10));
    };

    const extractKeywords = (text) => {
        const commonKeywords = ['javascript', 'python', 'react', 'node', 'sql', 'aws', 'docker', 'leadership', 'project management', 'agile', 'communication', 'problem solving'];
        const words = text.toLowerCase().split(/\s+/);
        const keywords = [...new Set(words.filter(word => word.length > 3 && commonKeywords.some(kw => kw.includes(word))))];
        return keywords.slice(0, 15);
    };

    useEffect(() => {
        const debounce = setTimeout(calculateATSScore, 500);
        return () => clearTimeout(debounce);
    }, [jobDescription, resumeData.skills, resumeData.summary]);

    const getScoreColor = () => {
        if (atsScore >= 80) return 'text-green-600';
        if (atsScore >= 60) return 'text-yellow-600';
        return 'text-red-600';
    };

    return (
        <div className="card p-6">
            <div className="flex items-center gap-2 mb-4">
                <ChartBarIcon className="w-6 h-6 text-primary-600" />
                <h3 className="text-lg font-semibold">ATS Score Analyzer</h3>
            </div>
            
            <div className="mb-4">
                <label className="block text-sm font-medium mb-2">Job Description</label>
                <textarea
                    rows="4"
                    value={jobDescription}
                    onChange={(e) => setJobDescription(e.target.value)}
                    placeholder="Paste the job description here to analyze compatibility..."
                    className="input-field"
                />
            </div>
            
            {jobDescription && (
                <div className="mt-4">
                    <div className="flex justify-between items-center mb-2">
                        <span className="font-medium">Compatibility Score</span>
                        <span className={`text-2xl font-bold ${getScoreColor()}`}>{atsScore}%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2 mb-4">
                        <div className="bg-primary-600 h-2 rounded-full transition-all duration-500" style={{ width: `${atsScore}%` }}></div>
                    </div>
                    
                    {missingKeywords.length > 0 && (
                        <div>
                            <p className="text-sm font-medium text-yellow-600 mb-2">Missing Keywords:</p>
                            <div className="flex flex-wrap gap-2">
                                {missingKeywords.map((keyword, idx) => (
                                    <span key={idx} className="bg-yellow-100 text-yellow-800 px-2 py-1 rounded text-xs">
                                        {keyword}
                                    </span>
                                ))}
                            </div>
                            <p className="text-xs text-gray-500 mt-2">Add these keywords to improve your ATS score</p>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default ATSAnalyzer;