// frontend/src/App.jsx
import React, { useState, useEffect } from 'react';
import EditorPanel from './components/Editor/EditorPanel';
import PreviewPanel from './components/Preview/PreviewPanel';
import Toolbar from './components/UI/Toolbar';
import { saveResume, getResume } from './api';

function App() {
  const [resumeData, setResumeData] = useState({
    personal: {
      name: 'Sarah Johnson',
      title: 'Senior Product Designer',
      email: 'sarah.j@example.com',
      phone: '+1 (555) 123-4567',
      location: 'New York, NY'
    },
    summary: 'Product designer with 8+ years of experience creating user-centered digital products. Led design teams at Series A startups to Fortune 500 companies.',
    skills: ['Figma', 'Adobe XD', 'User Research', 'Prototyping', 'Design Systems'],
    experience: [
      {
        id: 1,
        company: 'DesignStudio Inc.',
        position: 'Lead Product Designer',
        start_date: '2021-03',
        end_date: 'Present',
        description: 'Lead design for flagship product, increasing user engagement by 45% through redesign.'
      }
    ],
    education: [
      {
        id: 1,
        degree: 'BFA in Graphic Design',
        school: 'Rhode Island School of Design',
        year: '2015'
      }
    ]
  });
  
  const [selectedTemplate, setSelectedTemplate] = useState('modern');
  const [sectionsOrder, setSectionsOrder] = useState(['summary', 'skills', 'experience', 'education']);
  const [resumeId, setResumeId] = useState(null);
  const [autoSave, setAutoSave] = useState(true);
  
  useEffect(() => {
    const loadResume = async () => {
      const saved = await getResume(resumeId);
      if (saved) setResumeData(saved);
    };
    loadResume();
  }, [resumeId]);
  
  useEffect(() => {
    if (autoSave && resumeData) {
      const timer = setTimeout(() => saveResume({ data: resumeData, template: selectedTemplate, sections_order: sectionsOrder }), 1000);
      return () => clearTimeout(timer);
    }
  }, [resumeData, selectedTemplate, sectionsOrder, autoSave]);
  
  return (
    <div className="flex h-screen bg-gray-50">
      <Toolbar 
        onSave={() => saveResume({ data: resumeData, template: selectedTemplate })}
        onExport={() => window.open(`http://localhost:8000/api/export_pdf.php?id=${resumeId}`)}
        onTemplateChange={setSelectedTemplate}
        currentTemplate={selectedTemplate}
      />
      <div className="flex flex-1 pt-16">
        <EditorPanel 
          data={resumeData}
          onChange={setResumeData}
          sectionsOrder={sectionsOrder}
          onReorderSections={setSectionsOrder}
        />
        <PreviewPanel 
          data={resumeData}
          template={selectedTemplate}
        />
      </div>
    </div>
  );
}

export default App;