const { useState, useRef } = React;
const NAVY='#1a2744',ORANGE='#F4831F',F="'Barlow','Segoe UI',sans-serif";

const loadScript=(src,key)=>new Promise((ok,fail)=>{
  if(window[key])return ok();
  const s=document.createElement('script');s.src=src;s.onload=ok;s.onerror=fail;document.head.appendChild(s);
});

const readPdfText=async(file)=>{
  await loadScript('https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js','pdfjsLib');
  window.pdfjsLib.GlobalWorkerOptions.workerSrc='https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
  const buf=await file.arrayBuffer();
  const doc=await window.pdfjsLib.getDocument({data:buf}).promise;
  let text='';
  for(let p=1;p<=doc.numPages;p++){const page=await doc.getPage(p);const ct=await page.getTextContent();text+=ct.items.map(i=>i.str).join(' ')+'\n';}
  return text;
};

const PatLogo=()=>(<img src="/patagonianlogo2.png" alt="Patagonian" style={{height:32,objectFit:'contain'}}/>);

const SecTitle=({text})=>(<div style={{marginBottom:14}}><span style={{display:'block',fontFamily:F,fontSize:11.5,fontWeight:700,letterSpacing:2,color:NAVY}}>{text}</span><div style={{width:26,height:2,background:ORANGE,marginTop:5}}/></div>);

const CVTemplate=({data,position})=>(
  <div style={{width:794,background:'#fff',fontFamily:F}}>
    <div style={{background:NAVY,backgroundImage:'repeating-linear-gradient(-45deg,rgba(255,255,255,.022) 0,rgba(255,255,255,.022) 1px,transparent 1px,transparent 13px)',padding:'26px 36px 30px'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:18}}>
        <PatLogo/>
        <div style={{textAlign:'right',color:'rgba(255,255,255,.72)',fontSize:10.5,lineHeight:1.95}}><div><em>Reimagine</em> the future,</div><div>inspire <strong>innovation.</strong></div></div>
      </div>
      <h1 style={{margin:'0 0 4px',color:'#fff',fontSize:37,fontWeight:300,letterSpacing:-0.5,lineHeight:1.15}}>{data.name}</h1>
      <div style={{color:'rgba(255,255,255,.6)',fontSize:15,fontWeight:400}}>{position}</div>
    </div>
    <div style={{display:'flex'}}>
      <div style={{flex:'1 1 60%',padding:'30px 22px 48px 36px'}}>
        <SecTitle text="EXPERIENCE"/>
        {(data.experience||[]).map((exp,i)=>(<div key={i} style={{marginBottom:22}}>
          <p style={{margin:'0 0 2px',fontSize:13,fontWeight:700,color:NAVY}}>{exp.role}{exp.company?`, ${exp.company}`:''}</p>
          <p style={{margin:'0 0 8px',fontSize:10,color:'#aaa',textTransform:'uppercase',letterSpacing:0.8}}>{exp.location}{exp.startDate?` \u2014 ${exp.startDate} \u2013 ${exp.endDate}`:''}</p>
          {(exp.description||[]).map((b,j)=>(<div key={j} style={{display:'flex',gap:7,fontSize:11.5,color:'#333',lineHeight:1.6,marginBottom:4}}><span style={{color:'#ccc',flexShrink:0}}>-</span><span>{b}</span></div>))}
        </div>))}
      </div>
      <div style={{flex:'0 0 36%',padding:'30px 36px 48px 14px',borderLeft:'1px solid #efefef'}}>
        <SecTitle text="SKILLS"/>
        <div style={{marginBottom:26}}>{(data.skills||[]).map((s,i)=>(<div key={i} style={{display:'flex',gap:9,fontSize:12.5,color:'#444',marginBottom:9}}><span style={{color:'#ddd',flexShrink:0}}>-</span><span>{s}</span></div>))}</div>
        <SecTitle text="LANGUAGES"/>
        <div style={{marginBottom:26}}>{(data.languages||[]).map((l,i)=>(<p key={i} style={{margin:'0 0 8px',fontSize:12.5,color:'#555'}}>{l}</p>))}</div>
        <SecTitle text="EDUCATION"/>
        {(data.education||[]).map((e,i)=>(<div key={i} style={{marginBottom:12}}><p style={{margin:'0 0 2px',fontSize:11.5,fontWeight:700,textTransform:'uppercase',letterSpacing:0.4,color:NAVY}}>{e.degree}</p><p style={{margin:0,fontSize:11.5,color:'#666'}}>{e.institution}</p></div>))}
      </div>
    </div>
  </div>
);

