/* global React */
const { useState: useRBState } = React;

// ─────────────────────────────────────────────────────────────
// RESUME BUILDER — collects an actor's full profile and headshot,
// generates a print-ready acting resume (CentreStage-branded or
// white-label), and notifies the agency via Formspree with all
// details + uploaded files.
// ─────────────────────────────────────────────────────────────

const RESUMEBUILDER_FORMSPREE = 'https://formspree.io/f/mqpzrnvz';

const emptyCredit = () => ({ production: '', role: '', company: '', year: '' });
const emptyTraining = () => ({ course: '', provider: '', year: '' });

function sendResumeBuilder(data) {
  if (!RESUMEBUILDER_FORMSPREE || RESUMEBUILDER_FORMSPREE.includes('YOUR_FORM_ID')) return Promise.resolve();
  const fd = new FormData();
  fd.append('_subject', `Resume Builder submission · ${data.name}`);
  fd.append('_replyto', data.email);
  fd.append('Name', data.name);
  fd.append('Email', data.email);
  fd.append('Phone', data.phone);
  fd.append('Location', data.location);
  fd.append('Template', data.branded ? 'CentreStage branded' : 'White-label / unbranded');
  fd.append('Height', data.height);
  fd.append('Weight / build', data.weight);
  fd.append('Chest / bust', data.chest);
  fd.append('Waist', data.waist);
  fd.append('Hips', data.hips);
  fd.append('Dress / suit size', data.dressSuit);
  fd.append('Shoe size', data.shoe);
  fd.append('Hair colour', data.hair);
  fd.append('Eye colour', data.eyes);
  fd.append('Vocal range', data.vocalRange);
  fd.append('Special skills', data.skills);
  fd.append('Additional notes', data.notes);
  fd.append('Production credits', data.credits.filter(c => c.production).map(c => `${c.production} — ${c.role}${c.company ? ' — ' + c.company : ''}${c.year ? ' (' + c.year + ')' : ''}`).join('\n') || '(none listed)');
  fd.append('Training', data.training.filter(t => t.course).map(t => `${t.course}${t.provider ? ' — ' + t.provider : ''}${t.year ? ' (' + t.year + ')' : ''}`).join('\n') || '(none listed)');
  if (data.headshotFile) fd.append('headshot', data.headshotFile, data.headshotFile.name);
  if (data.previousResumeFile) fd.append('previous_resume', data.previousResumeFile, data.previousResumeFile.name);
  return fetch(RESUMEBUILDER_FORMSPREE, { method: 'POST', headers: { Accept: 'application/json' }, body: fd })
    .catch((err) => console.error('Formspree resume builder submit failed:', err));
}

