import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleGenAI, Type } from "@google/genai";
import { 
  Mail, Phone, MapPin, Link as LinkIcon, Globe, 
  Plus, Trash2, Wand2, Upload, User, X, Sparkles, 
  FileText, FileDown, Palette, ChevronDown 
} from 'lucide-react';

// --- TYPES ---
export interface Experience {
  id: string;
  role: string;
  company: string;
  date: string;
  description: string;
}

export interface Education {
  id: string;
  degree: string;
  school: string;
  date: string;
}

export interface CVData {
  personalInfo: {
    fullName: string;
    email: string;
    phone: string;
    location: string;
    website: string;
    summary: string;
    photo?: string;
  };
  experience: Experience[];
  education: Education[];
  skills: string[];
}

export type Theme = 'modern' | 'classic' | 'creative' | 'minimal' | 'professional';

export const INITIAL_CV_DATA: CVData = {
  personalInfo: {
    fullName: "Alex Doe",
    email: "alex.doe@example.com",
    phone: "(555) 123-4567",
    location: "New York, NY",
    website: "linkedin.com/in/alexdoe",
    summary: "Senior Software Engineer with 8+ years of experience in building scalable web applications. Proven track record of leading teams and delivering high-impact projects on time.",
  },
  experience: [
    {
      id: "1",
      role: "Senior Frontend Engineer",
      company: "Tech Solutions Inc.",
      date: "2020 - Present",
      description: "• Led the migration of legacy codebase to React 18, improving performance by 40%.\n• Mentored a team of 5 junior developers, conducting code reviews and technical workshops.\n• Implemented a new design system using Tailwind CSS.",
    },
    {
      id: "2",
      role: "Software Developer",
      company: "Creative Web Agency",
      date: "2017 - 2020",
      description: "• Developed responsive websites for over 20 clients using HTML, CSS, and JavaScript.\n• Collaborated with designers to ensure pixel-perfect implementation of UI mockups.\n• Optimized database queries to reduce API response times.",
    },
  ],
  education: [
    {
      id: "1",
      degree: "B.S. Computer Science",
      school: "University of Technology",
      date: "2013 - 2017",
    },
  ],
  skills: ["React", "TypeScript", "Node.js", "Tailwind CSS", "AWS", "GraphQL", "Agile Leadership"],
};

// --- GEMINI SERVICE ---
// Initialize with API Key safely
const apiKey = process.env.API_KEY || "";
const ai = new GoogleGenAI({ apiKey });

export const parseResumeText = async (text: string): Promise<CVData> => {
  const model = "gemini-2.5-flash";
  
  const response = await ai.models.generateContent({
    model,
    contents: `Parse the following raw text into a structured JSON resume. 
    If specific fields are missing, make a best guess or leave them empty string. 
    Ensure the output strictly follows the schema.
    
    Raw Text:
    ${text}`,
    config: {
      responseMimeType: "application/json",
      responseSchema: {
        type: Type.OBJECT,
        properties: {
          personalInfo: {
            type: Type.OBJECT,
            properties: {
              fullName: { type: Type.STRING },
              email: { type: Type.STRING },
              phone: { type: Type.STRING },
              location: { type: Type.STRING },
              website: { type: Type.STRING },
              summary: { type: Type.STRING },
              photo: { type: Type.STRING, description: "Leave empty unless a photo URL is explicitly provided" },
            },
            required: ["fullName", "email"],
          },
          experience: {
            type: Type.ARRAY,
            items: {
              type: Type.OBJECT,
              properties: {
                role: { type: Type.STRING },
                company: { type: Type.STRING },
                date: { type: Type.STRING },
                description: { type: Type.STRING },
              },
              required: ["role", "company"],
            },
          },
          education: {
            type: Type.ARRAY,
            items: {
              type: Type.OBJECT,
              properties: {
                degree: { type: Type.STRING },
                school: { type: Type.STRING },
                date: { type: Type.STRING },
              },
              required: ["degree", "school"],
            },
          },
          skills: {
            type: Type.ARRAY,
            items: { type: Type.STRING },
          },
        },
        required: ["personalInfo", "experience", "education", "skills"],
      },
    },
  });

  if (!response.text) {
    throw new Error("No response from AI");
  }

  const data = JSON.parse(response.text);
  
  return {
    ...data,
    experience: data.experience.map((e: any) => ({ ...e, id: Math.random().toString(36).substr(2, 9) })),
    education: data.education.map((e: any) => ({ ...e, id: Math.random().toString(36).substr(2, 9) })),
  };
};

export const enhanceDescription = async (text: string): Promise<string> => {
  const model = "gemini-2.5-flash";
  const response = await ai.models.generateContent({
    model,
    contents: `Rewrite the following resume bullet points to be more professional, action-oriented, and impactful. Keep it concise.
    
    Text: "${text}"`,
  });

  return response.text || text;
};