const DropZone=({label,file,onFile,icon='📄'})=>{
  const [drag,setDrag]=useState(false);const ref=useRef();
  return(<div onClick={()=>ref.current?.click()} onDragOver={e=>{e.preventDefault();setDrag(true)}} onDragLeave={()=>setDrag(false)} onDrop={e=>{e.preventDefault();setDrag(false);if(e.dataTransfer.files[0])onFile(e.dataTransfer.files[0])}} style={{border:`2px dashed ${drag?ORANGE:file?'#22c55e':'#d1d5db'}`,borderRadius:10,padding:'18px 16px',cursor:'pointer',textAlign:'center',background:drag?'#F4831F0a':file?'#22c55e0a':'#fafafa',transition:'all .18s'}}>
    <input ref={ref} type="file" accept=".pdf" style={{display:'none'}} onChange={e=>{if(e.target.files[0])onFile(e.target.files[0])}}/>
    <div style={{fontSize:22,marginBottom:5}}>{file?'✅':icon}</div>
    <p style={{margin:0,fontSize:13,color:file?'#16a34a':'#6b7280'}}>{file?file.name:label}</p>
    {file&&<p style={{margin:'3px 0 0',fontSize:11,color:'#9ca3af'}}>Click to replace</p>}
  </div>);
};

const Inp=({value,onChange,placeholder,multiline=false})=>{
  const base={width:'100%',border:'1px solid #e5e7eb',borderRadius:6,padding:'7px 10px',fontSize:12.5,fontFamily:F,outline:'none',background:'#fafafa',transition:'border-color .15s,background .15s',boxSizing:'border-box'};
  const focus=e=>{e.target.style.borderColor=ORANGE;e.target.style.background='#fff'};
  const blur=e=>{e.target.style.borderColor='#e5e7eb';e.target.style.background='#fafafa'};
  return multiline?<textarea value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} rows={2} onFocus={focus} onBlur={blur} style={{...base,resize:'vertical',lineHeight:1.5}}/>:<input value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} onFocus={focus} onBlur={blur} style={base}/>;
};

const Card=({title,children})=>(<div style={{background:'#fff',borderRadius:10,padding:'16px 18px',marginBottom:12,boxShadow:'0 1px 4px rgba(0,0,0,.06)'}}><p style={{fontSize:10.5,fontWeight:700,letterSpacing:1.5,color:'#9ca3af',textTransform:'uppercase',margin:'0 0 14px'}}>{title}</p>{children}</div>);