// ── Repeatable row group ─────────────────────────────────────
const RowGroup = ({ heading, hint, rows, setRows, fields, addLabel, emptyRow }) => (
  <div>
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{heading}</div>
    </div>
    {hint && <p style={{ fontSize: 13, color: 'var(--mid)', margin: '0 0 18px' }}>{hint}</p>}
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {rows.map((row, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: fields.map(f => f.w || '1fr').join(' ') + ' auto', gap: 16, alignItems: 'end' }}>
          {fields.map((f) => (
            <TextField key={f.key} label={f.label} value={row[f.key]}
              onChange={(v) => setRows(rows.map((r, ri) => ri === i ? { ...r, [f.key]: v } : r))} />
          ))}
          <button type="button" onClick={() => setRows(rows.filter((_, ri) => ri !== i))}
            style={{ height: 44, background: 'transparent', border: '1px solid var(--hairline)', color: 'var(--mid)', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', padding: '0 14px' }}>
            Remove
          </button>
        </div>
      ))}
    </div>
    <button type="button" onClick={() => setRows([...rows, emptyRow()])}
      style={{ marginTop: 16, background: 'transparent', border: '1px dashed var(--ink)', color: 'var(--ink)', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', padding: '12px 18px' }}>
      + {addLabel}
    </button>
  </div>
);

// ── Printable resume ─────────────────────────────────────────
const ResumePrint = ({ data }) => {
  const stat = (label, v) => v ? <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid #ddd' }}><span style={{ color: '#666' }}>{label}</span><span style={{ fontWeight: 700 }}>{v}</span></div> : null;
  const credits = data.credits.filter(c => c.production);
  const training = data.training.filter(t => t.course);
  return (
    <div className="rb-print-page" style={{ width: '210mm', minHeight: '297mm', margin: '0 auto', background: '#fff', color: '#0a0a0a', padding: '18mm', fontFamily: 'Georgia, serif', boxSizing: 'border-box' }}>
      <div style={{ display: 'flex', gap: '10mm', borderBottom: '2px solid #0a0a0a', paddingBottom: '8mm', marginBottom: '8mm' }}>
        {data.headshotUrl && <img src={data.headshotUrl} alt="Headshot" style={{ width: '38mm', height: '48mm', objectFit: 'cover', border: '1px solid #0a0a0a' }} />}
        <div style={{ flex: 1 }}>
          {data.branded && (
            <img src={(window.__resources && window.__resources.logoBlack) || "assets/logo/CentreStage-Solid-Black.png"} alt="CentreStage Agency" style={{ height: '9mm', marginBottom: '4mm', display: 'block' }} />
          )}
          <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.01em' }}>{data.name || 'Your Name'}</div>
          <div style={{ fontSize: 12, color: '#444', marginTop: 6, lineHeight: 1.6 }}>
            {data.phone}{data.phone && data.email ? ' · ' : ''}{data.email}<br/>
            {data.location}
          </div>
          {data.branded && (
            <div style={{ marginTop: 12, fontSize: 12, fontWeight: 700, letterSpacing: '0.04em' }}>
              Represented by CentreStage Pty Ltd<br/>
              <span style={{ fontWeight: 400, color: '#444' }}>Unit 2, 255 Hamilton Highway, Fyansford VIC · www.centrestageagency.org.au</span>
            </div>
          )}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10mm' }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>Vital statistics</div>
          {stat('Height', data.height)}
          {stat('Weight / build', data.weight)}
          {stat('Chest / bust', data.chest)}
          {stat('Waist', data.waist)}
          {stat('Hips', data.hips)}
          {stat('Dress / suit size', data.dressSuit)}
          {stat('Shoe size', data.shoe)}
          {stat('Hair colour', data.hair)}
          {stat('Eye colour', data.eyes)}
          {data.vocalRange && stat('Vocal range', data.vocalRange)}
        </div>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>Training</div>
          {training.length ? training.map((t, i) => (
            <div key={i} style={{ padding: '6px 0', borderBottom: '1px solid #ddd', fontSize: 13 }}>
              <strong>{t.course}</strong>{t.provider ? `, ${t.provider}` : ''}{t.year ? ` (${t.year})` : ''}
            </div>
          )) : <div style={{ fontSize: 13, color: '#888' }}>—</div>}

          {data.skills && (
            <React.Fragment>
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', margin: '16px 0 8px' }}>Special skills</div>
              <p style={{ fontSize: 13, lineHeight: 1.55, margin: 0 }}>{data.skills}</p>
            </React.Fragment>
          )}
        </div>
      </div>

      <div style={{ marginTop: '10mm' }}>
        <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>Production credits</div>
        {credits.length ? (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid #0a0a0a' }}>
                {['Production', 'Role', 'Company', 'Year'].map(h => <th key={h} style={{ textAlign: 'left', padding: '6px 8px 6px 0', fontWeight: 700 }}>{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {credits.map((c, i) => (
                <tr key={i} style={{ borderBottom: '1px solid #ddd' }}>
                  <td style={{ padding: '6px 8px 6px 0' }}>{c.production}</td>
                  <td style={{ padding: '6px 8px 6px 0' }}>{c.role}</td>
                  <td style={{ padding: '6px 8px 6px 0' }}>{c.company}</td>
                  <td style={{ padding: '6px 8px 6px 0' }}>{c.year}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : <div style={{ fontSize: 13, color: '#888' }}>—</div>}
      </div>

      {data.notes && (
        <div style={{ marginTop: '10mm' }}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>Additional information</div>
          <p style={{ fontSize: 13, lineHeight: 1.55, margin: 0 }}>{data.notes}</p>
        </div>
      )}
      {data.branded && (
        <div style={{ marginTop: '12mm', paddingTop: '4mm', borderTop: '1px solid #ccc', fontSize: 11, color: '#666', textAlign: 'center' }}>
          www.centrestageagency.org.au
        </div>
      )}
    </div>
  );
};

// ── Screen ────────────────────────────────────────────────────
const ResumeBuilderScreen = ({ navigate }) => {
  const [name, setName] = useRBState('');
  const [email, setEmail] = useRBState('');
  const [phone, setPhone] = useRBState('');
  const [location, setLocation] = useRBState('');
  const [branded, setBranded] = useRBState(true);
  const [headshot, setHeadshot] = useRBState(null);
  const [prevResume, setPrevResume] = useRBState(null);
  const [height, setHeight] = useRBState('');
  const [weight, setWeight] = useRBState('');
  const [chest, setChest] = useRBState('');
  const [waist, setWaist] = useRBState('');
  const [hips, setHips] = useRBState('');
  const [dressSuit, setDressSuit] = useRBState('');
  const [shoe, setShoe] = useRBState('');
  const [hair, setHair] = useRBState('');
  const [eyes, setEyes] = useRBState('');
  const [vocalRange, setVocalRange] = useRBState('');
  const [skills, setSkills] = useRBState('');
  const [notes, setNotes] = useRBState('');
  const [credits, setCredits] = useRBState([emptyCredit()]);
  const [training, setTraining] = useRBState([emptyTraining()]);
  const [consent, setConsent] = useRBState(false);
  const [extracting, setExtracting] = useRBState(false);
  const [extracted, setExtracted] = useRBState(false);
  const [status, setStatus] = useRBState('form'); // form | preview
  const [error, setError] = useRBState(null);
  const [sent, setSent] = useRBState(false);

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const ready = !!name.trim() && emailValid && !!phone.trim() && !!location.trim() && !!headshot && consent;

  const headshotUrl = headshot ? URL.createObjectURL(headshot.file || headshot) : null;

  function fileToBase64(f) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result.split(',')[1]);
      reader.onerror = () => reject(reader.error);
      reader.readAsDataURL(f);
    });
  }
  function guessType(n) {
    const ext = (n || '').toLowerCase().split('.').pop();
    if (ext === 'pdf') return 'application/pdf';
    if (ext === 'doc') return 'application/msword';
    if (ext === 'docx') return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    return 'application/octet-stream';
  }

  const handlePrevResume = async (f) => {
    setPrevResume(f);
    if (!f) return;
    setExtracting(true);
    setExtracted(false);
    try {
      const realFile = f.file || f;
      const base64 = await fileToBase64(realFile);
      const res = await fetch('/api/extract-resume', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ filename: realFile.name, filetype: guessType(realFile.name), fileData: base64 }),
      });
      if (!res.ok) throw new Error('Server responded with ' + res.status);
      const data = await res.json();
      if (data.name && !name) setName(data.name);
      if (data.email && !email) setEmail(data.email);
      if (data.phone && !phone) setPhone(data.phone);
      if (data.location && !location) setLocation(data.location);
      if (data.height) setHeight(data.height);
      if (data.weight) setWeight(data.weight);
      if (data.chest) setChest(data.chest);
      if (data.waist) setWaist(data.waist);
      if (data.hips) setHips(data.hips);
      if (data.dressSuit) setDressSuit(data.dressSuit);
      if (data.shoe) setShoe(data.shoe);
      if (data.hair) setHair(data.hair);
      if (data.eyes) setEyes(data.eyes);
      if (data.vocalRange) setVocalRange(data.vocalRange);
      if (data.skills) setSkills((s) => s ? s : data.skills);
      if (data.notes) setNotes((n) => n ? n : data.notes);
      if (Array.isArray(data.credits) && data.credits.length) {
        setCredits((c) => (c.length === 1 && !c[0].production) ? data.credits : [...c, ...data.credits]);
      }
      if (Array.isArray(data.training) && data.training.length) {
        setTraining((t) => (t.length === 1 && !t[0].course) ? data.training : [...t, ...data.training]);
      }
      setExtracted(true);
    } catch (err) {
      console.error(err);
      setError('We could not read that resume automatically — please enter your credits and training below.');
    } finally {
      setExtracting(false);
    }
  };

  const buildData = () => ({
    name: name.trim(), email: email.trim(), phone: phone.trim(), location: location.trim(), branded,
    headshotUrl, headshotFile: headshot ? (headshot.file || headshot) : null,
    previousResumeFile: prevResume ? (prevResume.file || prevResume) : null,
    height, weight, chest, waist, hips, dressSuit, shoe, hair, eyes, vocalRange, skills, notes,
    credits, training,
  });

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!name.trim())   return setError('Please enter your name to continue.');
    if (!emailValid)    return setError('Please enter a valid email address to continue.');
    if (!phone.trim())  return setError('Please enter a phone number to continue.');
    if (!location.trim()) return setError('Please enter your location to continue.');
    if (!headshot)      return setError('Please upload a headshot to continue.');
    if (!consent)       return setError('Please tick the consent box to continue.');

    const data = buildData();
    sendResumeBuilder(data).finally(() => setSent(true));
    setStatus('preview');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  if (status === 'preview') {
    const data = buildData();
    return (
      <main data-screen-label="Resume Builder · Preview">
        <style>{`@media print { body * { visibility: hidden; } .rb-print-page, .rb-print-page * { visibility: visible; } .rb-print-page { position: absolute; top: 0; left: 0; margin: 0; box-shadow: none; } @page { size: A4; margin: 0; } }`}</style>
        <section className="rb-hide-print" style={{ maxWidth: 1100, margin: '0 auto', padding: '56px 48px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 16 }}>
            <Eyebrow style={{ color: 'var(--mid)' }}>Resume Builder <Slash /> Preview</Eyebrow>
            <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
          </div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(36px, 5vw, 64px)', letterSpacing: '-0.03em', lineHeight: 1, margin: '24px 0 12px', textWrap: 'balance' }}>
            Your resume is ready.
          </h1>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink)', maxWidth: '72ch', margin: '0 0 8px' }}>
            Review it below, then use your browser's print dialog to save it as a PDF — choose "Save as PDF" as the destination.
            {sent ? ' Our team has also been notified of your submission.' : ''}
          </p>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', margin: '32px 0 48px' }}>
            <button type="button" onClick={() => window.print()} className="cs-btn">Save as PDF <span style={{ marginLeft: 8 }}>→</span></button>
            <Button variant="secondary" onClick={(e) => { e.preventDefault(); setStatus('form'); window.scrollTo({ top: 0, behavior: 'smooth' }); }}>← Edit details</Button>
          </div>
        </section>
        <div style={{ background: '#e8e8e8', padding: '40px 0' }}>
          <ResumePrint data={data} />
        </div>
      </main>
    );
  }

  return (
    <main data-screen-label="Resume Builder">
      {/* Hero */}
      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '56px 48px 96px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 48 }}>
          <Eyebrow style={{ color: 'var(--mid)' }}>Free tool <Slash /> Open to everyone</Eyebrow>
          <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
          <span className="cs-mono" style={{ color: 'var(--mid)' }}>PDF export</span>
        </div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(48px, 8vw, 132px)', letterSpacing: '-0.035em', lineHeight: 0.9, margin: 0, color: 'var(--ink)', textWrap: 'balance' }}>
          Build your<br/>acting resume.
        </h1>
        <div style={{ marginTop: 56, display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 64, alignItems: 'flex-end' }}>
          <p style={{ fontSize: 21, lineHeight: 1.5, color: 'var(--ink)', margin: 0, maxWidth: '54ch' }}>
            Enter your details, sizes, training and credits once, and generate a clean, industry-standard resume as a PDF — with CentreStage Agency branding, or as a plain, white-label copy. Free for every performer.
          </p>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
            <Button href="#builder" onClick={(e) => { e.preventDefault(); document.getElementById('rb-form')?.scrollIntoView({ behavior: 'smooth' }); }}>Build my resume · free</Button>
          </div>
        </div>
      </section>

      <Hairline />

      {/* Form */}
      <section id="rb-form" style={{ maxWidth: 1100, margin: '0 auto', padding: '96px 48px 120px' }}>
        <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 40 }}>

          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>Your details</div>
            <p style={{ fontSize: 14, color: 'var(--mid)', margin: '0 0 24px' }}>We email your resume-builder submission to our team. We never share your details.</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }}>
              <TextField label="Full name" required value={name} onChange={setName} placeholder="First and last name" autoComplete="name" />
              <TextField label="Email address" type="email" required value={email} onChange={setEmail} placeholder="you@example.com" autoComplete="email" />
              <TextField label="Phone number" type="tel" required value={phone} onChange={setPhone} placeholder="04XX XXX XXX" autoComplete="tel" />
              <TextField label="Location" required value={location} onChange={setLocation} placeholder="e.g. Geelong, VIC" />
            </div>
          </div>

          <Hairline />

          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>Template</div>
            <TogglePair label="Choose your resume template" value={branded ? 'branded' : 'white'}
              onChange={(v) => setBranded(v === 'branded')}
              options={[{ key: 'branded', label: 'CentreStage branded' }, { key: 'white', label: 'White-label / unbranded' }]} />
          </div>

          <Hairline />

          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>Headshot &amp; previous resume</div>
            <p style={{ fontSize: 14, color: 'var(--mid)', margin: '0 0 24px' }}>Upload your headshot for the resume. Optionally attach a previous resume for our reference — this won't be used to auto-fill the form.</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }}>
              <FileUpload label="Headshot" required accept="image/*" hint="JPG or PNG" value={headshot} onChange={setHeadshot} />
              <FileUpload label="Previous resume" accept=".pdf,.doc,.docx" hint="Optional · PDF, DOC or DOCX · auto-fills your credits below" value={prevResume} onChange={handlePrevResume} />
            </div>
            {extracting && (
              <p style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', margin: '16px 0 0' }}>Reading your previous resume and pre-filling your details…</p>
            )}
            {extracted && !extracting && (
              <p style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', margin: '16px 0 0' }}>✓ Pre-filled from your previous resume — review the fields below and adjust as needed.</p>
            )}
          </div>

          <Hairline />

          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>Vital statistics</div>
            <p style={{ fontSize: 14, color: 'var(--mid)', margin: '0 0 24px' }}>All optional, but standard on industry resumes.</p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28 }}>
              <TextField label="Height" value={height} onChange={setHeight} placeholder="e.g. 175cm" />
              <TextField label="Weight / build" value={weight} onChange={setWeight} placeholder="e.g. Athletic" />
              <TextField label="Chest / bust" value={chest} onChange={setChest} placeholder="e.g. 96cm" />
              <TextField label="Waist" value={waist} onChange={setWaist} placeholder="e.g. 80cm" />
              <TextField label="Hips" value={hips} onChange={setHips} placeholder="e.g. 98cm" />
              <TextField label="Dress / suit size" value={dressSuit} onChange={setDressSuit} placeholder="e.g. 10 / 40R" />
              <TextField label="Shoe size" value={shoe} onChange={setShoe} placeholder="e.g. AU 9" />
              <TextField label="Hair colour" value={hair} onChange={setHair} placeholder="e.g. Brown" />
              <TextField label="Eye colour" value={eyes} onChange={setEyes} placeholder="e.g. Green" />
            </div>
            <div style={{ marginTop: 28 }}>
              <TextField label="Vocal range" value={vocalRange} onChange={setVocalRange} placeholder="e.g. Alto, A3–F5" hint="if applicable" />
            </div>
          </div>

          <Hairline />

          <RowGroup heading="Production credits" hint="Add every production, role, company and year you'd like included."
            rows={credits} setRows={setCredits} addLabel="Add credit" emptyRow={emptyCredit}
            fields={[{ key: 'production', label: 'Production', w: '1.4fr' }, { key: 'role', label: 'Role', w: '1fr' }, { key: 'company', label: 'Company / Director', w: '1.2fr' }, { key: 'year', label: 'Year', w: '0.6fr' }]} />

          <Hairline />

          <RowGroup heading="Training & acting experience" hint="Courses, coaches, institutions and workshops."
            rows={training} setRows={setTraining} addLabel="Add training" emptyRow={emptyTraining}
            fields={[{ key: 'course', label: 'Course / Training', w: '1.4fr' }, { key: 'provider', label: 'Provider / Coach', w: '1.2fr' }, { key: 'year', label: 'Year', w: '0.6fr' }]} />

          <Hairline />

          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>Skills & anything else</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 24, marginTop: 18 }}>
              <div>
                <FieldLabel hint="accents, dialects, dance, sport, instruments, etc.">Special skills</FieldLabel>
                <textarea value={skills} onChange={(e) => setSkills(e.target.value)} rows={3}
                  style={{ width: '100%', padding: '16px 0', background: 'transparent', border: 0, borderBottom: '1px solid var(--ink)', fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.5, color: 'var(--ink)', resize: 'vertical', outline: 'none' }} />
              </div>
              <div>
                <FieldLabel hint="anything else you'd like included on your resume">Additional information</FieldLabel>
                <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3}
                  style={{ width: '100%', padding: '16px 0', background: 'transparent', border: 0, borderBottom: '1px solid var(--ink)', fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.5, color: 'var(--ink)', resize: 'vertical', outline: 'none' }} />
              </div>
            </div>
          </div>

          <Hairline />

          <ConsentCheckbox
            value={consent} onChange={setConsent}
            label={<span>I consent to CentreStage Agency receiving these details to generate my resume and to being contacted about it. <span style={{ color: 'var(--mid)' }}>We never share your details with third parties.</span></span>}
          />

          {error && (
            <div style={{ border: '1px solid var(--ink)', padding: '18px 20px', fontSize: 14, lineHeight: 1.55, color: 'var(--ink)' }}>{error}</div>
          )}

          <div>
            <button type="submit" className="cs-btn" style={{ width: '100%', justifyContent: 'center', height: 56, opacity: ready ? 1 : 0.4, pointerEvents: ready ? 'auto' : 'none' }}>
              Generate my resume <span style={{ marginLeft: 10 }}>→</span>
            </button>
          </div>
        </form>
      </section>
    </main>
  );
};

Object.assign(window, { ResumeBuilderScreen });
