// Generating, Preview, Export, Beautify, Dashboard
const HEADLINES = [
  "Reading your answers…",
  "Drafting your summary…",
  "Polishing your bullets…",
  "Picking the right verbs…",
  "Almost there…",
];

// ---- small helpers ----------------------------------------------------------
function relTime(iso) {
  if (!iso) return '';
  const ms = Date.now() - new Date(iso).getTime();
  const m = Math.floor(ms / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  const d = Math.floor(h / 24);
  return d === 1 ? 'yesterday' : `${d}d ago`;
}

function atsScore(data) {
  if (!data) return 0;
  let s = 58;
  if (data.summary) s += 8;
  if ((data.experience || []).length) s += 10;
  if ((data.experience || []).some(e => (e.bullets || []).length >= 2)) s += 8;
  if ((data.skills || []).length >= 4) s += 8;
  if (data.email) s += 3;
  if (data.phone) s += 3;
  if ((data.education || []).length) s += 2;
  return Math.min(99, s);
}

// Build a Word-compatible .doc (HTML) and trigger a real download.
function downloadDoc(data) {
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const contact = [data.location, data.phone, data.email, ...(data.links || [])].filter(Boolean).map(esc).join(' &middot; ');
  const exp = (data.experience || []).map(e => `
    <p style="margin:8pt 0 0"><b>${esc(e.title)}</b>, ${esc(e.company)}<span style="float:right">${esc(e.dates)}</span></p>
    ${e.location ? `<p style="margin:0;font-style:italic;color:#444">${esc(e.location)}</p>` : ''}
    <ul style="margin:2pt 0 0">${(e.bullets || []).map(b => `<li>${esc(b)}</li>`).join('')}</ul>`).join('');
  const edu = (data.education || []).map(ed => `<p style="margin:2pt 0"><b>${esc(ed.school)}</b> — ${esc(ed.degree)}<span style="float:right">${esc(ed.year)}</span></p>`).join('');
  const proj = (data.projects || []).map(p => `<p style="margin:2pt 0"><b>${esc(p.name)}</b> — ${esc(p.desc)}<span style="float:right">${esc(p.year)}</span></p>`).join('');
  const html = `<!doctype html><html><head><meta charset="utf-8"><title>${esc(data.name)}</title>
    <style>body{font-family:'Times New Roman',serif;font-size:11pt;color:#000;max-width:7.5in;margin:0 auto}
    h1{font-size:18pt;margin:0}h2{font-size:11pt;text-transform:uppercase;letter-spacing:.06em;border-bottom:1px solid #000;padding-bottom:2pt;margin:14pt 0 4pt}
    ul{padding-left:18pt}li{margin:2pt 0}p{line-height:1.4}</style></head><body>
    <h1>${esc(data.name)}</h1>
    <p style="font-size:10pt;color:#333;margin:2pt 0 0">${contact}</p>
    ${data.summary ? `<h2>Summary</h2><p>${esc(data.summary)}</p>` : ''}
    ${(data.experience || []).length ? `<h2>Experience</h2>${exp}` : ''}
    ${edu ? `<h2>Education</h2>${edu}` : ''}
    ${(data.skills || []).length ? `<h2>Skills</h2><p>${(data.skills || []).map(esc).join(' &middot; ')}</p>` : ''}
    ${proj ? `<h2>Projects</h2>${proj}` : ''}
    </body></html>`;
  const blob = new Blob(['﻿', html], { type: 'application/msword' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  a.href = url;
  a.download = `Resumerush_${(data.name || 'Resume').replace(/\s+/g, '_')}_${date}.doc`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

// ===========================================================================
function GeneratingScreen({ go, surveyData, setResume, setResumeId }) {
  const [phase, setPhase] = useState(0);
  const [pct, setPct] = useState(0);
  const [error, setError] = useState(null);
  const readyRef = useRef(false);
  const okRef = useRef(false);
  const navedRef = useRef(false);

  const run = () => {
    setError(null);
    setPct(0); setPhase(0);
    readyRef.current = false; okRef.current = false; navedRef.current = false;
    window.RR.generateResume(surveyData || {}).then(async ({ resume, error: err }) => {
      if (err || !resume) { setError(err || 'Generation failed.'); return; }
      setResume(resume);
      try {
        const title = surveyData?.name ? `${surveyData.name}'s resume` : (surveyData?.role || 'My resume');
        const row = await window.RR.db.save({ title, target_role: surveyData?.role || '', data: resume });
        if (row && row.id) setResumeId(row.id);
        window.RR.survey?.clear();
      } catch (e) { /* persistence is best-effort */ }
      okRef.current = true; readyRef.current = true;
    });
  };

  useEffect(() => { run(); }, []);

  useEffect(() => {
    if (error) return undefined;
    const headlineT = setInterval(() => setPhase(p => Math.min(p + 1, HEADLINES.length - 1)), 1800);
    const progT = setInterval(() => setPct(p => {
      const ceiling = readyRef.current ? 100 : 90;
      const next = Math.min(ceiling, p + (5 + Math.random() * 6));
      if (next >= 100 && okRef.current && !navedRef.current) {
        navedRef.current = true;
        clearInterval(progT);
        setTimeout(() => go('preview'), 600);
      }
      return next;
    }), 500);
    return () => { clearInterval(headlineT); clearInterval(progT); };
  }, [error]);

  if (error) {
    return (
      <div style={{ minHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, textAlign: 'center' }}>
        <div style={{ maxWidth: 460 }} className="fade-up">
          <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(220,38,38,0.1)', color: 'var(--error)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
            <Icon.x size={30}/>
          </div>
          <h2 className="t-h2" style={{ margin: 0 }}>We couldn't generate your resume.</h2>
          <p className="t-body secondary" style={{ marginTop: 8, marginBottom: 24 }}>
            The AI service didn't respond. This is usually temporary — give it another try.
          </p>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
            <Btn variant="secondary" onClick={() => go('survey', { resume: true })}>Edit answers</Btn>
            <Btn variant="primary" icon={<Icon.refresh size={16}/>} onClick={run}>Try again</Btn>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100%', display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', textAlign:'center', position:'relative', overflow:'hidden', padding: 24 }}>
      {Array.from({length: 12}).map((_, i) => (
        <span key={i} style={{
          position:'absolute',
          left: `${30 + (i * 17) % 40}%`,
          top: `${30 + (i * 23) % 40}%`,
          width: 6, height: 6, borderRadius:'50%',
          background:'var(--accent-primary)',
          opacity: 0.1 + (i % 4) * 0.05,
          animation: `drift ${3 + i * 0.3}s var(--e-inout) infinite`,
          animationDelay: `${-i * 0.5}s`,
        }}/>
      ))}

      <div style={{ position:'relative', zIndex: 2 }}>
        <div style={{
          width: 120, height: 120, borderRadius: 28,
          display:'inline-flex', alignItems:'center', justifyContent:'center',
          marginBottom: 48,
          boxShadow: '0 30px 60px rgba(0,0,0,0.18)',
          animation: 'pulse 2s var(--e-inout) infinite', position:'relative',
        }}>
          <img src="assets/brand/icon.png" alt="Resumerush" style={{ width: '100%', height: '100%', borderRadius: 28, display: 'block' }}/>
          {[0, 120, 240].map(deg => (
            <span key={deg} style={{ position:'absolute', inset: -20, borderRadius:'50%', animation: `spin ${3 + deg/120}s linear infinite`, animationDelay: `${-deg/360}s` }}>
              <span style={{ position:'absolute', top: -6, left:'50%', width: 8, height: 8, borderRadius:'50%', background:'var(--accent-primary)', opacity: 0.6, transform:'translateX(-50%)' }}/>
            </span>
          ))}
        </div>

        <h1 className="t-h1" key={phase} style={{ margin: 0, animation:'fadeUp 0.4s var(--e-out)' }}>{HEADLINES[phase]}</h1>

        <div style={{ width: 320, margin: '32px auto 0' }}>
          <div className="progress"><div className="progress-fill" style={{ width: `${pct}%` }}/></div>
        </div>

        <div className="t-body-sm muted" style={{ marginTop: 48 }}>We never train on your data.</div>
      </div>
    </div>
  );
}

// ===========================================================================
function PreviewScreen({ go, resume, setResume, surveyData, resumeId, setResumeId, user }) {
  const [toast, setToast] = useState('');
  const [busy, setBusy] = useState(null);
  const [working, setWorking] = useState('');
  const [loading, setLoading] = useState(!!resumeId && !resume);
  const [title, setTitle] = useState('');
  const [savedAt, setSavedAt] = useState(null);
  const idRef = useRef(resumeId || null);

  const tone = surveyData?.tone || 'Confident';
  const data = resume;
  const role = (data && data.experience && data.experience[0] && data.experience[0].title) || surveyData?.role || '';
  const displayTitle = title || (data && data.name ? `${data.name}` : 'My resume');

  const flash = (msg) => { setToast(msg); setTimeout(() => setToast(''), 2500); };

  useEffect(() => {
    if (resumeId && !resume) {
      setLoading(true);
      window.RR.db.get(resumeId).then(row => {
        if (row) { setResume(row.data); setTitle(row.title || ''); setSavedAt(row.updated_at || null); idRef.current = row.id; }
        setLoading(false);
      });
    }
  }, [resumeId]);

  const persist = async (newData, msg) => {
    setResume(newData);
    try {
      const row = await window.RR.db.save({ id: idRef.current || undefined, title: displayTitle, target_role: role, data: newData });
      if (row) { idRef.current = row.id; if (!resumeId) setResumeId(row.id); setSavedAt(row.updated_at || new Date().toISOString()); }
    } catch (e) { /* best-effort */ }
    if (msg) flash(msg);
  };

  const updateBullet = (ei, bi, newText) => {
    const exp = data.experience.map((e, i) => {
      if (i !== ei) return e;
      const bullets = newText === null ? e.bullets.filter((_, j) => j !== bi) : e.bullets.map((b, j) => (j === bi ? newText : b));
      return { ...e, bullets };
    });
    persist({ ...data, experience: exp });
  };

  const onEdit = async (act, info = {}) => {
    const { ei, bi, text } = info;
    if (act === 'regen') {
      setBusy(`${ei}:${bi}`);
      const better = await window.RR.rephraseBullet({ text, role, tone, mode: 'rewrite' });
      setBusy(null);
      if (better) { updateBullet(ei, bi, better); flash('Bullet regenerated. ✨'); }
      else flash('Could not reach the AI — try again.');
    } else if (act === 'edit') {
      const next = window.prompt('Edit this bullet:', text);
      if (next != null && next.trim()) { updateBullet(ei, bi, next.trim()); flash('Saved.'); }
    } else if (act === 'del') {
      updateBullet(ei, bi, null);
      flash('Bullet deleted.');
    }
  };

  const regenerateAll = async () => {
    if (!surveyData) { flash('Edit your answers first.'); return; }
    setWorking('Regenerating everything…');
    const { resume: r } = await window.RR.generateResume({ ...surveyData });
    setWorking('');
    if (r) persist(r, 'Fresh draft ready. ✨');
    else flash('Could not regenerate — try again.');
  };

  const transformAll = async (mode, label) => {
    setWorking(label);
    const exp = [];
    for (const e of data.experience || []) {
      const bullets = [];
      for (const b of e.bullets || []) {
        const r = await window.RR.rephraseBullet({ text: b, role, tone, mode });
        bullets.push(r || b);
      }
      exp.push({ ...e, bullets });
    }
    setWorking('');
    persist({ ...data, experience: exp }, 'Updated. ✨');
  };

  const tuneForJob = async () => {
    const jd = window.prompt('Paste the job description to tune your resume toward:');
    if (!jd || !jd.trim()) return;
    setWorking('Tuning to the job…');
    const base = surveyData || { role };
    const payload = { ...base, transcript: `${base.transcript || ''}\n\nTARGET JOB DESCRIPTION:\n${jd.trim()}` };
    const { resume: r } = await window.RR.generateResume(payload);
    setWorking('');
    if (r) persist(r, 'Tuned to the job. ✨');
    else flash('Could not tune — try again.');
  };

  const rename = async () => {
    const next = window.prompt('Rename this resume:', displayTitle);
    if (next == null || !next.trim()) return;
    setTitle(next.trim());
    if (idRef.current) { await window.RR.db.rename(idRef.current, next.trim()); flash('Renamed.'); }
  };
  const duplicate = async () => {
    if (!idRef.current) { flash('Save first.'); return; }
    await window.RR.db.duplicate(idRef.current);
    flash('Duplicated — find it on your dashboard.');
  };
  const removeResume = async () => {
    if (!idRef.current) { go('dashboard'); return; }
    if (!window.confirm('Delete this resume? This cannot be undone.')) return;
    await window.RR.db.remove(idRef.current);
    go('dashboard');
  };

  if (loading) {
    return <div style={{ minHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <span style={{ width: 28, height: 28, border: '3px solid var(--border-default)', borderTopColor: 'var(--accent-primary)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }}/>
    </div>;
  }
  if (!data) {
    return <div style={{ minHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, textAlign: 'center' }}>
      <div style={{ maxWidth: 420 }}>
        <h2 className="t-h2" style={{ margin: 0 }}>No resume open.</h2>
        <p className="t-body secondary" style={{ marginTop: 8, marginBottom: 24 }}>Start a new one and we'll build it from your answers.</p>
        <Btn variant="primary" icon={<Icon.plus size={16}/>} onClick={() => go('welcome')}>New resume</Btn>
      </div>
    </div>;
  }

  return (
    <div style={{ minHeight: '100%', display:'grid', gridTemplateColumns: '280px 1fr 320px', background:'var(--bg-canvas)' }}>
      <aside style={{ borderRight:'1px solid var(--border-default)', padding: '24px 20px', background:'var(--bg-surface)' }}>
        <div style={{ marginBottom: 24 }}>
          <button onClick={() => go('dashboard')} style={{ background: 'transparent', border: 0, cursor: 'pointer', padding: 0 }}><Wordmark size="sm"/></button>
        </div>
        <div className="t-mono muted" style={{ marginBottom: 10, fontSize: 11, letterSpacing:'0.1em', textTransform:'uppercase' }}>Your resume</div>
        <div style={{ marginBottom: 6, fontSize: 16, fontWeight: 500 }}>{displayTitle}</div>
        <div className="t-body-sm muted" style={{ marginBottom: 24 }}>{savedAt ? `Saved ${relTime(savedAt)}` : 'Not saved yet'}</div>

        <div className="stack-sm">
          <button className="side-action" onClick={regenerateAll}><Icon.refresh size={16}/> Regenerate everything</button>
          <button className="side-action" onClick={()=>go('survey')}><Icon.pencil size={16}/> Edit answers</button>
          <button className="side-action" onClick={duplicate}><Icon.copy size={16}/> Duplicate</button>
          <button className="side-action" onClick={rename}><Icon.pencil size={16}/> Rename</button>
          <button className="side-action danger" onClick={removeResume}><Icon.trash size={16}/> Delete</button>
        </div>

        <div className="t-mono muted" style={{ margin: '32px 0 10px', fontSize: 11, letterSpacing:'0.1em', textTransform:'uppercase' }}>AI Tools</div>
        <div className="stack-sm">
          <button className="side-action" onClick={tuneForJob} disabled={!!working}><Icon.sparkles size={16}/> Tune for a job</button>
          <button className="side-action" onClick={()=>transformAll('concise', 'Making it concise…')} disabled={!!working}><Icon.zap size={16}/> Make it concise</button>
          <button className="side-action" onClick={()=>transformAll('impactful', 'Making it impactful…')} disabled={!!working}><Icon.sparkles size={16}/> Make it impactful</button>
        </div>

        {working && (
          <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-secondary)' }}>
            <span style={{ width: 14, height: 14, border: '2px solid var(--border-default)', borderTopColor: 'var(--accent-primary)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }}/>
            {working}
          </div>
        )}
      </aside>

      <main className="scroll" style={{ padding: '40px 56px', overflowY: 'auto', maxHeight: '100vh' }}>
        <div style={{ maxWidth: 720, margin: '0 auto' }}>
          <BoringResume data={data} editable busy={busy} onEdit={onEdit}/>
        </div>
      </main>

      <aside style={{ borderLeft:'1px solid var(--border-default)', padding: '24px 20px', background:'var(--bg-surface)' }}>
        <Btn variant="primary" size="lg" style={{ width:'100%' }} iconRight={<Icon.arrowRight size={16}/>} onClick={()=>go('export')}>Export</Btn>

        <div className="t-mono muted" style={{ margin: '24px 0 12px', fontSize: 11, letterSpacing:'0.1em', textTransform:'uppercase' }}>Choose a format</div>
        <div className="stack-sm">
          <button onClick={()=>go('export')} style={{ width:'100%', background:'transparent', border:'1px solid var(--border-default)', borderRadius: 12, padding: 12, cursor:'pointer', textAlign:'left', display:'flex', gap: 12, alignItems:'center', fontFamily:'inherit' }} onMouseEnter={e=>e.currentTarget.style.borderColor='var(--border-strong)'} onMouseLeave={e=>e.currentTarget.style.borderColor='var(--border-default)'}>
            <div style={{ width: 60 }}><ResumeThumb flavor="boring"/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Boring</div>
              <div className="t-body-sm muted">Word / Docs</div>
            </div>
            <Icon.arrowRight size={14} style={{ color: 'var(--text-muted)' }}/>
          </button>
          <button onClick={()=>go('beautify')} style={{ width:'100%', background:'transparent', border:'1px solid var(--border-default)', borderRadius: 12, padding: 12, cursor:'pointer', textAlign:'left', display:'flex', gap: 12, alignItems:'center', fontFamily:'inherit' }} onMouseEnter={e=>e.currentTarget.style.borderColor='var(--border-strong)'} onMouseLeave={e=>e.currentTarget.style.borderColor='var(--border-default)'}>
            <div style={{ width: 60 }}><ResumeThumb flavor="beautify"/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Beautify</div>
              <div className="t-body-sm muted">Designed PDF</div>
            </div>
            <Icon.arrowRight size={14} style={{ color: 'var(--text-muted)' }}/>
          </button>
        </div>

        <div style={{ background:'var(--bg-sunken)', borderRadius: 12, padding: 14, marginTop: 24 }}>
          <div className="t-body-sm" style={{ fontWeight: 500, marginBottom: 4, display:'flex', alignItems:'center', gap: 6 }}><Icon.sparkles size={14}/> Hover any bullet</div>
          <div className="t-body-sm muted">To regenerate, edit, or delete it.</div>
        </div>
      </aside>

      {toast && <div className="toast toast-success">{toast}</div>}
    </div>
  );
}

// ===========================================================================
function ExportScreen({ go, resume }) {
  const data = resume || SAMPLE_RESUME;
  const [phase, setPhase] = useState('choose');
  const fileBase = (data.name || 'Resume').replace(/\s+/g, '_');
  const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');

  return (
    <div style={{ minHeight: '100%', display:'flex', alignItems:'center', justifyContent:'center', padding: 48, background: 'rgba(17,17,17,0.5)' }}>
      <div style={{ position:'absolute', inset: 0, opacity: 0.3 }}>
        <BoringResume data={data}/>
      </div>
      <div style={{ position:'relative', maxWidth: 920, width:'100%' }}>
        <button onClick={()=>go('preview')} style={{ position:'absolute', top: -16, right: -16, background:'#fff', border:'1px solid var(--border-default)', borderRadius: '50%', width: 36, height: 36, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'var(--shadow-md)' }}>
          <Icon.x size={16}/>
        </button>

        {phase === 'choose' && (
          <div className="fade-up">
            <div style={{ textAlign:'center', marginBottom: 40, color: '#fff' }}>
              <h1 className="t-h1" style={{ color:'#fff', margin: 0 }}>How do you want to ship?</h1>
              <p className="t-body-lg" style={{ color:'rgba(255,255,255,0.7)', marginTop: 8 }}>Most people end up with both. You can come back anytime.</p>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 20 }}>
              {[
                { id: 'boring', title: 'Boring', sub: 'ATS-safe .doc', features: ['Standard fonts, no formatting tricks', 'Passes ATS filters', 'Opens in Word or Google Docs', 'Free to edit forever'], cta: 'Download Word (.doc)', accent: '#1E3A8A' },
                { id: 'beautify', title: 'Beautify', sub: 'Designed PDF', features: ['Templates, colors, fonts, layout', 'Looks great in portfolios', 'Optional photo monogram', 'Live preview before download'], cta: 'Open the Beautify Studio', accent: 'var(--accent-primary)' },
              ].map(c => (
                <div key={c.id} className="card card-lg" style={{ padding: 32, background:'#fff' }}>
                  <div style={{ marginBottom: 20 }}><ResumeThumb flavor={c.id}/></div>
                  <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 4 }}>
                    <h2 className="t-h2" style={{ margin: 0 }}>{c.title}</h2>
                    <span className="t-mono muted" style={{ color: c.accent }}>{c.sub}</span>
                  </div>
                  <ul style={{ marginTop: 20, paddingLeft: 0, listStyle:'none' }}>
                    {c.features.map(f => (
                      <li key={f} style={{ display:'flex', gap: 10, padding: '7px 0', fontSize: 14, color:'var(--text-secondary)' }}>
                        <Icon.check size={16} style={{ color: c.accent, flexShrink: 0, marginTop: 2 }}/> {f}
                      </li>
                    ))}
                  </ul>
                  <Btn
                    variant={c.id === 'beautify' ? 'primary' : 'secondary'}
                    size="lg"
                    style={{ width:'100%', marginTop: 16, background: c.id === 'beautify' ? undefined : c.accent, color: c.id === 'beautify' ? undefined : '#fff', borderColor: c.id === 'beautify' ? undefined : c.accent }}
                    onClick={()=>{ if (c.id === 'beautify') go('beautify'); else { downloadDoc(data); setPhase('done'); } }}
                    icon={c.id === 'boring' ? <Icon.download size={16}/> : undefined}
                    iconRight={c.id === 'beautify' ? <Icon.arrowRight size={16}/> : undefined}
                  >
                    {c.cta}
                  </Btn>
                </div>
              ))}
            </div>
          </div>
        )}

        {phase === 'done' && (
          <div className="card card-lg fade-up" style={{ maxWidth: 460, margin:'0 auto', background:'#fff', padding: 40, textAlign:'center' }}>
            <div style={{ width: 64, height: 64, borderRadius:'50%', background:'rgba(22,163,74,0.12)', color:'var(--success)', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom: 20 }}>
              <Icon.check size={32}/>
            </div>
            <h2 className="t-h2" style={{ margin: 0 }}>Downloaded.</h2>
            <p className="t-body secondary" style={{ marginTop: 8, marginBottom: 24 }}>Open it in Word, or upload it to Google Drive to edit as a Doc.</p>
            <div style={{ background:'var(--bg-sunken)', padding: 12, borderRadius: 8, marginBottom: 20, display:'flex', alignItems:'center', gap: 8, justifyContent:'space-between' }}>
              <span className="t-mono" style={{ fontSize: 12, color:'var(--text-secondary)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>Resumerush_{fileBase}_{date}.doc</span>
            </div>
            <div style={{ display:'flex', gap: 8, flexDirection:'column' }}>
              <Btn variant="primary" size="lg" icon={<Icon.download size={16}/>} style={{ width:'100%' }} onClick={()=>downloadDoc(data)}>Download again</Btn>
              <Btn variant="text" onClick={()=>go('preview')}>Back to my resume</Btn>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}


// ===========================================================================
function DashboardScreen({ go, user }) {
  const [resumes, setResumes] = useState(null);
  const [menuId, setMenuId] = useState(null);
  const [survey, setSurvey] = useState(null);
  const displayName = (user?.user_metadata?.full_name?.split(' ')[0]) || user?.email?.split('@')[0] || 'there';

  const load = () => {
    window.RR.db.list().then(setResumes).catch(() => setResumes([]));
    window.RR.survey?.get().then(setSurvey).catch(() => {});
  };
  useEffect(() => { load(); }, []);

  const signOut = async () => {
    try { await window.RR?.auth?.signOut(); } catch (e) { /* ignore */ }
    go('landing');
  };
  const rename = async (r) => {
    const next = window.prompt('Rename this resume:', r.title);
    if (next == null || !next.trim()) return;
    await window.RR.db.rename(r.id, next.trim()); setMenuId(null); load();
  };
  const duplicate = async (r) => { await window.RR.db.duplicate(r.id); setMenuId(null); load(); };
  const remove = async (r) => {
    if (!window.confirm(`Delete "${r.title}"? This cannot be undone.`)) return;
    await window.RR.db.remove(r.id); setMenuId(null); load();
  };
  const discardSurvey = async () => { await window.RR.survey?.clear(); setSurvey(null); };

  return (
    <div style={{ minHeight: '100%', background: 'var(--bg-canvas)' }} onClick={() => setMenuId(null)}>
      <nav style={{ padding:'18px 32px', borderBottom:'1px solid var(--border-default)', display:'flex', alignItems:'center', justifyContent:'space-between', background:'var(--bg-canvas)' }}>
        <Wordmark size="sm"/>
        <div style={{ display:'flex', alignItems:'center', gap: 12 }}>
          <Btn variant="text" size="sm" onClick={signOut}>Sign out</Btn>
          <Avatar name={user?.user_metadata?.full_name || displayName} size={32}/>
        </div>
      </nav>

      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '40px 32px' }}>
        <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom: 32 }}>
          <div>
            <h1 className="t-h1" style={{ margin: 0 }}>Welcome back, {displayName}.</h1>
            <p className="t-body-lg secondary" style={{ marginTop: 8, marginBottom: 0 }}>
              {resumes == null ? 'Loading your resumes…'
                : resumes.length === 0 ? 'Let’s build your first resume.'
                : `${resumes.length} resume${resumes.length === 1 ? '' : 's'} saved.`}
            </p>
          </div>
          <Btn variant="primary" size="lg" icon={<Icon.plus size={16}/>} onClick={()=>go('welcome')}>New resume</Btn>
        </div>

        {/* Resume-in-progress banner (real autosaved progress) */}
        {survey && typeof survey.progress === 'number' && survey.progress < 100 && (
          <div className="card" style={{ background:'rgba(var(--accent-rgb),0.06)', border:'1px solid rgba(var(--accent-rgb),0.2)', marginBottom: 32, display:'flex', alignItems:'center', gap: 16 }}>
            <div style={{ width: 36, height: 36, borderRadius:'50%', background:'var(--accent-primary)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.sparkles size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 500, fontSize: 15 }}>You're {survey.progress}% through a survey.</div>
              <div className="t-body-sm muted">{survey.label || 'Pick up where you left off'}</div>
            </div>
            <Btn variant="text" size="sm" onClick={discardSurvey}>Discard</Btn>
            <Btn variant="primary" size="sm" onClick={()=>go('survey', { resume: true })} iconRight={<Icon.arrowRight size={14}/>}>Resume survey</Btn>
          </div>
        )}

        {resumes == null && (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '80px 0' }}>
            <span style={{ width: 28, height: 28, border: '3px solid var(--border-default)', borderTopColor: 'var(--accent-primary)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }}/>
          </div>
        )}

        {resumes != null && resumes.length === 0 && (
          <div className="card card-lg" style={{ textAlign: 'center', padding: '64px 32px' }}>
            <img src="assets/brand/icon.png" alt="Resumerush" style={{ width: 64, height: 64, borderRadius: 18, display: 'block', margin: '0 auto 24px' }}/>
            <h2 className="t-h2" style={{ margin: 0 }}>No resumes yet.</h2>
            <p className="t-body-lg secondary" style={{ marginTop: 8, marginBottom: 24, maxWidth: 420, marginInline: 'auto' }}>
              Answer about 30 quick questions and we’ll write a recruiter-ready resume in a couple of minutes.
            </p>
            <Btn variant="primary" size="lg" icon={<Icon.plus size={16}/>} onClick={()=>go('welcome')}>Create your first resume</Btn>
          </div>
        )}

        {resumes != null && resumes.length > 0 && (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(250px, 1fr))', gap: 20 }}>
            {resumes.map(r => (
              <div key={r.id} className="card card-hoverable" style={{ padding: 16, cursor:'pointer', position: 'relative' }} onClick={(e)=>{ e.stopPropagation(); go('preview', { resumeId: r.id }); }}>
                <div style={{ marginBottom: 12 }}><ResumeThumb flavor="boring"/></div>
                <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap: 8 }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 15, marginBottom: 2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{r.title || 'Untitled resume'}</div>
                    <div className="t-body-sm muted" style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{[r.target_role, relTime(r.updated_at)].filter(Boolean).join(' · ')}</div>
                  </div>
                  <button style={{ background:'transparent', border:0, cursor:'pointer', color:'var(--text-muted)', padding: 4 }} onClick={e=>{ e.stopPropagation(); setMenuId(menuId === r.id ? null : r.id); }}><Icon.more size={16}/></button>
                </div>
                {menuId === r.id && (
                  <div onClick={e=>e.stopPropagation()} style={{ position:'absolute', top: 44, right: 12, zIndex: 20, background:'var(--bg-surface)', border:'1px solid var(--border-default)', borderRadius: 10, boxShadow:'var(--shadow-md)', padding: 4, minWidth: 140 }}>
                    <button className="side-action" onClick={()=>rename(r)}><Icon.pencil size={14}/> Rename</button>
                    <button className="side-action" onClick={()=>duplicate(r)}><Icon.copy size={14}/> Duplicate</button>
                    <button className="side-action danger" onClick={()=>remove(r)}><Icon.trash size={14}/> Delete</button>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {resumes != null && resumes.length > 0 && (
          <div style={{ marginTop: 56, paddingTop: 32, borderTop:'1px solid var(--border-default)' }}>
            <div className="t-body-sm muted">You're on the <strong style={{ color:'var(--text-primary)' }}>Free</strong> plan — {resumes.length} resume{resumes.length === 1 ? '' : 's'} saved.</div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { GeneratingScreen, PreviewScreen, ExportScreen, DashboardScreen });