const EditPanel=({data,position,setPosition,setCvData})=>{
  const [newSkill,setNewSkill]=useState('');
  const [newLang,setNewLang]=useState('');
  const [openExp,setOpenExp]=useState([0]);
  const update=(field,value)=>setCvData(d=>({...d,[field]:value}));
  const toggleExp=i=>setOpenExp(o=>o.includes(i)?o.filter(x=>x!==i):[...o,i]);
  const removeSkill=i=>update('skills',data.skills.filter((_,j)=>j!==i));
  const addSkill=()=>{const v=newSkill.trim();if(!v)return;update('skills',[...data.skills,v]);setNewSkill('');};
  const updateExp=(ei,f,v)=>update('experience',data.experience.map((e,j)=>j===ei?{...e,[f]:v}:e));
  const updateBullet=(ei,bi,v)=>update('experience',data.experience.map((e,j)=>j===ei?{...e,description:e.description.map((b,k)=>k===bi?v:b)}:e));
  const removeBullet=(ei,bi)=>update('experience',data.experience.map((e,j)=>j===ei?{...e,description:e.description.filter((_,k)=>k!==bi)}:e));
  const addBullet=ei=>update('experience',data.experience.map((e,j)=>j===ei?{...e,description:[...e.description,'']}:e));
  const removeExp=ei=>update('experience',data.experience.filter((_,j)=>j!==ei));
  const removeLang=i=>update('languages',data.languages.filter((_,j)=>j!==i));
  const addLang=()=>{const v=newLang.trim();if(!v)return;update('languages',[...data.languages,v]);setNewLang('');};
  const updateEdu=(i,f,v)=>update('education',data.education.map((e,j)=>j===i?{...e,[f]:v}:e));
  const removeEdu=i=>update('education',data.education.filter((_,j)=>j!==i));
  const addEdu=()=>update('education',[...data.education,{degree:'',institution:''}]);
  const lbl=t=><label style={{display:'block',fontSize:11,fontWeight:600,color:'#6b7280',marginBottom:4}}>{t}</label>;
  const TagPill=({text,onRemove})=>(<div style={{display:'flex',alignItems:'center',gap:4,background:'#f0f2f5',borderRadius:20,padding:'4px 8px 4px 12px',fontSize:12,color:NAVY,fontWeight:600}}>{text}<button onClick={onRemove} style={{background:'none',border:'none',cursor:'pointer',color:'#9ca3af',fontSize:15,lineHeight:1,padding:'0 0 0 2px',marginTop:-1}}>×</button></div>);
  const AddBtn=({onClick})=>(<button onClick={onClick} style={{padding:'7px 14px',background:ORANGE,border:'none',borderRadius:6,color:'#fff',cursor:'pointer',fontSize:13,fontWeight:700,whiteSpace:'nowrap',flexShrink:0,fontFamily:F}}>+ Add</button>);

  return(
    <div style={{height:'calc(100vh - 52px)',overflowY:'auto',padding:'14px 16px 40px',background:'#f0f2f5'}}>
      <Card title="Basic Info">
        <div style={{display:'flex',flexDirection:'column',gap:10}}>
          <div>{lbl('Full Name')}<Inp value={data.name} onChange={v=>update('name',v)} placeholder="Full name"/></div>
          <div>{lbl('Position')}<Inp value={position} onChange={setPosition} placeholder="Position title"/></div>
        </div>
      </Card>
      <Card title={`Skills (${data.skills.length})`}>
        <div style={{display:'flex',flexWrap:'wrap',gap:6,marginBottom:data.skills.length?10:0}}>
          {data.skills.map((s,i)=><TagPill key={i} text={s} onRemove={()=>removeSkill(i)}/>)}
        </div>
        <div style={{display:'flex',gap:6,marginTop:data.skills.length?0:4}}><Inp value={newSkill} onChange={setNewSkill} placeholder="Add a skill…"/><AddBtn onClick={addSkill}/></div>
      </Card>
      <Card title={`Experience (${data.experience.length} entries)`}>
        {data.experience.map((exp,ei)=>(
          <div key={ei} style={{marginBottom:ei<data.experience.length-1?10:0}}>
            <div style={{display:'flex',alignItems:'center',gap:6}}>
              <div onClick={()=>toggleExp(ei)} style={{flex:1,display:'flex',justifyContent:'space-between',alignItems:'center',padding:'8px 12px',background:openExp.includes(ei)?'#eef0f3':'#f8f9fb',borderRadius:openExp.includes(ei)?'8px 8px 0 0':8,border:'1px solid #e5e7eb',cursor:'pointer',transition:'background .15s'}}>
                <span style={{fontSize:12.5,fontWeight:700,color:NAVY,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',maxWidth:'85%'}}>{exp.role||'Untitled'}{exp.company?`, ${exp.company}`:''}</span>
                <span style={{fontSize:12,color:'#9ca3af',flexShrink:0}}>{openExp.includes(ei)?'▲':'▼'}</span>
              </div>
              <button onClick={()=>removeExp(ei)} style={{background:'none',border:'none',cursor:'pointer',color:'#fca5a5',fontSize:18,padding:'4px',lineHeight:1,flexShrink:0}}>×</button>
            </div>
            {openExp.includes(ei)&&(
              <div style={{padding:'14px 12px 12px',border:'1px solid #e5e7eb',borderTop:'none',borderRadius:'0 0 8px 8px',display:'flex',flexDirection:'column',gap:10}}>
                <div style={{display:'flex',gap:8}}>
                  <div style={{flex:1}}>{lbl('Role')}<Inp value={exp.role||''} onChange={v=>updateExp(ei,'role',v)} placeholder="Job title"/></div>
                  <div style={{flex:1}}>{lbl('Company')}<Inp value={exp.company||''} onChange={v=>updateExp(ei,'company',v)} placeholder="Company"/></div>
                </div>
                <div style={{display:'flex',gap:8}}>
                  <div style={{flex:2}}>{lbl('Location')}<Inp value={exp.location||''} onChange={v=>updateExp(ei,'location',v)} placeholder="City, Country"/></div>
                  <div style={{flex:1}}>{lbl('Start')}<Inp value={exp.startDate||''} onChange={v=>updateExp(ei,'startDate',v)} placeholder="Jun 2022"/></div>
                  <div style={{flex:1}}>{lbl('End')}<Inp value={exp.endDate||''} onChange={v=>updateExp(ei,'endDate',v)} placeholder="Present"/></div>
                </div>
                <div>
                  {lbl(`Bullets (${(exp.description||[]).length})`)}
                  <div style={{display:'flex',flexDirection:'column',gap:6}}>
                    {(exp.description||[]).map((b,bi)=>(
                      <div key={bi} style={{display:'flex',gap:6,alignItems:'flex-start'}}>
                        <span style={{color:'#ccc',paddingTop:9,fontSize:16,flexShrink:0}}>—</span>
                        <div style={{flex:1}}><Inp value={b} onChange={v=>updateBullet(ei,bi,v)} placeholder="Describe an achievement…" multiline/></div>
                        <button onClick={()=>removeBullet(ei,bi)} style={{background:'none',border:'none',cursor:'pointer',color:'#fca5a5',fontSize:18,padding:'6px 2px',lineHeight:1,flexShrink:0}}>×</button>
                      </div>
                    ))}
                  </div>
                  <button onClick={()=>addBullet(ei)} style={{marginTop:8,background:'none',border:`1px dashed ${ORANGE}`,borderRadius:6,color:ORANGE,cursor:'pointer',fontSize:12,fontWeight:600,padding:'5px 12px',fontFamily:F}}>+ Add bullet</button>
                </div>
              </div>
            )}
          </div>
        ))}
      </Card>
      <Card title="Languages">
        <div style={{display:'flex',flexWrap:'wrap',gap:6,marginBottom:data.languages.length?10:0}}>{data.languages.map((l,i)=><TagPill key={i} text={l} onRemove={()=>removeLang(i)}/>)}</div>
        <div style={{display:'flex',gap:6}}><Inp value={newLang} onChange={setNewLang} placeholder="Add a language…"/><AddBtn onClick={addLang}/></div>
      </Card>
      <Card title="Education">
        {data.education.map((e,i)=>(<div key={i} style={{display:'flex',gap:8,marginBottom:10}}><div style={{flex:1,display:'flex',flexDirection:'column',gap:6}}><Inp value={e.degree||''} onChange={v=>updateEdu(i,'degree',v)} placeholder="Degree / Title"/><Inp value={e.institution||''} onChange={v=>updateEdu(i,'institution',v)} placeholder="Institution — YYYY"/></div><button onClick={()=>removeEdu(i)} style={{background:'none',border:'none',cursor:'pointer',color:'#fca5a5',fontSize:18,padding:'4px',alignSelf:'flex-start'}}>×</button></div>))}
        <button onClick={addEdu} style={{background:'none',border:'1px dashed #d1d5db',borderRadius:6,color:'#6b7280',cursor:'pointer',fontSize:12,fontWeight:600,padding:'5px 12px',fontFamily:F}}>+ Add education</button>
      </Card>
    </div>
  );
};

function App(){
  const [step,setStep]=useState('input');
  const [cvFile,setCvFile]=useState(null);
  const [position,setPosition]=useState('');
  const [mode,setMode]=useState('manual');
  const [manualSkills,setManualSkills]=useState('');
  const [jdFile,setJdFile]=useState(null);
  const [cvData,setCvData]=useState(null);
  const [statusMsg,setStatusMsg]=useState('');
  const [errorMsg,setErrorMsg]=useState('');
  const [activeTab,setActiveTab]=useState('edit');
  const [downloading,setDownloading]=useState(false);
  const previewRef=useRef(null);
  const canProcess=!!(cvFile&&position.trim()&&(mode==='manual'?manualSkills.trim():jdFile));

  const processCV=async()=>{
    setStep('processing');
    try{
      setStatusMsg('Extracting CV text…');
      const cvText=await readPdfText(cvFile);
      let skillsCtx;
      if(mode==='manual'){skillsCtx=`Required technical skills: ${manualSkills}`;}
      else{setStatusMsg('Reading Job Description…');skillsCtx=`Job Description:\n${await readPdfText(jdFile)}`;}
      setStatusMsg('AI is analyzing the CV…');
      const res=await fetch('/api/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:
`You are a professional CV parser. Extract and structure data from this CV into JSON.
Position applied for: ${position}
${skillsCtx}
CV Text:
${cvText}

Return ONLY a JSON object — no markdown, no explanation:
{"name":"Full Name","skills":["Skill1"],"experience":[{"role":"","company":"","location":"","startDate":"","endDate":"","description":[""]}],"languages":["English"],"education":[{"degree":"","institution":"School - YYYY"}]}
Rules: ALL English · skills by position relevance · ALL experience entries · action-verb bullets`
      })});
      const apiData=await res.json();
      if(apiData.error)throw new Error(apiData.error);
      const raw=apiData.content.replace(/```[\w]*\n?|```\n?/g,'').trim();
      let parsed;
      try{parsed=JSON.parse(raw);}catch{const m=raw.match(/\{[\s\S]*\}/);if(m)parsed=JSON.parse(m[0]);else throw new Error('Could not parse AI response.');}
      setCvData(parsed);setActiveTab('edit');setStep('review');
    }catch(err){setErrorMsg(err.message||'Unknown error');setStep('error');}
  };

  const downloadPdf=async()=>{
    setActiveTab('preview');
    await new Promise(r=>setTimeout(r,150));
    setDownloading(true);
    try{
      await loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js','html2canvas');
      await loadScript('https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js','jspdf');
      await document.fonts.ready;
      const canvas=await window.html2canvas(previewRef.current,{scale:2,useCORS:true,allowTaint:true,logging:false,backgroundColor:'#ffffff'});
      const{jsPDF}=window.jspdf;
      const pdf=new jsPDF({orientation:'portrait',unit:'mm',format:'a4'});
      const A4W=210,A4H=297,pxPerMm=canvas.width/A4W,pageH_px=A4H*pxPerMm;
      const numPages=Math.ceil(canvas.height/pageH_px);
      for(let i=0;i<numPages;i++){
        if(i>0)pdf.addPage();
        const yOff=Math.round(i*pageH_px),sliceH=Math.min(Math.round(pageH_px),canvas.height-yOff);
        const slice=document.createElement('canvas');slice.width=canvas.width;slice.height=sliceH;
        slice.getContext('2d').drawImage(canvas,0,yOff,canvas.width,sliceH,0,0,canvas.width,sliceH);
        pdf.addImage(slice.toDataURL('image/jpeg',0.95),'JPEG',0,0,A4W,sliceH/pxPerMm);
      }
      pdf.save(`${(cvData.name||'CV').replace(/\s+/g,'_')}_Patagonian.pdf`);
    }catch(e){alert('PDF error: '+e.message);}
    finally{setDownloading(false);}
  };

  const reset=()=>{setCvFile(null);setPosition('');setMode('manual');setManualSkills('');setJdFile(null);setCvData(null);setErrorMsg('');setStep('input');};

  if(step==='input')return(
    <div style={{minHeight:'100vh',background:'#f0f2f5',fontFamily:F}}>
      <div style={{background:NAVY,padding:'13px 26px',display:'flex',alignItems:'center',gap:10}}>
        <PatLogo/><span style={{color:'rgba(255,255,255,.22)',fontSize:20,margin:'0 4px'}}>|</span>
        <span style={{color:'rgba(255,255,255,.5)',fontSize:13}}>CV Converter</span>
      </div>
      <div style={{maxWidth:540,margin:'36px auto',padding:'0 20px 60px'}}>
        <h2 style={{color:NAVY,fontSize:21,fontWeight:700,margin:'0 0 6px'}}>New CV Conversion</h2>
        <p style={{color:'#6b7280',fontSize:13,margin:'0 0 28px',lineHeight:1.65}}>Upload a candidate PDF and configure the target position.</p>
        <div style={{marginBottom:20}}>
          <label style={{display:'block',fontSize:11.5,fontWeight:700,color:'#374151',marginBottom:7,letterSpacing:0.5}}>CANDIDATE CV (PDF) *</label>
          <DropZone label="Drop CV PDF here or click to browse" file={cvFile} onFile={setCvFile} icon="📄"/>
        </div>
        <div style={{marginBottom:20}}>
          <label style={{display:'block',fontSize:11.5,fontWeight:700,color:'#374151',marginBottom:7,letterSpacing:0.5}}>POSITION *</label>
          <input value={position} onChange={e=>setPosition(e.target.value)} placeholder="e.g. Senior React Developer"
            style={{width:'100%',padding:'10px 13px',border:'1.5px solid #d1d5db',borderRadius:8,fontSize:14,outline:'none',boxSizing:'border-box',fontFamily:F,transition:'border-color .15s'}}
            onFocus={e=>e.target.style.borderColor=ORANGE} onBlur={e=>e.target.style.borderColor='#d1d5db'}/>
        </div>
        <div style={{marginBottom:28}}>
          <label style={{display:'block',fontSize:11.5,fontWeight:700,color:'#374151',marginBottom:8,letterSpacing:0.5}}>SKILLS SOURCE *</label>
          <div style={{display:'flex',gap:8,marginBottom:12}}>
            {[{v:'manual',label:'✏️  Enter Manually'},{v:'jd',label:'📋  Job Description PDF'}].map(({v,label})=>(
              <button key={v} onClick={()=>setMode(v)} style={{flex:1,padding:'9px 0',border:'none',borderRadius:8,cursor:'pointer',fontFamily:F,fontSize:13,fontWeight:600,background:mode===v?NAVY:'#e5e7eb',color:mode===v?'#fff':'#6b7280',transition:'all .15s'}}>{label}</button>
            ))}
          </div>
          {mode==='manual'
            ?<textarea value={manualSkills} onChange={e=>setManualSkills(e.target.value)} placeholder="e.g. React, TypeScript, Node.js, AWS, Docker…" rows={3}
              style={{width:'100%',padding:'10px 13px',border:'1.5px solid #d1d5db',borderRadius:8,fontSize:13,resize:'vertical',outline:'none',boxSizing:'border-box',fontFamily:F,transition:'border-color .15s'}}
              onFocus={e=>e.target.style.borderColor=ORANGE} onBlur={e=>e.target.style.borderColor='#d1d5db'}/>
            :<DropZone label="Drop Job Description PDF here or click to browse" file={jdFile} onFile={setJdFile} icon="📋"/>}
        </div>
        <button onClick={processCV} disabled={!canProcess} style={{width:'100%',padding:'13px 0',border:'none',borderRadius:10,fontFamily:F,fontSize:15,fontWeight:700,background:canProcess?ORANGE:'#e5e7eb',color:canProcess?'#fff':'#9ca3af',cursor:canProcess?'pointer':'not-allowed',transition:'all .15s'}}>
          Generate Patagonian CV →
        </button>
      </div>
    </div>
  );

  if(step==='processing')return(
    <div style={{minHeight:'100vh',background:'#f0f2f5',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:F}}>
      <div style={{textAlign:'center'}}>
        <div style={{width:50,height:50,margin:'0 auto 22px',border:'4px solid #e5e7eb',borderTopColor:ORANGE,borderRadius:'50%',animation:'spin .85s linear infinite'}}/>
        <h3 style={{color:NAVY,fontSize:17,fontWeight:700,margin:'0 0 8px'}}>Processing CV</h3>
        <p style={{color:'#9ca3af',fontSize:13,margin:0}}>{statusMsg}</p>
      </div>
    </div>
  );

  if(step==='error')return(
    <div style={{minHeight:'100vh',background:'#f0f2f5',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:F}}>
      <div style={{background:'#fff',borderRadius:14,padding:'40px',maxWidth:400,textAlign:'center',boxShadow:'0 4px 28px rgba(0,0,0,.1)'}}>
        <div style={{fontSize:36,marginBottom:12}}>⚠️</div>
        <h3 style={{color:'#dc2626',fontWeight:700,margin:'0 0 10px',fontSize:17}}>Error</h3>
        <p style={{color:'#6b7280',fontSize:13,lineHeight:1.65,margin:'0 0 22px'}}>{errorMsg}</p>
        <button onClick={reset} style={{padding:'9px 24px',background:NAVY,color:'#fff',border:'none',borderRadius:8,cursor:'pointer',fontSize:14,fontWeight:600}}>← Try Again</button>
      </div>
    </div>
  );

  const Tab=({id,icon,label})=>(<button onClick={()=>setActiveTab(id)} style={{padding:'6px 16px',border:'none',borderRadius:6,cursor:'pointer',fontFamily:F,fontSize:13,fontWeight:600,background:activeTab===id?'rgba(255,255,255,.18)':'transparent',color:activeTab===id?'#fff':'rgba(255,255,255,.5)',transition:'all .15s'}}>{icon}&nbsp;{label}</button>);

  return(
    <div style={{height:'100vh',display:'flex',flexDirection:'column',fontFamily:F,overflow:'hidden'}}>
      <div style={{background:NAVY,padding:'0 18px',height:52,flexShrink:0,display:'flex',alignItems:'center',justifyContent:'space-between',boxShadow:'0 2px 14px rgba(0,0,0,.3)',zIndex:99}}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <PatLogo/><span style={{color:'rgba(255,255,255,.22)',margin:'0 4px',fontSize:18}}>|</span>
          <span style={{color:'rgba(255,255,255,.5)',fontSize:12.5,maxWidth:180,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{cvData?.name}</span>
        </div>
        <div style={{display:'flex',gap:3,background:'rgba(0,0,0,.22)',borderRadius:8,padding:'3px'}}>
          <Tab id="edit" icon="✏️" label="Review & Edit"/>
          <Tab id="preview" icon="👁" label="Preview"/>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button onClick={reset} style={{padding:'6px 14px',background:'transparent',border:'1px solid rgba(255,255,255,.25)',borderRadius:7,color:'rgba(255,255,255,.7)',cursor:'pointer',fontSize:12.5,fontWeight:600}}>← New CV</button>
          <button onClick={downloadPdf} disabled={downloading} style={{padding:'6px 16px',background:ORANGE,border:'none',borderRadius:7,color:'#fff',cursor:downloading?'wait':'pointer',fontSize:12.5,fontWeight:700,opacity:downloading?.75:1,display:'flex',alignItems:'center',gap:6}}>
            {downloading?<><div style={{width:11,height:11,border:'2px solid rgba(255,255,255,.35)',borderTopColor:'#fff',borderRadius:'50%',animation:'spin .7s linear infinite'}}/>Generating…</>:'⬇ Download PDF'}
          </button>
        </div>
      </div>
      <div style={{flex:1,overflow:'hidden'}}>
        {activeTab==='edit'&&cvData&&<EditPanel data={cvData} position={position} setPosition={setPosition} setCvData={setCvData}/>}
        {activeTab==='preview'&&cvData&&(
          <div style={{height:'100%',overflowY:'auto',overflowX:'auto',background:'#ced3da',padding:'24px 20px 40px',display:'flex',justifyContent:'center'}}>
            <div style={{boxShadow:'0 6px 44px rgba(0,0,0,.22)',display:'inline-block',lineHeight:'normal'}}>
              <div ref={previewRef}><CVTemplate data={cvData} position={position}/></div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