export const generateSummary = async (data: Pick<CVData, 'experience' | 'education' | 'skills'>): Promise<string> => {
  const model = "gemini-2.5-flash";
  
  const experienceText = data.experience.map(e => `${e.role} at ${e.company} (${e.date}): ${e.description}`).join('\n');
  const educationText = data.education.map(e => `${e.degree} at ${e.school}`).join('\n');
  const skillsText = data.skills.join(', ');

  const response = await ai.models.generateContent({
    model,
    contents: `Write a professional resume summary (max 3-4 sentences) based on the following details. Highlight years of experience, key roles, and major skills. Do not include placeholders.
    
    Experience:
    ${experienceText}
    
    Education:
    ${educationText}
    
    Skills:
    ${skillsText}`,
  });

  return response.text || "";
};

// --- COMPONENTS ---

// 1. CV PREVIEW
interface CVPreviewProps {
  data: CVData;
  theme: Theme;
}

const CVPreview: React.FC<CVPreviewProps> = ({ data, theme }) => {
  const { personalInfo, experience, education, skills } = data;

  const ContactItem = ({ icon: Icon, text }: { icon: any, text: string }) => (
    <div className="flex items-center gap-1.5">
      <Icon className="w-3.5 h-3.5" />
      <span>{text}</span>
    </div>
  );

  // Creative Theme
  if (theme === 'creative') {
    return (
      <div id="cv-preview" className="w-[794px] min-h-[1123px] mx-auto bg-white shadow-2xl print:shadow-none flex overflow-hidden">
        <div className="w-[30%] bg-slate-900 text-white p-6 flex flex-col gap-8 print:bg-slate-900 print:print-color-adjust">
          {personalInfo.photo && (
            <div className="w-32 h-32 mx-auto rounded-full overflow-hidden border-4 border-slate-700 shrink-0">
              <img src={personalInfo.photo} alt="Profile" className="w-full h-full object-cover" />
            </div>
          )}
          <div className="space-y-4 text-sm">
            <h3 className="text-slate-400 uppercase tracking-widest text-xs font-bold border-b border-slate-700 pb-2">Contact</h3>
            <div className="space-y-3">
              {personalInfo.email && <div className="break-all text-slate-300">{personalInfo.email}</div>}
              {personalInfo.phone && <div className="text-slate-300">{personalInfo.phone}</div>}
              {personalInfo.location && <div className="text-slate-300">{personalInfo.location}</div>}
              {personalInfo.website && <div className="break-all text-slate-300">{personalInfo.website}</div>}
            </div>
          </div>
          {skills.length > 0 && (
            <div className="space-y-4">
              <h3 className="text-slate-400 uppercase tracking-widest text-xs font-bold border-b border-slate-700 pb-2">Skills</h3>
              <div className="flex flex-wrap gap-2">
                {skills.map((skill, index) => (
                  <span key={index} className="bg-slate-800 text-slate-200 text-xs px-2 py-1 rounded">
                    {skill}
                  </span>
                ))}
              </div>
            </div>
          )}
           {education.length > 0 && (
             <div className="space-y-4">
               <h3 className="text-slate-400 uppercase tracking-widest text-xs font-bold border-b border-slate-700 pb-2">Education</h3>
               <div className="space-y-4">
                 {education.map((edu) => (
                   <div key={edu.id}>
                     <div className="font-bold text-slate-200 text-sm">{edu.school}</div>
                     <div className="text-xs text-slate-400">{edu.degree}</div>
                     <div className="text-xs text-slate-500 mt-0.5">{edu.date}</div>
                   </div>
                 ))}
               </div>
             </div>
           )}
        </div>
        <div className="w-[70%] p-8 bg-white flex flex-col">
          <div className="mb-8">
             <h1 className="text-5xl font-bold text-slate-900 mb-4 uppercase leading-none tracking-tight">{personalInfo.fullName}</h1>
             <p className="text-slate-600 leading-relaxed">{personalInfo.summary}</p>
          </div>
          {experience.length > 0 && (
            <section className="flex-1">
              <h2 className="text-xl font-bold uppercase tracking-widest text-slate-800 border-b-2 border-slate-100 mb-6 pb-2">Experience</h2>
              <div className="space-y-8">
                {experience.map((exp) => (
                  <div key={exp.id} className="relative pl-4 border-l-2 border-slate-200">
                    <div className="absolute -left-[9px] top-1.5 w-4 h-4 bg-white border-2 border-slate-300 rounded-full"></div>
                    <div className="flex justify-between items-baseline mb-1">
                      <h3 className="font-bold text-slate-900 text-lg">{exp.role}</h3>
                      <span className="text-sm text-slate-500 font-medium whitespace-nowrap">{exp.date}</span>
                    </div>
                    <div className="text-blue-600 font-semibold text-sm mb-2">{exp.company}</div>
                    <p className="text-slate-600 text-sm leading-relaxed whitespace-pre-line">{exp.description}</p>
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>
      </div>
    );
  }

  // Classic Theme
  if (theme === 'classic') {
    return (
       <div id="cv-preview" className="w-[794px] min-h-[1123px] mx-auto bg-[#fffbf7] shadow-2xl print:shadow-none p-12 text-gray-900 font-serif print:w-full print:p-0 print:bg-white">
        <header className="text-center border-b-2 border-gray-900 pb-6 mb-8">
           <h1 className="text-4xl font-bold mb-4 tracking-wide">{personalInfo.fullName}</h1>
           <div className="flex justify-center flex-wrap gap-4 text-sm text-gray-700">
              {personalInfo.email && <span>{personalInfo.email}</span>}
              {personalInfo.phone && <span>• {personalInfo.phone}</span>}
              {personalInfo.location && <span>• {personalInfo.location}</span>}
              {personalInfo.website && <span>• {personalInfo.website}</span>}
           </div>
        </header>
        {personalInfo.summary && (
          <section className="mb-8">
             <h2 className="text-center text-sm font-bold uppercase tracking-widest border-b border-gray-300 pb-2 mb-4 text-gray-800">Professional Profile</h2>
             <p className="text-justify leading-relaxed text-gray-800">{personalInfo.summary}</p>
          </section>
        )}
        {experience.length > 0 && (
           <section className="mb-8">
              <h2 className="text-center text-sm font-bold uppercase tracking-widest border-b border-gray-300 pb-2 mb-6 text-gray-800">Professional Experience</h2>
              <div className="space-y-6">
                 {experience.map(exp => (
                    <div key={exp.id}>
                       <div className="flex justify-between items-baseline mb-1 font-bold">
                          <div className="text-lg">{exp.company}</div>
                          <div className="text-sm">{exp.date}</div>
                       </div>
                       <div className="italic text-gray-700 mb-2">{exp.role}</div>
                       <p className="text-sm leading-relaxed whitespace-pre-line text-gray-800">{exp.description}</p>
                    </div>
                 ))}
              </div>
           </section>
        )}
        {education.length > 0 && (
           <section className="mb-8">
             <h2 className="text-center text-sm font-bold uppercase tracking-widest border-b border-gray-300 pb-2 mb-6 text-gray-800">Education</h2>
             <div className="space-y-4">
               {education.map(edu => (
                  <div key={edu.id} className="flex justify-between items-baseline">
                     <div>
                        <div className="font-bold">{edu.school}</div>
                        <div className="italic text-sm">{edu.degree}</div>
                     </div>
                     <div className="text-sm">{edu.date}</div>
                  </div>
               ))}
             </div>
           </section>
        )}
        {skills.length > 0 && (
           <section>
             <h2 className="text-center text-sm font-bold uppercase tracking-widest border-b border-gray-300 pb-2 mb-4 text-gray-800">Core Competencies</h2>
             <div className="text-center leading-loose">
                {skills.join(" • ")}
             </div>
           </section>
        )}
       </div>
    );
  }

  // Minimal Theme
  if (theme === 'minimal') {
    return (
      <div id="cv-preview" className="w-[794px] min-h-[1123px] mx-auto bg-white shadow-2xl print:shadow-none p-12 text-black print:w-full print:p-0">
        <header className="mb-8 pb-4 border-b-2 border-black">
          <h1 className="text-3xl font-bold uppercase mb-2 tracking-tight">{personalInfo.fullName}</h1>
          <div className="text-sm flex flex-wrap gap-x-4 gap-y-1 text-gray-800">
             {personalInfo.email && <span>{personalInfo.email}</span>}
             {personalInfo.phone && <span>| {personalInfo.phone}</span>}
             {personalInfo.location && <span>| {personalInfo.location}</span>}
             {personalInfo.website && <span>| {personalInfo.website}</span>}
          </div>
        </header>
        {personalInfo.summary && (
          <section className="mb-6">
            <h2 className="text-sm font-bold uppercase mb-2 tracking-wider">Summary</h2>
            <p className="text-sm leading-relaxed text-gray-900">{personalInfo.summary}</p>
          </section>
        )}
        {experience.length > 0 && (
           <section className="mb-6">
             <h2 className="text-sm font-bold uppercase mb-4 tracking-wider">Experience</h2>
             <div className="space-y-5">
               {experience.map(exp => (
                 <div key={exp.id}>
                   <div className="flex justify-between items-baseline mb-1">
                     <span className="font-bold text-base">{exp.role}</span>
                     <span className="text-sm font-medium">{exp.date}</span>
                   </div>
                   <div className="text-sm font-medium mb-1">{exp.company}</div>
                   <p className="text-sm leading-relaxed whitespace-pre-line text-gray-800">{exp.description}</p>
                 </div>
               ))}
             </div>
           </section>
        )}
        {education.length > 0 && (
           <section className="mb-6">
             <h2 className="text-sm font-bold uppercase mb-3 tracking-wider">Education</h2>
             <div className="space-y-2">
               {education.map(edu => (
                  <div key={edu.id} className="flex justify-between">
                     <div>
                        <span className="font-bold text-sm block">{edu.school}</span>
                        <span className="text-sm">{edu.degree}</span>
                     </div>
                     <span className="text-sm">{edu.date}</span>
                  </div>
               ))}
             </div>
           </section>
        )}
        {skills.length > 0 && (
           <section>
             <h2 className="text-sm font-bold uppercase mb-2 tracking-wider">Skills</h2>
             <div className="text-sm leading-relaxed">
               {skills.join(", ")}
             </div>
           </section>
        )}
      </div>
    );
  }

  // Professional Theme
  if (theme === 'professional') {
    return (
      <div id="cv-preview" className="w-[794px] min-h-[1123px] mx-auto bg-white shadow-2xl print:shadow-none flex flex-col print:w-full print:h-auto">
        <div className="bg-slate-800 text-white p-10 print:bg-slate-800 print:print-color-adjust">
           <h1 className="text-4xl font-bold mb-4 tracking-wide">{personalInfo.fullName}</h1>
           <div className="flex flex-wrap gap-6 text-sm text-slate-300">
             {personalInfo.email && <div className="flex items-center gap-2"><Mail className="w-4 h-4"/> {personalInfo.email}</div>}
             {personalInfo.phone && <div className="flex items-center gap-2"><Phone className="w-4 h-4"/> {personalInfo.phone}</div>}
             {personalInfo.location && <div className="flex items-center gap-2"><MapPin className="w-4 h-4"/> {personalInfo.location}</div>}
             {personalInfo.website && <div className="flex items-center gap-2"><Globe className="w-4 h-4"/> {personalInfo.website}</div>}
           </div>
        </div>
        <div className="p-10 flex-1">
           {personalInfo.summary && (
             <div className="mb-8">
               <h2 className="text-lg font-bold text-slate-800 border-b-2 border-slate-200 pb-2 mb-3">Professional Summary</h2>
               <p className="text-slate-700 leading-relaxed">{personalInfo.summary}</p>
             </div>
           )}
           {experience.length > 0 && (
             <div className="mb-8">
               <h2 className="text-lg font-bold text-slate-800 border-b-2 border-slate-200 pb-2 mb-4">Work History</h2>
               <div className="space-y-6">
                 {experience.map(exp => (
                   <div key={exp.id}>
                     <div className="flex justify-between items-baseline mb-1">
                       <h3 className="font-bold text-slate-900 text-lg">{exp.role}</h3>
                       <span className="text-sm font-medium text-slate-500 bg-slate-100 px-2 py-0.5 rounded">{exp.date}</span>
                     </div>
                     <div className="text-slate-700 font-medium mb-2">{exp.company}</div>
                     <p className="text-slate-600 text-sm leading-relaxed whitespace-pre-line">{exp.description}</p>
                   </div>
                 ))}
               </div>
             </div>
           )}
           <div className="grid grid-cols-2 gap-8">
              {education.length > 0 && (
                <div>
                   <h2 className="text-lg font-bold text-slate-800 border-b-2 border-slate-200 pb-2 mb-4">Education</h2>
                   <div className="space-y-4">
                     {education.map(edu => (
                       <div key={edu.id}>
                         <div className="font-bold text-slate-900">{edu.school}</div>
                         <div className="text-sm text-slate-700">{edu.degree}</div>
                         <div className="text-xs text-slate-500 mt-1">{edu.date}</div>
                       </div>
                     ))}
                   </div>
                </div>
              )}
              {skills.length > 0 && (
                 <div>
                   <h2 className="text-lg font-bold text-slate-800 border-b-2 border-slate-200 pb-2 mb-4">Skills</h2>
                   <ul className="list-disc list-inside text-sm text-slate-700 space-y-1">
                     {skills.map((skill, i) => (
                       <li key={i}>{skill}</li>
                     ))}
                   </ul>
                 </div>
              )}
           </div>
        </div>
      </div>
    );
  }

  // Modern Theme (Default)
  return (
    <div id="cv-preview" className="w-[794px] min-h-[1123px] mx-auto bg-white shadow-2xl print:shadow-none p-12 text-gray-800 print:w-full print:p-0">
      <header className="border-b-2 border-gray-800 pb-8 mb-8 flex gap-8 items-start">
        {personalInfo.photo && (
           <div className="w-32 h-32 shrink-0 rounded-full overflow-hidden border-2 border-gray-100 print:print-color-adjust">
             <img src={personalInfo.photo} alt="Profile" className="w-full h-full object-cover" />
           </div>
        )}
        <div className="flex-1">
          <h1 className="text-4xl font-bold uppercase tracking-wider text-gray-900 mb-2">{personalInfo.fullName}</h1>
          <div className="flex flex-wrap gap-4 text-sm text-gray-600 mt-3">
            {personalInfo.email && <ContactItem icon={Mail} text={personalInfo.email} />}
            {personalInfo.phone && <ContactItem icon={Phone} text={personalInfo.phone} />}
            {personalInfo.location && <ContactItem icon={MapPin} text={personalInfo.location} />}
            {personalInfo.website && <ContactItem icon={Globe} text={personalInfo.website} />}
          </div>
        </div>
      </header>
      {personalInfo.summary && (
        <section className="mb-6">
          <h2 className="text-lg font-bold uppercase tracking-widest text-gray-700 border-b border-gray-300 mb-3 pb-1">Professional Summary</h2>
          <p className="text-sm leading-relaxed text-gray-700 whitespace-pre-wrap">{personalInfo.summary}</p>
        </section>
      )}
      {experience.length > 0 && (
        <section className="mb-6">
          <h2 className="text-lg font-bold uppercase tracking-widest text-gray-700 border-b border-gray-300 mb-4 pb-1">Experience</h2>
          <div className="space-y-5">
            {experience.map((exp) => (
              <div key={exp.id}>
                <div className="flex justify-between items-baseline mb-1">
                  <h3 className="font-bold text-gray-900">{exp.role}</h3>
                  <span className="text-sm text-gray-600 font-medium whitespace-nowrap ml-4">{exp.date}</span>
                </div>
                <div className="text-gray-700 font-medium text-sm mb-2">{exp.company}</div>
                <p className="text-sm text-gray-600 leading-relaxed whitespace-pre-line">{exp.description}</p>
              </div>
            ))}
          </div>
        </section>
      )}
      {education.length > 0 && (
        <section className="mb-6">
          <h2 className="text-lg font-bold uppercase tracking-widest text-gray-700 border-b border-gray-300 mb-4 pb-1">Education</h2>
          <div className="space-y-4">
            {education.map((edu) => (
              <div key={edu.id}>
                <div className="flex justify-between items-baseline">
                  <h3 className="font-bold text-gray-900">{edu.school}</h3>
                  <span className="text-sm text-gray-600 font-medium whitespace-nowrap ml-4">{edu.date}</span>
                </div>
                <div className="text-sm text-gray-700">{edu.degree}</div>
              </div>
            ))}
          </div>
        </section>
      )}
      {skills.length > 0 && (
        <section>
          <h2 className="text-lg font-bold uppercase tracking-widest text-gray-700 border-b border-gray-300 mb-4 pb-1">Skills</h2>
          <div className="flex flex-wrap gap-2">
            {skills.map((skill, index) => (
              <span key={index} className="px-3 py-1 bg-gray-100 text-gray-700 text-sm font-medium rounded-full print:bg-transparent print:border print:border-gray-300 print:text-black">
                {skill}
              </span>
            ))}
          </div>
        </section>
      )}
    </div>
  );
};

// 2. EDITOR
interface EditorProps {
  data: CVData;
  onChange: (data: CVData) => void;
}

const Editor: React.FC<EditorProps> = ({ data, onChange }) => {
  const [enhancingId, setEnhancingId] = useState<string | null>(null);
  const [isGeneratingSummary, setIsGeneratingSummary] = useState(false);
  const photoInputRef = useRef<HTMLInputElement>(null);

  const updatePersonalInfo = (field: keyof CVData['personalInfo'], value: string) => {
    onChange({
      ...data,
      personalInfo: { ...data.personalInfo, [field]: value },
    });
  };

  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        updatePersonalInfo('photo', reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const removePhoto = () => {
    updatePersonalInfo('photo', '');
    if (photoInputRef.current) {
      photoInputRef.current.value = '';
    }
  };

  const updateExperience = (id: string, field: keyof Experience, value: string) => {
    onChange({
      ...data,
      experience: data.experience.map((exp) => (exp.id === id ? { ...exp, [field]: value } : exp)),
    });
  };

  const addExperience = () => {
    const newExp: Experience = {
      id: Date.now().toString(),
      role: 'Role Title',
      company: 'Company Name',
      date: 'Date Range',
      description: '',
    };
    onChange({ ...data, experience: [...data.experience, newExp] });
  };

  const removeExperience = (id: string) => {
    onChange({ ...data, experience: data.experience.filter((exp) => exp.id !== id) });
  };

  const updateEducation = (id: string, field: keyof Education, value: string) => {
    onChange({
      ...data,
      education: data.education.map((edu) => (edu.id === id ? { ...edu, [field]: value } : edu)),
    });
  };

  const addEducation = () => {
    const newEdu: Education = {
      id: Date.now().toString(),
      school: 'School Name',
      degree: 'Degree',
      date: 'Date Range',
    };
    onChange({ ...data, education: [...data.education, newEdu] });
  };

  const removeEducation = (id: string) => {
    onChange({ ...data, education: data.education.filter((edu) => edu.id !== id) });
  };

  const updateSkills = (value: string) => {
    const skillsArray = value.split(',').map(s => s.trim()).filter(Boolean);
    onChange({ ...data, skills: skillsArray });
  };

  const handleEnhance = async (id: string, text: string, type: 'experience' | 'summary') => {
    if (!text) return;
    setEnhancingId(id);
    try {
      const enhancedText = await enhanceDescription(text);
      if (type === 'experience') {
        updateExperience(id, 'description', enhancedText);
      } else {
        updatePersonalInfo('summary', enhancedText);
      }
    } catch (error) {
      console.error("Failed to enhance", error);
      alert("Failed to enhance text. Please check your API key and try again.");
    } finally {
      setEnhancingId(null);
    }
  };

  const handleGenerateSummary = async () => {
    if (data.experience.length === 0 && data.education.length === 0) {
      alert("Please add experience or education details first to generate a summary.");
      return;
    }
    
    setIsGeneratingSummary(true);
    try {
      const summary = await generateSummary({
        experience: data.experience,
        education: data.education,
        skills: data.skills
      });
      updatePersonalInfo('summary', summary);
    } catch (error) {
      console.error("Failed to generate summary", error);
      alert("Failed to generate summary. Please check your API key.");
    } finally {
      setIsGeneratingSummary(false);
    }
  };

  return (
    <div className="space-y-8 p-6 pb-20">
      {/* Personal Info */}
      <section className="space-y-4">
        <h2 className="text-xl font-semibold text-gray-800 border-b pb-2">Personal Details</h2>
        <div className="flex items-center gap-4 mb-4">
          <div className="relative group w-20 h-20 shrink-0">
            {data.personalInfo.photo ? (
              <img 
                src={data.personalInfo.photo} 
                alt="Profile" 
                className="w-full h-full rounded-full object-cover border-2 border-gray-200"
              />
            ) : (
              <div className="w-full h-full rounded-full bg-gray-100 flex items-center justify-center text-gray-400 border-2 border-gray-200 border-dashed">
                <User className="w-8 h-8" />
              </div>
            )}
            
            {data.personalInfo.photo ? (
               <button 
                onClick={removePhoto}
                className="absolute -top-1 -right-1 bg-red-500 text-white p-1 rounded-full hover:bg-red-600 transition-colors shadow-sm"
                title="Remove photo"
              >
                <X className="w-3 h-3" />
              </button>
            ) : (
              <button 
                onClick={() => photoInputRef.current?.click()}
                className="absolute inset-0 flex items-center justify-center bg-black/50 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
              >
                <Upload className="w-5 h-5" />
              </button>
            )}
          </div>
          
          <div className="flex-1">
             <input
              type="file"
              ref={photoInputRef}
              onChange={handlePhotoUpload}
              accept="image/*"
              className="hidden"
            />
            <button 
               onClick={() => photoInputRef.current?.click()}
               className="text-sm font-medium text-blue-600 hover:text-blue-700"
            >
              {data.personalInfo.photo ? "Change Photo" : "Upload Photo"}
            </button>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <input
            type="text"
            placeholder="Full Name"
            value={data.personalInfo.fullName}
            onChange={(e) => updatePersonalInfo('fullName', e.target.value)}
            className="p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
          />
          <input
            type="email"
            placeholder="Email"
            value={data.personalInfo.email}
            onChange={(e) => updatePersonalInfo('email', e.target.value)}
            className="p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
          />
          <input
            type="text"
            placeholder="Phone"
            value={data.personalInfo.phone}
            onChange={(e) => updatePersonalInfo('phone', e.target.value)}
            className="p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
          />
          <input
            type="text"
            placeholder="Location"
            value={data.personalInfo.location}
            onChange={(e) => updatePersonalInfo('location', e.target.value)}
            className="p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
          />
          <input
            type="text"
            placeholder="Website / LinkedIn"
            value={data.personalInfo.website}
            onChange={(e) => updatePersonalInfo('website', e.target.value)}
            className="p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none col-span-1 md:col-span-2"
          />
        </div>
        <div>
          <div className="flex justify-between items-end mb-1.5">
              <label className="text-sm font-medium text-gray-700">Professional Summary</label>
              <button
                  onClick={handleGenerateSummary}
                  disabled={isGeneratingSummary}
                  className="text-xs flex items-center gap-1.5 text-purple-600 hover:text-purple-700 font-medium bg-purple-50 px-2 py-1 rounded-md transition-colors hover:bg-purple-100"
              >
                  {isGeneratingSummary ? (
                      <div className="w-3 h-3 border-2 border-purple-600 border-t-transparent rounded-full animate-spin" />
                  ) : (
                      <Sparkles className="w-3 h-3" />
                  )}
                  Auto-Generate
              </button>
          </div>
          <div className="relative">
            <textarea
              placeholder="Professional Summary"
              value={data.personalInfo.summary}
              onChange={(e) => updatePersonalInfo('summary', e.target.value)}
              className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none h-32"
            />
            <button
              onClick={() => handleEnhance('summary', data.personalInfo.summary, 'summary')}
              disabled={!data.personalInfo.summary || !!enhancingId}
              className="absolute bottom-2 right-2 p-1.5 bg-gray-100 text-gray-600 rounded-md hover:bg-gray-200 transition-colors disabled:opacity-50"
            >
              {enhancingId === 'summary' ? <div className="animate-spin h-4 w-4 border-2 border-gray-600 border-t-transparent rounded-full"/> : <Wand2 className="w-4 h-4" />}
            </button>
          </div>
        </div>
      </section>

      {/* Experience */}
      <section className="space-y-4">
        <div className="flex justify-between items-center border-b pb-2">
          <h2 className="text-xl font-semibold text-gray-800">Experience</h2>
          <button onClick={addExperience} className="flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700">
            <Plus className="w-4 h-4" /> Add
          </button>
        </div>
        <div className="space-y-6">
          {data.experience.map((exp) => (
            <div key={exp.id} className="bg-gray-50 p-4 rounded-lg border relative group">
              <button
                onClick={() => removeExperience(exp.id)}
                className="absolute top-2 right-2 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <Trash2 className="w-4 h-4" />
              </button>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
                <input
                  type="text"
                  placeholder="Role"
                  value={exp.role}
                  onChange={(e) => updateExperience(exp.id, 'role', e.target.value)}
                  className="p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none"
                />
                <input
                  type="text"
                  placeholder="Company"
                  value={exp.company}
                  onChange={(e) => updateExperience(exp.id, 'company', e.target.value)}
                  className="p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none"
                />
                <input
                  type="text"
                  placeholder="Date (e.g., 2020 - Present)"
                  value={exp.date}
                  onChange={(e) => updateExperience(exp.id, 'date', e.target.value)}
                  className="p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none md:col-span-2"
                />
              </div>
              <div className="relative">
                <textarea
                  placeholder="Description (Bullet points)"
                  value={exp.description}
                  onChange={(e) => updateExperience(exp.id, 'description', e.target.value)}
                  className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none h-24 text-sm"
                />
                <button
                  onClick={() => handleEnhance(exp.id, exp.description, 'experience')}
                  disabled={!exp.description || !!enhancingId}
                  className="absolute bottom-2 right-2 p-1.5 bg-purple-100 text-purple-700 rounded-md hover:bg-purple-200 transition-colors disabled:opacity-50"
                >
                  {enhancingId === exp.id ? <div className="animate-spin h-4 w-4 border-2 border-purple-700 border-t-transparent rounded-full"/> : <Wand2 className="w-4 h-4" />}
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Education */}
      <section className="space-y-4">
        <div className="flex justify-between items-center border-b pb-2">
          <h2 className="text-xl font-semibold text-gray-800">Education</h2>
          <button onClick={addEducation} className="flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700">
            <Plus className="w-4 h-4" /> Add
          </button>
        </div>
        <div className="space-y-4">
          {data.education.map((edu) => (
            <div key={edu.id} className="bg-gray-50 p-4 rounded-lg border relative group">
               <button
                onClick={() => removeEducation(edu.id)}
                className="absolute top-2 right-2 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <Trash2 className="w-4 h-4" />
              </button>
              <div className="grid grid-cols-1 gap-3">
                <input
                  type="text"
                  placeholder="School"
                  value={edu.school}
                  onChange={(e) => updateEducation(edu.id, 'school', e.target.value)}
                  className="p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none"
                />
                <input
                  type="text"
                  placeholder="Degree"
                  value={edu.degree}
                  onChange={(e) => updateEducation(edu.id, 'degree', e.target.value)}
                  className="p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none"
                />
                 <input
                  type="text"
                  placeholder="Date"
                  value={edu.date}
                  onChange={(e) => updateEducation(edu.id, 'date', e.target.value)}
                  className="p-2 border rounded focus:ring-2 focus:ring-blue-500 outline-none"
                />
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Skills */}
      <section className="space-y-4">
        <h2 className="text-xl font-semibold text-gray-800 border-b pb-2">Skills</h2>
        <textarea
          placeholder="Enter skills separated by commas (e.g., React, Node.js, Design)"
          value={data.skills.join(', ')}
          onChange={(e) => updateSkills(e.target.value)}
          className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none h-24"
        />
      </section>
    </div>
  );
};

// 3. MAIN APP
const App: React.FC = () => {
  const [cvData, setCvData] = useState<CVData>(INITIAL_CV_DATA);
  const [showAIModal, setShowAIModal] = useState(false);
  const [rawText, setRawText] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [theme, setTheme] = useState<Theme>('modern');

  const handleDownloadPDF = () => {
    const element = document.getElementById('cv-preview');
    if (!element) return;
    
    setIsDownloading(true);

    const opt = {
      margin: 0,
      filename: `${cvData.personalInfo.fullName.replace(/\s+/g, '_')}_CV.pdf`,
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 2, useCORS: true, logging: false },
      jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };

    // @ts-ignore
    if (window.html2pdf) {
      // @ts-ignore
      window.html2pdf().set(opt).from(element).save().then(() => {
        setIsDownloading(false);
      }).catch((err: any) => {
        console.error("PDF generation failed:", err);
        setIsDownloading(false);
        alert("Direct PDF generation failed. Opening print dialog instead.");
        window.print();
      });
    } else {
      window.print();
      setIsDownloading(false);
    }
  };

  const handleAIParse = async () => {
    if (!rawText.trim()) return;
    setIsProcessing(true);
    try {
      const parsedData = await parseResumeText(rawText);
      setCvData(parsedData);
      setShowAIModal(false);
      setRawText('');
    } catch (error) {
      console.error("Error parsing resume:", error);
      alert("Failed to parse resume content. Please ensure your API key is configured correctly.");
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 flex flex-col">
      <nav className="bg-white border-b border-gray-200 px-6 py-4 flex justify-between items-center no-print sticky top-0 z-30 shadow-sm">
        <div className="flex items-center gap-2">
            <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white">
                <FileText className="w-5 h-5"/>
            </div>
            <h1 className="text-xl font-bold text-gray-800 hidden sm:block">CV Forge AI</h1>
        </div>
        <div className="flex items-center gap-2 sm:gap-3">
          <div className="hidden md:flex items-center bg-gray-100 rounded-lg p-1 mr-2 border border-gray-200">
            <Palette className="w-4 h-4 text-gray-500 ml-2 mr-2" />
            <div className="relative">
              <select 
                value={theme}
                onChange={(e) => setTheme(e.target.value as Theme)}
                className="bg-transparent text-sm font-medium text-gray-700 py-1 pr-8 pl-1 outline-none cursor-pointer appearance-none"
              >
                <option value="modern">Modern</option>
                <option value="classic">Classic</option>
                <option value="creative">Creative</option>
                <option value="minimal">Minimal</option>
                <option value="professional">Professional</option>
              </select>
              <ChevronDown className="w-3 h-3 text-gray-500 absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none" />
            </div>
          </div>
          <button
            onClick={() => setShowAIModal(true)}
            className="flex items-center gap-2 px-3 sm:px-4 py-2 bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors font-medium text-sm"
          >
            <Sparkles className="w-4 h-4" />
            <span className="hidden sm:inline">AI Import</span>
            <span className="sm:hidden">AI</span>
          </button>
          <div className="h-8 w-px bg-gray-300 mx-1"></div>
          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-3 sm:px-4 py-2 bg-gray-900 text-white rounded-lg hover:bg-gray-800 transition-colors font-medium text-sm shadow-sm ml-2 disabled:opacity-70 disabled:cursor-wait"
          >
            {isDownloading ? (
               <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
            ) : (
               <FileDown className="w-4 h-4" />
            )}
            <span className="hidden sm:inline">Download PDF</span>
            <span className="sm:hidden">PDF</span>
          </button>
        </div>
      </nav>

      <main className="flex-1 flex flex-col md:flex-row overflow-hidden relative">
        <div className="w-full md:w-1/2 lg:w-5/12 overflow-y-auto bg-white border-r border-gray-200 no-print h-[calc(100vh-64px)] scrollbar-thin">
            <Editor data={cvData} onChange={setCvData} />
        </div>
        <div className="w-full md:w-1/2 lg:w-7/12 overflow-y-auto bg-gray-200 p-4 sm:p-8 flex justify-center h-[calc(100vh-64px)] print:w-full print:h-auto print:bg-white print:p-0 print:overflow-visible">
           <div className="transform scale-[0.6] sm:scale-75 lg:scale-90 origin-top print:scale-100 print:transform-none transition-transform duration-200">
             <CVPreview data={cvData} theme={theme} />
           </div>
        </div>
      </main>

      {showAIModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 no-print backdrop-blur-sm">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-2xl flex flex-col max-h-[90vh]">
            <div className="p-6 border-b flex justify-between items-center">
              <div>
                <h2 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                  <Sparkles className="w-5 h-5 text-purple-600" />
                  Import Resume Content
                </h2>
                <p className="text-sm text-gray-500 mt-1">Paste your existing resume text, LinkedIn about section, or rough notes.</p>
              </div>
              <button
                onClick={() => setShowAIModal(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <div className="p-6 flex-1 overflow-y-auto">
              <textarea
                value={rawText}
                onChange={(e) => setRawText(e.target.value)}
                placeholder="Paste text here... e.g. John Doe, Software Engineer..."
                className="w-full h-64 p-4 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none font-mono text-sm resize-none"
              />
            </div>
            <div className="p-6 border-t bg-gray-50 rounded-b-xl flex justify-end gap-3">
               <button onClick={() => setShowAIModal(false)} className="px-5 py-2.5 text-gray-700 font-medium hover:bg-gray-200 rounded-lg transition-colors">Cancel</button>
              <button
                onClick={handleAIParse}
                disabled={!rawText.trim() || isProcessing}
                className="px-5 py-2.5 bg-purple-600 text-white font-medium rounded-lg hover:bg-purple-700 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isProcessing ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Processing...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4" />
                    Generate CV
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);